0

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?

mliebelt
  • 15,345
  • 7
  • 55
  • 92
user2674341
  • 277
  • 2
  • 6
  • 15
  • http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function ? – parchment Aug 19 '14 at 12:22

1 Answers1

2

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);
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155