views:

29

answers:

2

I wrote this simple AJAX script:

 var request; 




function createRequest(){ 

 request = null;

 try{
 request = new XMLHttpRequest();

 }catch(failed){
  request = null;

 }

 if(request==null){
  alert("Incompatible Browser");
 }



}



function getProd(form){


 createRequest();


 var w = form.list.selectedIndex;
 var cat = form.list.options[w].text;

 var url = "showProd.do?prodCat=" + cat;

 request.open("GET",url,false);

 //Send request to server
 request.onreadyStateChange = updatePage();
 request.send(null);

}

function updatePage(){

 //if(request.readyState == 4){
  //add your code here
  var options = "Bloody Server";
  options = request.responseText;
  //docWrite(options);
  alert(options);
 //}

}

I used firebug to check the response i was getting from server. Its absolutely fine and is of type "text/html".

Problem is it doesn't show up in alert box!

+2  A: 

By writing request.onreadyStateChange = updatePage(), you are calling the updatePage function and assigning its return value to onreadyStateChange (which, by the way, must be lowercase)

You need to assign the function itself to onreadystatechange without calling it by removing the ().

For example:

request.onreadystatechange = updatePage;

Note that using a global request variable is a horrible idea; your code cannot send two requests at once.

I highly recommend that you use an existing AJAX framework, such as jQuery's, instead.

SLaks
@Josh:​​​ What?
SLaks
slaks - the salient issue is that he is calling his update on every state change, likely resulting in an error that halts the script when it gets called the first time with readyState==1.
Sky Sanders
@code: Yes; your answer is also true. (Since I didn't notice it myself, I didn't add it to my answer) However, he also needs to correctly handle the event.
SLaks
+1  A: 

umm, you are calling your update function on every state change and all but the last will be before there is any data available, resulting in undesirable results.

You need to update your page when readystate==4

 createRequest();


....

 request.open("GET",url,false);

 //Send request to server
 request.onreadyStateChange = function(){

 if(request.readyState == 4){
  //add your code here
  var options = "Bloody Server";
  options = request.responseText;
  //docWrite(options);
  alert(options);
 }

};
 request.send(null);

....
Sky Sanders