32596

Jquery anchor tag click event does an ajax post, when it redirects, it causes error callback to exec

Question:

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

Answer1:

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 the error function (=request has not finished yet).

An overview:

<ul><li><em>click</em> #do_something</li> <li><em>fires</em> click event -> Ajax request</li> <li><em>follows</em> link to /main/.</li> <li><em>page unloads</em> -> Cancel all requests</li> <li><em>XHR aborted</em> -> error function triggered</li> </ul>

If you want the page to open, add this at the success function:

location.href = "/main/";

Alternatively, if you don't want to hard-code the link:

$('#do_something').click(function(event) { event.preventDefault(); var linkTo = $(this).attr("href"); var my_values = ['1','2']; $.ajax({ url:"/process_values/", type: "POST", data: {values:my_values}, success:function(response){ alert("success: " + response); location.href = linkTo; //Redirect the user to the new page }, error:function (xhr, textStatus, thrownError){ alert("xhr status: " + xhr.statusText); }, }); });

Answer2:

the idea with Ajax is not to do a page reload at all but load data asynchronously (parts at a time)

if you really need to you should use location.reload();

Answer3:

You couold do:

$('#do_something').click(function(event) { var hrefSaved = $(this).attr('href'); event.preventDefault(); var my_values = ['1','2']; $.ajax({ url:"/process_values/", type: "POST", data: {values:my_values}, success:function(response){ alert("success: " + response); window.location.href = hrefSaved }, error:function (xhr, textStatus, thrownError){ alert("xhr status: " + xhr.statusText); }, }); });

in this way you prevent the default action, make an AJAX call and if the calls is successful redirect to the desired page

Recommend

  • First jQuery ajax call collides with the second
  • Promise not returning the intended file in Angular.js
  • Checking JavaScript AJAX loaded resources with Mink/Zombie in PHP?
  • Internet Explorer 7 & 8 issue with Prototype 1.6.1 - Could not complete the operation due to err
  • react setState sets to string instead of object
  • Overriding jQuery default ajaxError for a specific status code
  • pass a javascript object to a jsp page using jquery
  • jquery ajax fails in firefox
  • Google Adsense inside a jquery dialog?
  • firebase storage cors strange Behaviour
  • XMLHttpRequest for Video Tag?
  • ajax function not going to php codeigniter controller
  • How to check for connectivity with server using javaScript from native Android 2.1 browser?
  • Ajax call always returning error 500 client side
  • SQL Query - Table Joining Problems
  • Can't remove headers after they are sent
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • How to use JavaScript to determine whether a file exists in a directory?
  • How do I pass the string value parameter of the selected list item from an auto-populated dropdown l
  • Get data from AJAX - How to
  • Bug in WPF DataGrid
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Convert array of 8 bytes to signed long in C++
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Is there a mandatory requirement to switch app.yaml?
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • AngularJs get employee from factory
  • Free memory of cv::Mat loaded using FileStorage API
  • Hits per day in Google Big Query
  • Understanding cpu registers
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize