Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is window.location.reload() negating the previous command?

I'm making a HTTP POST/DELETE request in javascript to delete a message in my rails app

 $.post(message_url, { _method: 'delete' }, null, "script");

If I refresh my browser on the page after I execute this line, I see that that the message has been in fact delete and no longer appears.

Now I want the page to automatically refresh after this command so the user sees its gone. I have the following lines:

    $.post(message_url, { _method: 'delete' }, null, "script");
    window.location.reload();

Now the page does indeed refresh but the message no longer gets delete. And I don't see any errors in the console.

So basically, without this reload(); command the message deletes just fine, but if I add this reload() line it stops working. Why is this happening?

More to the point, how could I accomplish what I'm trying to do?

like image 988
pejmanjohn Avatar asked Jan 15 '23 09:01

pejmanjohn


2 Answers

The "problem" is that $.post is asynchronous. That means that when you call it, it fires off an AJAX request to the server (to delete that message). Since it's asynchronous, the Javascript continues running (it doesn't wait for the AJAX request to complete in order to continue to run the rest of your code (window.location.reload()). Since it doesn't wait, window.location.reload() runs immediately after the request is fired off and is probably aborted (because the browser is being redirected to a new page and that is the default behavior).

The solution is to execute the reload() on complete of the $.post call:

$.post(message_url, { _method: 'delete' }, function () {
    window.location.reload();
}, "script");

http://api.jquery.com/jQuery.post/

like image 117
Ian Avatar answered Jan 18 '23 23:01

Ian


You have to wait until the ajax request finishes before you refresh the page, since ajax is asynchronous its still being executed when the window.location.reload(); which cancels the ajax request. You can use the success parameter in the $.post() method.

$.post(message_url, { _method: 'delete' }, function(){window.location.reload();}, "script");

That being said, this kind of defeats the purpose of ajax.

like image 25
Musa Avatar answered Jan 19 '23 00:01

Musa