A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question.

I've attempted to use the following examples without success:

  • jquery submit form and then show results in an existing div

  • Form submit in DIV using jQuery

Here's my question:

I have a situation where there is a div containing a form like this:

<div id="mydiv">
<form id="myform" method="post" action="action.php?id=1&lang=en">
...
</form>
</div>

The issue at hand are:

1) Unable to submit form results to the "mydiv" div

2) The desired outcome is to submit without refreshing the page

Unfortunately, neither 1 nor 2 work for me.

JavaScript used:

$(document).ready(function() {
  $('#myform').submit(function () {
    $.post('action.php?id=1&lang=en', 
    $('#myform').serialize(), 
    function (data, textStatus) {
        $('#mydiv').append(data);
    });
    return false;
   });  
});

Edit: I am utilizing two different files:

The main file, and the second file (containing "myform") is used within the "mydiv".

Upon submitting, the form redirects to a new page (not intended) and does not load any jQuery/JavaScript scripts (as they are in the mainfile).

Example:

FILE_1 main.php (with loaded jquery/js scripts) 

loads inside "mydiv" 

FILE_2 action.php (contains the form)

Complicated, right?


An update to my question:

I have created a basic script to showcase what I am attempting to achieve here:

divform.html

<title>test</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>

<!-- THIS SCRIPT ALLOW TO USE A DIV AS A TARGETED IFRAME -->    
<script type="text/javascript">
    /***********************************************
    * Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
    * This notice MUST stay intact for legal use
    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
    ***********************************************/

    var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
    var loadedobjects=""
    var rootdomain="http://"+window.location.hostname
    var bustcacheparameter=""

    function ajaxpage(url, containerid){
    var page_request = false
    if (window.XMLHttpRequest) // if Mozilla, Safari etc
    page_request = new XMLHttpRequest()
    else if (window.ActiveXObject){ // if IE
    try {
    page_request = new ActiveXObject("Msxml2.XMLHTTP")
    } 
    catch (e){
    try{
    page_request = new ActiveXObject("Microsoft.XMLHTTP")
    }
    catch (e){}
    }
    }
    else
    return false
    page_request.onreadystatechange=function(){
    loadpage(page_request, containerid)
    }
    if (bustcachevar) //if bust caching of external page
    bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
    page_request.open('GET', url+bustcacheparameter, true)
    page_request.send(null)
    }

    function loadpage(page_request, containerid){
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
    document.getElementById(containerid).innerHTML=page_request.responseText
    }

    function loadobjs(){
    if (!document.getElementById)
    return
    for (i=0; i<arguments.length; i++){
    var file=arguments[i]
    var fileref=""
    if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
    if (file.indexOf(".js")!=-1){ //If object is a js file
    fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", file);
    }
    else if (file.indexOf(".css")!=-1){ //If object is a css file
    fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", file);
    }
    }
    if (fileref!=""){
    document.getElementsByTagName("head").item(0).appendChild(fileref)
    loadedobjects+=file+" " //Remember this object as being already added to page
    }
    }
    }   
</script>   
</head>

<body>

<div id="centerbody" style="width: 600px; height: 300px; border: 1px solid #ccc; margin: 0 auto;">

    <div id="linkzone" style="width: 120px; height: 250px; border: 1px solid #f00; float: left; display: inline;">

    <a href="javascript:ajaxpage('action.php?i=link1', 'mydiv');">goto link1</a>
    <br>
    <a href="javascript:ajaxpage('action.php?i=link2', 'mydiv');">goto link2</a>

    </div>

    <div id="mydiv" style="width: 400px; height: 200px; border: 1px solid #000; float: right; display: inline;">
    </div>
</div>

</body>
</html>

and a php script that is loaded inside "Mydiv" / do the form thing:

action.php:

<script type="text/javascript">


    /** THIS SCRIPT IS SUPPOSED TO ALLOW A FORM SUBMITION BEING loaded in the same div, without refreshing it */
    $(document).ready(function() {
            $('#myform').submit(function () {
                $.post('action.php?i=link2', $('#myform').serialize(), function (data, textStatus) {
                     $('#mydiv').append(data);
                });
                return false;
            }); 
    });
</script>
<?
if ($_GET['i']=="link1") {
    echo "link 1";
    ?>
    <br><a href="javascript:ajaxpage('action.php?i=link2', 'mydiv');">goto link2</a>
    <?  
}
if ($_GET['i']=="link2") {
    $error="0";
    $sent="";
    if (isset($_POST['submit'])=="go") {
        if ($_POST['form_1']!=""){
            echo "good...( {$_POST['form_1']} )...<p>";
            $sent=1;
        }
        else{
            $error=1;
        }
    }
    if ($sent=="1"){
        echo "...gogogogo...  should refresh to another link...5 secs after... (inside here)";
    }
    else{
        echo "link 2";
        ?>
        <br><a href="javascript:ajaxpage('action.php?i=link1', 'mydiv');">goto link1</a>
        <form id="myform" method="post" action="action.php?i=link2">
        input zone: <input type="text" name="form_1"> <input type="submit" value="go" name="submit">    
        </form>
        <?
        if ($error=="1") {
            echo "* mandatory fields"; 
        }
    }
}
?>

You should now have a better understanding of what I am trying to accomplish. Thank you, and apologies for any confusion in my initial post as this is my first time posting and I'm still learning the ropes :)

Answer №1

$('#searchform').submit(function (event) {
  event.preventDefault(); // stop default submission behavior

  $.ajax({
    // include necessary parameters

    success: function (result) {
      // process retrieved data from ajax call
    }
  }); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

having difficulty altering a string in EJS

After passing a JSON string to my EJS page, I noticed that it displays the string with inverted commas. To resolve this issue, I am looking for a way to eliminate the inverted comma's and convert the string to UPPERCASE. Does anyone know how to achiev ...

Move data from one mysql table to another in different databases using PDO

After spending the last hour researching, I still haven't found a straightforward solution that doesn't involve complicated exports and imports. All I want to do is establish a PDO connection with two databases so that I can utilize them both in ...

What is the best way to retrieve a value from this json_decode function?

After decoding a JSON string from an API call, I have retrieved the following result. However, I am unsure how to extract the specific value labeled as "VALUE." Here is the decoded object: $obj=json_decode($json_string); print_r($obj); stdClass O ...

Creating placeholder values with keys in PHP arrays can be achieved by using the array_fill_keys

How can we programmatically generate dummy data based on a given number in PHP? For instance, if we set $var=2, the script should generate two entries in an array. If we set $var=100, it should create 100 entries following a specific format using arrays i ...

The npm command returns an error message stating "Either an insufficient amount of arguments were provided or no matching entry was found."

I'm trying to pass a custom flag from an npm script to my webpack config, but I keep encountering the following error in the logs: Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. ...

Develop a collection of data entries and add them to a database at a later time using

To track and log the users entering different subpages, I am looking to store this information in a MySQL table. The table will contain details such as userid, subpage, subpageid, and datetime. function logstore(){ global $DB, $USER, $CFG; $protocol = s ...

Hide Address with Jquery Dialog Box

How can I securely redirect a user to another page within the same website? In my specific situation, I have a form where users input information. For cancellations, they should have options available. When a user clicks the cancellation button, a dialog ...

Replace Euro symbols in JavaScript Regexp with grouping

Need assistance creating a Regex pattern for &#8203; € 14,50. After the replacement is completed, only 14,50 Can anyone provide guidance? ...

Using ext.js to make asynchronous AJAX requests

Could someone help me with a question? I have the code below that I found from a certain source: Ext.Ajax.request({ url: 'http://localhost/day1/new.php', method:'GET', params:{format:'json'}, success: this. ...

Decoding JSON data from the Twitch API

I am currently working on retrieving a user's Twitch name using json_decode and their Steam ID, but I keep encountering an error that I can't seem to resolve. Despite researching similar issues faced by other users, I haven't made any progre ...

Unlocking a Static HTML Website in a Private S3 Bucket using PHP

I have recently set up a private bucket on AWS S3, containing 4 folders labeled A, B, C, and D. Inside these folders, I have uploaded an index.html file along with JS scripts and images to create a static HTML website. On my own website (www.test.com), I ...

Node.js and TestCafe encountered a critical error: Inefficient mark-compacts were performed near the heap limit, resulting in an allocation failure. The JavaScript heap ran

While executing my test scripts in Node v14.6.0, I encountered the following problem. Here are some of the options I've tried: I attempted to increase the Node Heap Size but unfortunately had no success: export NODE_OPTIONS=--max_old_space_size=4096 ...

What Causes the Response to Vary in a Post Request?

Issue: When I use console.log(res.data), it shows different data compared to console.log(JSON.parse(res.request.response)). My Next.js application is sending a post request to an internal API. The response from the REST endpoint should contain a list obje ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

What is the best way to implement JavaScript for loading and removing content based on button clicks on a webpage?

I'm in need of a vanilla JavaScript solution (I know JQuery options exist, but I want to stick to vanilla JS for now)? Currently, I am using a simple page as a testing ground for my ongoing project. The page consists of two buttons that load HTML pag ...

AntiforgeryToken validation issue when using Ajax in ASP.NET MVC

When looking at this View: @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })) { @Html.AntiForgeryToken() <div id='calendar'></div> <script src="~/Scripts/Services/Agenda.js" ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Having trouble accessing the ng-model within ng-repeat in the controller of an AngularJS component

One approach I am considering is to use ng-model="model.ind[$index]" in order to keep track of the active tag. This way, when I click on a tag (specifically the 'a' tag), both the parentIndex and $index will be passed to my controller. Subsequent ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...