views:

18

answers:

2

Hi Everyone,

I'm tying to do what seems like a simple ajax but can't get it to work. Here's my code:

var xmlHttpRequest;

function processRequest(){
 alert("process request called with " + xmlHttpRequest);
 if(xmlHttpRequest.readyState==4){
  alert("status = " + xmlHttpRequest.status);
  if(xmlHttpRequest.status == 200){    
     }
   } else {
    alert("process request no luck readyState = " + xmlHttpRequest.readyState);
   }
 alert("process request exiting");
}


function updateCount(customerID, productID) {

 xmlHttpRequest = init();

  function init(){

 if (window.XMLHttpRequest) {
               return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } else {
         alert("Your browser does not support AJAX!");
        }
  }


 xmlHttpRequest.open("GET", url, true); 

 xmlHttpRequest.onreadystatechange = processRequest(); 
}

Like I said in the subject line, readyState is always 1. What am I doing wrong?

Thanks! Eddy

A: 

Add xmlHttpRequest.send(); after xmlHttpRequest.onreadystatechange = processRequest;.

digitalFresh
A: 

You are calling processRequest before you start your request.

xmlHttpRequest.onreadystatechange = processRequest();

is wrong and has to be

xmlHttpRequest.onreadystatechange = processRequest;

This will store a reference to your method instead of calling it directly.

As soon as the ready state changes, the xmlHttpRequest object trys to call this reference.

Ghommey
Thank you very much for both Ghnommy and digitalFresh! It works beautifully. I was struggling to figure out where is the blocking / waiting being done by this API. I guess javascript works in mysterious ways :)
Eddy