My HTML which is at this url ‘/main/’ contains the following link:
<a href="/main/" id="do_something">Do Something</a>
So, the link should do something and then refresh the page.
My jquery looks something like this:
$('#do_something').click(function(event) {
var my_values = ['1','2'];
$.ajax({
url:"/process_values/",
type: "POST",
data: {values:my_values},
success:function(response){
alert("success: " + response);
},
error:function (xhr, textStatus, thrownError){
alert("xhr status: " + xhr.statusText);
},
});
});
The post is executing correctly, but the error callback is always called when it completes.
If I prevent the link from being called using event.preventDefault();, the success function is executed. Why is this? And how do I get the page to update after the post call?
Thanks
Without
event.preventDefault(), the user is directed to/main/(because it’s the default behavior of an anchor). Unloading the page causes all pending (XmlHttp) requests to abort, thus triggering theerrorfunction (=request has not finished yet).An overview:
#do_somethingclickevent -> Ajax request/main/.errorfunction triggeredIf you want the page to open, add this at the
successfunction:Alternatively, if you don’t want to hard-code the link: