Javascript – Ajax script only returns results sometimes

ajaxjavascript

I have a script running on xampp and when I run this script with alert call in it the file executes but when I run it without alerts it just sits there and doesnt return anything. What am I doing wrong?

Code:

var xhr;

function getPlants(xhr){
try {
xhr=new XMLHttpRequest();
}catch(microsoft){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
xhr=false;
alert("ajax not supported");
}
}
}

xhr.onreadystatechange=state_change;    
xhr.open("GET","db_interactions.php",true);     
xhr.send(null);
    alert("sent");


function state_change() {
    if(xhr.readyState==4 && xhr.status==200) {
        alert("all systems go");
        return xhr.responseText;
    }

}

Best Answer

I would highly recommend using jQuery or Prototype. They are JavaScript libraries that will make your life easier when doing Ajax calls and many other JavaScript operations.

Ajax example with jQuery:

 $.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });