The problem is that Ajax is requesting asynchronously . Therefore, you cannot immediately return the data. The way you should do this is to specify a callback function that will process the response data.
function handleJSON( data ) { // ... // do whatever you want to do with the data } ajax( "url/file.php?param=value", handleJSON ); //////////////////////////////////////////////////////////////////////////////// function getXmlHttpObject() { var xmlHttp; try { xmlHttp = new XMLHttpRequest(); } catch (e) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } function ajax(url, onSuccess, onError) { var xmlHttp = getXmlHttpObject(); xmlHttp.onreadystatechange = function () { if (this.readyState == 4) { // onError if (this.status != 200) { if (typeof onError == 'function') { onError(this.responseText); } } // onSuccess else if (typeof onSuccess == 'function') { onSuccess(this.responseText); } } }; xmlHttp.open("GET", url, true); xmlHttp.send(null); return xmlHttp; }
source share