stewart715
stewart715

Reputation: 5647

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!

Upvotes: 12

Views: 50819

Answers (3)

Idham Perdameian
Idham Perdameian

Reputation: 2277

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.

Upvotes: 19

Menni
Menni

Reputation: 19

To show a spinning wheel while submitting a page, try to get a animated GIF (there are much free loading circles). This GIF implement in your page with:

class="myloadingcircle" style="display:none"

and then use jQuery:

$("form").submit(function(e) { $(".myloadingcircle").show(); });

Upvotes: 1

Blender
Blender

Reputation: 298176

You can use a manual $.post() request instead of a .submit(). The $.post() has a success callback.

You'll have to fill in the details of the $.post() (the target URL) and .serialize() your form's elements.

Upvotes: 7

Related Questions