YSFKBDY YSFKBDY - 2 months ago 9
jQuery Question

Showing message before page refresh using jQuery

I want to display ajax result message before page refresh, but something is wrong. My code is like this:

$.ajax({
cache: false,
type: "POST",
url: "@(Url.RouteUrl("DummyRequest"))",
success: function (data) {
if (data.Success) {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
setInterval(function () {
location.reload();
}, 5000);
}
else {
$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
/*setInterval(function () {
location.reload();
}, 5000);*/
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
}
});


My code is working just fine on else situation. When I tried, message appears, then after 5 secs page reloads itself. But when if situation is on, page reloads itself, however message doesn't show.

How can I solve this problem?

Answer

Its depends on response time of server.. so if response from server is late then not working correctly.. so you have to wait for AJAX response then you have to display popup and redirect. so use ajax option async: false in your ajax request. as mentioned below

$.ajax({
    cache: false,
    async: false,
    type: "POST",
    url: "@(Url.RouteUrl("DummyRequest"))",
    success: function (data) {
        if (data.Success) {
            $('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
            setInterval(function () {
                location.reload();
            }, 5000);
        }
        else {
            $('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
            /*setInterval(function () {
                location.reload();
            }, 5000);*/
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        $('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
    }
});
Comments