通过AJAX onclick传递数据

When a user clicks a certain link, I'd like to run an AJAX call that sets a $_SESSION variable, while still directing the user towards the link's href.

When I run the following code, Firebug shows that there is an error, but doesn't specify; readyState=0, status=0, statusText="error" is all I get from console.log.

If I add e.preventDefault and window.location.href = linkPath; into my success function, the script sends the user to the correct place; but only after a delay while it waits for the php page to complete.

How can I run the AJAX call while still passing the user through to their link without delay?

$(document).ready(function() {
$(".example_class").click(function(e) {
    //Stop the page from leaving until we start our ajax
    //e.preventDefault();

    //var linkPath = this.href;

    var form_data = new Object();

    //Set the application ID for insert into the DB
    form_data.variableName = encodeURIComponent('ExampleName');

    //Send the data out to be processed and stored
    $.ajax({
       url:'/mypath/myfile.php',
       type:'POST',
       data:form_data,
       success:function(return_data){
            //window.location.href = linkPath;
            return;
        },
       error:function(w,t,f){
           console.log(w);
           return;
       }
    }); 

    return;
});
});

Make the ajax call, then redirect the user. The ajax call will send before the window.location changes. The only thing you can't account for is if the ajax call fails.

$(".example_class").click(function(e) {
    var linkPath = this.href; 
    var form_data = new Object();

    //Set the application ID for insert into the DB
    form_data.variableName = encodeURIComponent('ExampleName');

    //Send the data out to be processed and stored
    $.ajax({
       url:'/mypath/myfile.php',
       type:'POST',
       data:form_data,
       success:function(data){ alert('never alerts but request sent to server.'); },
       error:function(){  alert('page changes, but ajax request failed, sorry.'); }
    });
    window.location.href = linkPath;
    return;
});

The other option is to set the onbeforeunload event with an ajax call.

As said in coments, ajax calls are aborted when the caller page is unloaded. But it does not mean that the server has not received the call, it only means that the server has not sent back a reply. To minimize the time spent by the ajax call, you could just wait for the first response to the ajax call with "xhr.onprogress" (which is not implemented in $.ajax from jquery), and then open the link.

But, if you were having the control of the server, simply make a redirection of '/mypath/myfile.php?redirect_url='+linkPath to linkPath with:

header('location: '.$_GET['redirect_url']);