Saturday, March 26, 2011

Multiple Requests with Ajax

The Ajax programing technique can only be used to make one request at a time: however, it is possible to get more data using the java script split command.

Returning only one piece of information at a time is very limiting, and impractical. Many times you need to return more than one item to a web page. While maintaining and adding to a commercial website, I needed to find a solution.


The solution was not easy to find. It took a while to wrap my head around the concept, but I eventually figured it out.


Here it is. In your statechange function under readystate 4, after,

document.getElementById("data").innerHTML=xmlhttp.responseText;,

add the following line;


//The message is split wherever [BRK] is part of the message and stored in an array.
var result=document.getElementById("portdata").innerHTML.split("[BRK]");.


If you are using PHP for your server side script,  your last line should include the following (this is only an example, but your code should follow the same format);

$variable="George Thomson";
echo "Customer_Name".[BRK].$variable.[BRK];.

In readystate 4, evaluate the data and assign it.


Example:

if (result[0]=="Customer_Name"){
      document.getElementById("msg").innerHTML=result[1];
}


Remember that the index number for an array always starts at zero.


Additional resources;


http://www.w3schools.com/JS/js_obj_array.asp


No comments:

Post a Comment

Programming for the Web