I have following AJax request function which is working fine. upon successful it returns 1 else 2.
Now i would like to perform some action outside of this function based on this return value, as below, but its not working .. it always returns "undefined"...
I expect the return_code should return either 1 or 2 based on following code
<script>
var return_code=add_to_cart_ajax(200);
alert(return_code);
</script>
returns "undefined"
AJAX Request :
<script>
//Ajax to send request to add
function add_to_cart_ajax(id)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText); // returns 1
if (xmlhttp.responseText==1)
{
return 1;
}
else
{
return 2;
}
}
}
xmlhttp.open("GET","add.php?id="+id,true);
xmlhttp.send();
}//end of the function..
</script>
Since an AJAX call is asynchronous one common way of dealing with it is to use a callback-function that gets called once the request is processed.
Something like
EDIT: If you need to hang on to the return_code, you'd do
But it's important to understand that since the AJAX request is asynchronous, your
return_codevariable will not have a value assigned to it untill the AJAX request is fulfilled and you can't use it for anything untill that has happened, so any code that needs to do something withreturn_codeshould be included in or called from the callback. This is one of the things that is going to be a bit hard to grasp at first if you're coming from a background where all code is being run top-to-down. That's simply not the case once you start working with asynchronous stuff.