I am using .submit()
to submit my form over ajax periodically, but I want the user to see that the form is being saved with a spinning wheel and then 'Saved!' upon success. Is there a success
trigger for .submit()
in jQuery?
Thanks!
No, it's not deprecated! Deprecated = Not current. Obsolete = no longer available.
$("#something-%"). submit(function(e) { e. preventDefault(); $("#some-span"). html(data); });
You need to do two things if validation fails, e. preventDefault() and to return false. This really works.
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
Try this:
jQuery:
$(document).ready(function() {
$('#form').submit(function() {
var status = '<img class="loading" src="loading_detail.gif" alt="Loading..." />';
$("#ajax").after(status);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(json) {
if(json.type == 'success') {
$('#msg').css("color","green").html(json.message);
} else if(json.type == 'warning'){
$('#msg').css("color","yellow").html(json.message);
} else if(json.type == 'error'){
$('#msg').css("color","red").html(json.message);
}
$('.loading').remove();
}
})
return false;
});
});
Html:
<div id="msg"></div>
<form id="form" method="post" action="action.php" >
<input type="text" name="email" />
<input type="submit" name="submit" value="submit" /><span id="ajax"></span>
</form>
action.php :
<?php
if(isset($_POST['email'])){
$val = $_POST['email'];
switch ($val) {
case '[email protected]':
$return = array('type'=>'success', 'message'=>'This is success message!'); break;
case 'email':
$return = array('type'=>'warning', 'message'=>'This is warning message!'); break;
default:
$return = array('type'=>'error', 'message'=>'This is error message!');
}
echo json_encode($return);
}
?>
Note:
If you are submitting the form programmatically you need to call $('#form').submit()
once again but this time without arguments so that you trigger the submit event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With