简体   繁体   中英

Displaying message on Ajax success

I have the following piece of javascript which passes data to my database and then returns a success message.

At the moment on success the button fades out and hides perfectly as it should, but the success message doesn't display.

$(document).ready(function () {
    $('form.user_status').submit(function () {
        var userna = $(this).find("[name='userna']").val();
        var joborder_id = $(this).find("[name='joborder_id']").val();
        var user_email = $(this).find("[name='user_email']").val();
        var app_status = $(this).find("[name='app_status']").val();
        // ...
        $.ajax({
            type: "POST",
            url: "user_status.php",
            data: {
                userna: userna,
                joborder_id: joborder_id,
                user_email: user_email,
                app_status: app_status
            },
            success: function () {
                $('form.user_status').hide(function () {
                    $('div.success').fadeOut();
                });
                success = 'Status changed';
            }
        });
        return false;
    });
});

the html where the success message should be dsplayed

<div class="success" style="display: none;"></div>

You don't actually do anything with the success string.

Why not go:

success: function(data){
    $('form.user_status').hide();
    $('div.success').html('Status changed').delay(1000).fadeOut();
}

UNLESS Your success div is inside your form. If so then your div will disappear immediately with the form. Which is a bit silly. Note I've added data - you need to pass what you've returned (or how will you use the data if you wanted to?)

Display none means by default obviously your div is invisible. fadeout is just going to keep it invisible surely?

Edit: So I have removed a bunch of stuff. If you are just looking to change what is written in the div then make it disappear. You insert html then fadeout and it'll take care of it for you.

JSFiddle

Delay is there to give the user a second to read it.

In jQuery, ajax method has success method called when ajax response succeed. As ajax is asynchronous, after executing $.ajax, the compilation cursor moves to next line. Whatever code you write in success method will gets executed immediately after ajax success. you need to change DOM in success method, not a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM