Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .submit() success or failure trigger

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!

like image 809
stewart715 Avatar asked Nov 11 '11 04:11

stewart715


People also ask

Is jQuery submit deprecated?

No, it's not deprecated! Deprecated = Not current. Obsolete = no longer available.

How do you check form is submitted or not in jQuery?

$("#something-%"). submit(function(e) { e. preventDefault(); $("#some-span"). html(data); });

How Prevent form submit in jQuery validation fails?

You need to do two things if validation fails, e. preventDefault() and to return false. This really works.

How do I stop form submit in jQuery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.


1 Answers

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.

like image 179
Idham Perdameian Avatar answered Oct 04 '22 06:10

Idham Perdameian