简体   繁体   中英

ajax success callback not working

So I have this JavaScript which works fine up to the $.ajax({ . Then it just hangs on the loader and nothing happens.

$(function() {
$('.com_submit').click(function() {
    var comment = $("#comment").val();
    var user_id = $("#user_id").val();
    var perma_id = $("#perma_id").val();
    var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
    if(comment=='') {
        alert('Please Give Valid Details');
    }
    else {
        $("#flash").show();
        $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
        $.ajax({
            type: "POST",
            url: "commentajax.php",
            data: dataString,
            cache: false,
            success: function(html){
        alert('This works');
                $("ol#update").append(html);
                $("ol#update li:first").fadeIn("slow");
                $("#flash").hide();
            }
        });
    }
    return false;
}); 
});

Try replacing:

var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;

with:

var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };

in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success . The complete event is triggered even in the case of an exception.

Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.

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