Nate Norman
Nate Norman

Reputation: 129

replace a div tag using JQuery after form submit

I am submitting a form without leaving my page through a post call Using JQuery.

After I submit I want to replace the div with the form in it with a thank you message. The problem is the message is showing before I submit and not replacing, below is my code.

$(document).ready(function() {
            //When the form with id="myform" is submitted...
            $("#myform").submit(function() {
                //Send the serialized data to mailer.php.
                $.post("mailer.php", $("#myform").serialize(),
                    //Take our repsonse, and replace whatever is in the "formResponse"
                    //div with it.
                    function(data) {
                        $("#formResponse").html(data);
                    }
                );
                return false;
            });
        });

and the HTML

<div data-role="content">
<form id="myform">
  <div data-role="fieldcontain">
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" value=""  />
</div>
<div data-role="fieldcontain">
  <label for="email">Email:</label>
  <input type="email" name="email" id="email" value=""  />
</div>
<div data-role="fieldcontain">
  <label for="company">Company Name:</label>
  <input type="text" name="company" id="company" value=""  />
</div>        
<input type="submit" name="submit" value="Submit" data-icon="star" data-theme="b" />
</form>

</div>
<div data-role="content" div id="formResponse">
    thank you, your quote has been received and you will hear back from us shortly.
    </div>

Upvotes: 2

Views: 2233

Answers (2)

Try replacing your following code:

<div data-role="content" div id="formResponse">

for this one:

<div data-role="content" style="display:none" id="formResponse">

and then replace your following javascript function:

function(data) {
  $("#formResponse").html(data);
}

for this one:

function(data) {
  $("#myForm").html( $("#formResponse").html() );
}

UPDATE:
If you just want to show the result obtained from the ajax call, instead of showing the content of the #formResponse div, just remove the #formResponse div at all, and just do the following:

function(data) {
  $("#myForm").html( data );
}

UPDATE 2:
You can also hide the form div and show the "thank you" div, like this:

function(data) {
  $("#myForm").hide('slide', function() {$("#formResponse").show('slide');});
}

Upvotes: 2

Abubakkar
Abubakkar

Reputation: 15664

use success(data) A callback function that is executed if the request succeeds.

Upvotes: 1

Related Questions