0

I am taking a click event on an anchor with JQuery which makes a $.getJSON request to the server sending some data in the querystring. I am doing some logic in the server with the querystring provided and returning nothing back to the client. I am not making e.preventDefault(); on the click; so after the javascript code runs it will go immediately to navigate to another page. my question is: Is there any side effect to let this code runs like that? Normally i would do:

e.preventDefault();
$.getJSON('uri', function(data){
location = $(this).href;
});

To navigate after the callback.

Manuel Valle
  • 297
  • 8
  • 18
  • `href` is not a property of a jQuery object. You mean to use the prop() method. – George Sep 17 '15 at 18:10
  • Have you tested it in different browsers? There might be differences in how the requests and navigation are handled, so that some browsers won't make the AJAX call because the navigation happens first. – Guffa Sep 17 '15 at 18:14
  • 2
    @charlietfl: Actually `this.href` won't work either, as `this` is no longer a reference to the element when the callback is called. – Guffa Sep 17 '15 at 18:15
  • @charlietfl: No, the redirect is not in the callback. It's in the callback in the alternative code that the OP is showing, but not in the code that the question is about because then it would never happen. – Guffa Sep 17 '15 at 18:16
  • browsers won't wait for ajax if don't prevent the default IMO...click event is synchronous – charlietfl Sep 17 '15 at 18:17
  • @charlietfl: No, it won't wait for the AJAX call to complete, but the question is whether it will reliably send the request. – Guffa Sep 17 '15 at 18:19
  • As stated in the linked duplicate question, the behavior is unpredictable if you do not wait until the call has been made before proceeding with a location change. – plalx Sep 17 '15 at 18:20
  • Yes, href is not a property I meant to write location = $(this).attr('href'); but the question is willl the getJSON request be handled properly eventhough I navigate quick to the other page? – Manuel Valle Sep 17 '15 at 19:39
  • Looking in the net. I believe my goal can be achieved by using a var img = new Image() and settings its src to my end point....looks promising. thanks everyone. – Manuel Valle Sep 17 '15 at 20:43

0 Answers0