The title of this question is not very clear but I cannot explain what I am asking without providing some code.
I am making a page which submits reports (which are arrays) using AJAX. I have functions stored in a library which submit the array to the PHP page that look like this:
function saveReport(params)
{
var url="reports/save.php";
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
return false;
}
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
if (xmlHttp.responseText == 'complete')
{
return true;
}
else
{
return false;
}
}
}
(I don’t believe the GetXmlHttpObject() function is relevant to the question)
I would like to be able to call the saveReport() from my page like this
success = saveReport(params);
if (success == true)
{
alert('success');
}
else
{
alert('failure');
}
So the function saveReport() needs to return a value which is returned from the function stateChanged() when it is called so that the page that called saveReport() can then decide what to do – which may be a different on different pages. Is there any way of doing this?
I realise that it may be impossible the way I am trying but is there something I can do to the same effect.
Is there a reason why you’re rolling your own Ajax helper?
In this situation you’re going to need a callback function to be fired when the server has responded so that you can do something with the response, whether it be a success or fail.
Obviously, you can use something like jQuery.ajax but that might be overkill for something this simple.
You could try one of the many micro Ajax libraries at http://microjs.com/#ajax to achieve what you’re after.