1. Tech

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/blajax05.htm

was emailed to:

Thanks for sharing About.com with others!

Introduction to Ajax

5. Passing Parameters

Before we move on to looking at how to deal with what we get returned from our AJAX request and how to set up the server side processing to create that response, let's first look at how we can tell the server what it is that we want it to do.

In the code that we have looked at so far we have defined myrequest.php as the server side process that is to handle our request. We actually have three options when it comes to setting up multiple AJAX requests for different information.

  1. We can substitute different server side scripts for myrequest.php and have each server side script perform different data retrievals for us. This is the obvious choice where the retrievals are for completely different purposes that have no real interdependence.
  2. As you will remember we called open passing a first parameter of "GET". When we use get processing we can pass parameters on the end of the url. For example we can have myrequest.php?type=1 and myrequest.php?type=2 where we pass different values in the type field that the server side script can access to determine what we want it to do. We can of course pass multiple arguments this way by separating them with ampersands.
  3. We can change from using "GET" to using "POST" in order to pass a larger amount of data to the request. To be able to do this we'll need to add a request header and pass the data in the send command. The following can pass all of the form fields from the first form on the page.
ajaxObj.open("POST", url, true);
ajaxObj.setRequestHeader("Content-Type"
"application/x-www-form-urlencoded");

ajaxObj.onreadystatechange = function() {
ajaxObj.processRequest();}
var myform = document.forms[0];
var reqBody = getRequestBody(myform);

ajaxObj.send(reqBody);

The getRequestBody function needs to rebuild the values from the form into the appropriate format to pass as the body of the request. Submitting the form using POST does this conversion of the format for us automatically but when we are using Ajax to send the data without submitting the form to the server we need to build it ourselves. The following code should handle this for us allowing for whatever fields we might have in the form.

function getRequestBody(theForm) {
var p = [];
for (var i = theForm.elements.length-1; i >= 0; i--) {
var fld = theForm.elements[i];
switch (fld.type) {
case "button": case "submit": case "reset": break;
case "checkbox": case "radio": if (!fld.checked) break;
default:
if ("select" == fld.tagName.toLowerCase())
p.push(ncode(fld.name,fld.options[fld.selectedIndex].value));
else p.push(ncode(fld.name,fld.value));
}
}
return p.join('&');
}
 
function ncode(n,v) {
return encodeURIComponent(n) +
'=' + encodeURIComponent(v);
}

©2014 About.com. All rights reserved.