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
$.postis 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$.postcall:http://api.jquery.com/jQuery.post/