user2674341
user2674341

Reputation: 277

How to control the execution of Javascript

I wants to get the last id from MySQL table and create a cookie with this value in Javascript and PHP. following is my code.

if (getCookie("id")=='') {
    last_visitor_id = get_last_visitor();
    deviceID = last_visitor_id++;
    setCookie("id", deviceID , 365);
    $.ajax({
        url:"save_device.php?deviceID="+deviceID+
            "&websiteID="+WebsiteID+
            "&width="+sWidth+
            "&height="+sHeight,
            success:function (datasource) {
                // alert (datasource);
            }
        }
    );  
} else {
    deviceID = getCookie("id");
    alert ("working...." + deviceID);
}


 function get_last_visitor(){
    $.ajax({url:"get_last_visitor.php",success:function(last_visitor){
         // last_visitor++;
         //alert ("Last Visitor ID " + last_visitor);
         return (last_visitor);
    }});        

}

There is a problem with code. Before it gets the last visitor id it executes the setCookie function even though there is no value returned by the get_last_visitor() function. Functions return the value after some time, but in the mean time it creates a cookie with NAN.

Can any one suggest some solution?

Upvotes: 0

Views: 61

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68440

It make no sense to execute return (last_visitor) from your ajax call since it is async. The execution flow is not waiting for the ajax call to finish, next line is executed inmetiatly so get_last_visitor is returning null ALWAYS.

You can change your code like this to use the success ajax callback to execute your logic

if (getCookie("id")==''){
    $.ajax({url:"get_last_visitor.php"})
    .done(function(last_visitor_id) {
        deviceID = last_visitor_id++;
        setCookie("id", deviceID , 365);
        $.ajax({url:"save_device.php?deviceID="+deviceID+"&websiteID="+WebsiteID+"&width="+sWidth+"&height="+sHeight,success:function(datasource){
            // alert (datasource);
        }});    
    });
} else {
    deviceID = getCookie("id");
    alert ("working...." + deviceID);
}

Upvotes: 2

Related Questions