How do I get jQuery to not execute <a href> until ajax is successfully written?
I am trying to update the database and send users to another page browser with one click.
The html is as follows:
<a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</a> Javascript is as follows:
$("#updateLiveProgress").live("click", function(e){ var ajaxlink = "~ajaxlink~" $.post(ajaxlink, function(data, e){ return true; }); }); When the user clicks on the link, he must update the database through the ajax link, and then the page returned will depend on the updates of the ajax database. The problem is that the page seems to load before ajax completes the database update. I am trying to pass the clickt event through ajax using e to prevent the link from being executed until the ajax call completes, but it does not work.
Is there a better way for me to do this?
Try to do this:
$("#updateLiveProgress").live("click", function(e){ e.preventDefault(); var href = this.href; var ajaxlink = "~ajaxlink~" $.post(ajaxlink, function(data, e){ window.location = href; }); return false; }); As with jQuery 1.7, use this (using .on instead of .live ):
$("#updateLiveProgress").on("click", function(e){ e.preventDefault(); var href = this.href; var ajaxlink = "~ajaxlink~" $.post(ajaxlink, function(data, e){ window.location = href; }); return false; }); This is the inherent behavior of Ajax, in fact this is what A : asynchronous means. The ajax call is launched, and the click function is returned before the ajax request is returned. You have 2 options:
Make a synchronous ajax call. I would not recommend this.
Manually follow the link when the ajax call returns:
$("#updateLiveProgress").live("click", function(e){ var ajaxlink = "~ajaxlink~" $.post(ajaxlink, function(data, e){ window.location.href = ajaxlink; // or something similar }); return false; // this keeps the link from being followed });
Depending on how you configured AJAX , you are likely to use a callback. In this case, the callback is where the success of the function is indicated. Here is a sample code:
//assuming button is an anchor link $('#button').click(function(){ //do ajax request $.ajax{ url: 'http://someurl.com/getuser?id=69', success: function(data, status){ //assuming page to load is in data, redirect window.location = "http://mysite.com/newuser.aspx"; } } //import to stop the anchor link request return false; });