jQuery - replace contact form with 'thanks message'
I have a contact form which performs a PHP action. The contact form is connected with validation engine in jQuery. If messege is sent correctly I simply include PHP file with thanks message - require_once('success.php');
. After sending message I would like to replace contact form with thanks message without reloading the whole page. Please give me some advices how to do it.
Here is my html:
<div id="contactForm">
<form id="expertForm" class="formular" method="post" action="send.php">
<fieldset>
<label>
<input name="email"
id="email"
class="required email"
type="text"
size="40"/>
</label>
<p>
<textarea name="body" id="body" rows="5" cols="50" class="required"></textarea>
</p>
</fieldset>
<input class开发者_如何转开发="submit"
type="image"
src="../images/btn-send.png"/>
</form>
</div>
<script type="text/javascript">
$("#expertForm").validate();
</script>
In send.php
I have:
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
require_once('success.php');
}
You can see an almost working demo here http://jsfiddle.net/v7MJA/1/
$(function(){
$("#expertForm").submit(function(e){
e.preventDefault();
if(!$(this).validate().form()) return false;
$.ajax({
url:$(this).attr('action'),
data:$(this).serialize(),
type:'post',
success:function(msg){
$("#expertForm").replaceWith(msg);
}
});
});
});
You'd better give us some code so that we could help.
Here is the theorical way: use the success
event of the jquery ajax
[ref] call:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$("#myformdiv").html("Thanks!");
}
});
assuming that your HTML markup is something like:
<div id="myformdiv">
<form>
<!-- form code here -->
</form>
</div>
Assuming I've understood your question correctly, you can use the replaceWith
method to replace the matched elements with the specified content:
$("#yourForm").replaceWith("<p>Thanks!</p>");
I'm assuming that you're doing something asynchronously to send the form data to the server, so you can just run the above code in the callback:
$.post("yourScript.php", function() {
$("#yourForm").replaceWith("<p>Thanks!</p>");
});
精彩评论