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?
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With