Archive | AJAX RSS feed for this section

Using POST method in XMLHTTPRequest(Ajax)

19 Jan

Usually only the GET method is used while creating Ajax apps. But there are several occasions when POST is necessary when creating a ajax request. This could be for several reasons. For example, POST request are considered more secure than GET request as creating a POST request is relatively harder than creating a GET request.

Requirements

  • Create a XMLHTTPRequest Object that uses the POST method.
  • See if the arguments passed to it appear in the ‘$_POST‘ array in PHP.

Code

XMLHTTPRequest Object

For the sake of simplicity, we are going to create the XMLHTTPRequest object using the Firefox supported ‘ XMLHttpRequest()’ function. I believe that you know the proper way of creating a cross-browser XMLHttpRequest object. If not, learn that first.

var http = new XMLHttpRequest();

Using GET method

Now we open a connection using the GET method.


var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		alert(http.responseText);
	}
}
http.send(null);

I really hope that this much is clear for you – I am assuming that you know a bit of Ajax coding. If you don’t, please read a ajax tutorial that explains these parts before continuing.

POST method

We are going to make some modifications so POST method will be used when sending the request…


var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		alert(http.responseText);
	}
}
http.send(params);

The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument – in the GET method, we send the parameters along with the url separated by a ‘?’ character…

http.open("GET",url+"?"+params, true);

But in the POST method we will use just the url as the second argument. We will send the parameters later.

http.open("POST", url, true);

Some http headers must be set along with any POST request. So we set them in these lines…

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		alert(http.responseText);
	}
}

We set a handler for the ‘ready state’ change event. This is the same handler we used for the GET method. You can use the http.responseText here – insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.

http.send(params);

Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the send function. The params variable was declared in the second line as “lorem=ipsum&name=binny” – so we send two parameters – ‘lorem’ and ‘name’ with the values ‘ipsum’ and ‘binny’ respectively.

That’s it. If you wish to see the working of this script, I have set up a demo page for Ajax using post.

Libraries

The above given methods are the manual way of doing things – you can automate this using the hundreds of Ajax libraries out there.

jx


jx.load("get_data.php?lorem=ipsum&name=binny",handlerFunction,"text","POST");

Prototype

var myAjax = new Ajax.Request('get_data.php?lorem=ipsum&name=binny',{
	method: 'post',
	onComplete:handlerFunction
});

Dojo Toolkit

dojo.io.bind({
	url:        "get_data.php?lorem=ipsum&name=binny",
	mimetype:   "text/plain",
	method:		"POST",
	load:handlerFunction
});

Update Multiple Page Elements Using The XMLHTTPRequest Object and JavaScript

19 Jan

In the development of Ajax application many times we will encounter following issues.

  • The requiremnt to update multiple text boxes simultaneously.
  • Fill more that one dropdown list.
  • Update a combination of text boxes, dropdown lists and div tags.
  • Call different web pages and different webservices at the same time.

Imagine the case of a financial data site (such as a stock market info site) with various regions of the page used for displaying data any taking user inputs. We may want to populate fill numerous div tags, textboxes and dropdown lists with real time data. If we loop the several requests and we will also have to check for timeout, if timeout occurs and no data is returned, then we will have to fire the same request again. It may end up that we have made 10 requests and 4-5 requests simply timeout because of network problems. If we dont loop then we will either get whole data or nothing (in which case there is only one more request to be made).

In this article we will discuss the XMLHTTPRequest object and JavaScript and develop a JavaScript class which can asychronously update multiple HTML elements. Also this class can be extended as per the requirements. I have used ASP.NET as the platform in this example but it does as the solution is just Javascript it can be applied to any web development platform.

Regarding classes in JavaScript, technically there is no ‘class’ in JavaScript but we can use a function as a class.

Consider the following code :

function testClass()
{
this.Msg = “Hello”;
this.showMsg = function()
{
alert(this.Msg);
}
}

var obj = new testClass();
obj.Msg = “HI”;
obj.showMsg();

In above script if we remove obj.Msg = “HI”; we will get an alert with text Hello.

We will now develop our JavaScript class step-by-step:

  1. Include JS file and add the following code:

function AjaxClass()
{
this.Method = “GET”;//OR “POST”
this.Async = true; //OR false (asynchronous or synchronous call)
this.request = null;
this.init = function()
{
if (window.XMLHttpRequest) // if Mozilla, Safari etc
this.request = new XMLHttpRequest();
else if (window.ActiveXObject)
{ // if IE
try
{
this.request = new    ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
this.request = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e){}
}
}

if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
//we will develope this.handleResponse function in step 3
this.request.open(this.Method, this.url , this.Async);
this.request.send(null);
}
}
}

Here we have created an XMLHTTPRequest object which is simply used to send a call to the server. The default method is GET (this.Method = “GET”) and calling type is Ascynchronous (this.Async = true)

  1. In this step we will develop simple logic which will allow us to dynamically call Ajax function created in Step 1.

For this one JSON (http://www.json.org/) object as follows.

this.JSONArray = {  “Method” : “POST”, //Method type
“Async”  : true, //Call type
“CallPage” : “CallPage.aspx”, //page or webservice
“Querystring” : “”, //Query string
“dependentType” : null,//[0,1,2,3] for isEdit
“isEdit”: [
{
“textBoxId” : null, //0 then this element
“dropDownId” : null, //1 then this element
“default” : null, //2 then this element
“misc”:null //3 then this element
}
]

};

In above script we can set the default values for all elements. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using “CallPage” : “CallPage.aspx” we can define default server page and while calling Ajax function we can change this value to web method or to any other web page.
As we will proceed in this article we will examine how to change all the above values and how can we use it to update multiple elements.Also we will see that how to extend the class.

  1. Recall from Step 1 : this.request.onreadystatechange = this.handleResponse;

In this step we will develop this.handleResponse function and in this function we will use the JSON object defined in Step 2. Whenever this.handleResponse function gets called script loses the focus of  this. To keep track of this object we will asign it to some variable. i.e var self = this; // To lose of focus of the element

In this function we will be able to receive data from server. Once we receive the data we can manipulate it. This function will handle the responses from web services as well as from web pages. The web service always returns a response in the form of XML whereas the response from the webpage can be any format defined by web developer.

The function will be as follows:

var self = this; // To handle lose of focus
this.handleResponse = function()
{
if(self.request.readyState == 4 && self.request.status == 200)
{
if (window.ActiveXObject) // for IE
{
var doc=new ActiveXObject(“Microsoft.XMLDOM”);
doc.async=”false”;
doc.loadXML(self.request.responseText);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(self.request.responseText,”text/xml”);
}
try
{
var data  = “”;
if(doc.documentElement) //Response from webservice
data = doc.documentElement.childNodes[0].nodeValue;
else data = self.request.responseText; //from web page
//data contains response text from the server

//At this point we have response from serve
//so here we will write our function to    //manipulate the data. We will develop it in
//4th step.
}
catch(e) {}
}

In the the 1st step we had:

if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
this.request.open(this.Method, this.url , this.Async);
this.request.send(null);
}

We will now modify this so that we can directly use the JSON array which we defined in 2nd step:

if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
this.request.open(this.JSONArray.Method, this.url , this.JSONArray.Async);
this.request.send(null);
}

While developing Ajax applications we ned to be aware of the following issues regarding domains:

  • URL for XMLHTTPRequest object should belong to same domain.
  • Firefox and other browser doesn’t allow cross domain communication.
  • IE will show warning for cross domain communication.

Thus our this.url = “http://myDomain/mysite/” + this.JSONArray.CallPage + this.JSONArray.Querystring;

e.g. “http://localhost/Demo/CallPage.aspx?”+this.JSONArray.Querystring;
Also whenever we want to call web methods like above example, we need to set following protocols under <webServices> in web.config file.

<webServices>
<protocols>
<add name=”HttpGet”/>
<add name=”HttpPost”/>
</protocols>
</webServices>

  1. Up to this point we have finished with development of the Ajax logic which will return a response. So now we need to develop logic for updating the HTML controls.

In this.handleResponse (step 3) we have seen that we get response in the “data” variable in JavaScript.

So now we have response from the server we will add following logic:

switch(self.JSONArray.dependentType)
{
case 0:
PopulateControls(self.JSONArray.isEdit[0].textBoxId,data);
//simple call to JS function
break;
case 1:
PopulateControls(self.JSONArray.isEdit[0].dropDownId,data);
break;
}


self.JSONArray.isEdit[0].textBoxId
will contain the id of the text box in which we need to update. And data is the response from the server. In our switch we have simply used the elements of JSON object developed in Step 2.

We will now focus on initiating a request and setting the elements of the JSON objects.

First simply create object of our AjaxClass().

var obj = new AjaxClass(); //Object creation
obj.JSONArray.Method = “GET”; //Setting Method
obj.JSONArray.isEdit[0].textBoxId=”txt1″;//Textboxid for response
obj.JSONArray.dependentType=0;//0->Textbox,1->drop downlist,
//2->tagId,3->Misc and so on
obj.init();//Initiate the AjaxCall

If obj.JSONArray.dependentType=1 then our switch case will not work for the textbox, but it will work for a dropdown list (check above switch case). This means we will have to set the dropdown in the JSON object:

obj.JSONArray.isEdit[0].dropDownId=”ddl1″;

In this way we can define our own set of HTML controls to be updated.

In the same way we can also change all the default settings in JSON object of that class.

e.g.

obj.JSONArray.Method = “GET”;
obj.JSONArray.CallPage = “Mywebservice/webMethod”;
obj.JSONArray.Querystring= “My querystring”;

For this URL will be : this.url = this.url + this.JSONArray.CallPage + this.JSONArray.Querystring ;

In case of a web service we will have to set the CallPage element as we did in the above example.

For multiple textboxes use: obj.JSONArray.isEdit[0].textBoxId=”txt1$txt2$txtn”;//$ is a delimiter
While sending data from the server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will receive data and the appropriate textBoxId.

Now that we have different types like “txtbox(es) + drop down list(s) + div” in such case we can use “misc” option of isEdit element of JSON object.

And we can define our  PopulateControls function the way we want. For ASP.NET we could also integrate ICallback logic for large data transfers.

You can download the demo code here . This contains an ASP.NET project with the following files:

  • XMLHTTPJsClass.js this file contains our AjaxClass() and funtion to populate textbox(es).
  • Demo.js this file contains 3 js function which initiates AjaxRequest with customization of  request. Here you can find web page and webservice calls.
  • Default.aspx page
  • Webservice.asmx page.


Getting started with AJAX using PHP

19 Jan

AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms.

In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is not a programming language, so you don’t have to learn any new technology. AJAX can be implemented by using existing standards (JavaScript and XML) in a different way.

If we are using PHP or any server side technology and need to extract data from storage on a server (eg a database or a file), we will have to make an HTTP request (either POST or GET) to get the data. Once the data is received the the web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from server in background and then display it on the page without a reload. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object (XML over HTTP). With an HTTP request, a web page can make a request to, and get a response from a web server without reloading the page.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. But the creation of XMLHttpRequest object is different in Internet Explorer than the other browsers. I will discuss this later. To use AJAX to request a data from the server we need to do the following.

1. Create an XMLHttpRequest object.
2. Then using this object, request data from the server.
3. JavaScript will then monitor for the changing of state of the request.
4. If the response is successful, then the content from the data store requested will be returned as response (response can be in the form of a String or XML).
5. Use the response in your web page.

1. Create an XMLHttpRequest object

JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object. The following codes creates an XMLHttpRequest for all browsers:

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5
req = new ActiveXObject(“Microsoft.XMLHTTP”);
} else if(window.ActiveXObject){
//For IE 6+
req = new ActiveXObject(“Msxml2.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject(“Microsoft.XMLHTTP”) and for IE 6.0+ use new ActiveXObject(“Msxml2.XMLHTTP”). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.

var req;
try
{
// Firefox, Opera, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
}
}

In JavaScript, if statements within a try section fail, then the execution resumes from the corresponding catch block. Here first we are trying to get create a XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject(“Msxml2.XMLHTTP”), and if it fails also we will try ActiveXObject(“Microsoft.XMLHTTP”). If all these fail, then we will alert the user that his/her browser does not support AJAX.

2. Request for a web page

After creating the XMLHttpRequest we now need to send the web request using the open method. We also need to specify the HttpRequest method, GET or POST. Use the following code to send the request.

req.open(“GET”,”somedata.php”);
req.send(null);

Here, req is the XMLHttpRequest object. It will request to the server for somedata.php using GET method. The open function also has a third parameter, an optional boolean parameter. You should set that to true :

req.open(“GET”,”somedata.php”,true);
req.send(null);

Both of the above is correct.

3. Monitor for the response of the request

You will need to monitor for the state of the request. For doing this you can assign a function to req.onreadystatechange (Here, req is the XMLHttpRequest object), like below.

req.onreadystatechange=function()
{
if(req.readyState==4 && req.status == 200)
{
var resp = req.responseText;
}
}

Or like this,

req.onreadystatechange = handleResponse;

function handleResponse(){
if(req.readyState == 4 && req.status == 200){
//returned text from the PHP script
var response = req.responseText;
}
}

The readyState property holds the status of the server’s response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.

4. Get the response

The response will be as string or as XML. The data sent back from the server can be retrieved with the responseText property as string. Use responseXML for getting the response as XML.

5. Use the response on your web page

You can use the response you got from the XMLHttpRequest in your web page/application. You can either set a value of a text field or use the returned HTML from the web request as innerHTML for a <div></div> tag or <span></span> tag (See below for the implementation of this)

Using AJAX with PHP

I usually place all the AJAX related functions in one JavaScript (ajax.js), and later add the JavaScript in my PHP pages. My ajax.js looks like below.

function createRequestObject(){

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}

function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(“ajax_res”).innerHTML = response;
}
}
}

Now I add a <script></script> tag in my PHP pages like following to access the JavaScript functions.

Then I create a function called sendReq() as shown above for preparing the URL to the PHP page to get some data from the database. If you look into the ajax.js, you will see that I’m assigning the output of the PHP page to a <div> tags innerHTML. My div tag has the id=’ajax_res’.

<div align=”center” class=”black” id=”ajax_res”>
<img src=”wt_bg.jpg”>
</div>

After calling the sendReq function with a value of ‘success’, it will connect to the server for sending a request to the URL get_lcm.php?status=success, then get the data from the database using the value ‘success’, and set the innerHTML attribute of the div tag whose id is ‘ajax_res’ according to the response. Initially my div tag shows an image, but after AJAX responds successfully this image will be replaced with the response. You can also get the response as the value of an input text.

My get_lcm.php looks like this.

<?php
include_once(“create_table.php”);

if(!empty($status)){
echo “<strong>Search Result for Status: “.$status.”</strong><br><br>”;

$ct = new createtable(“select * from lcm where state=$status”);

$ct->table_viewer();
}
?>

I used one of my PHP classes ‘create_table.php’ for creating a table from SQL queries. ‘create_table.php’ has a function, table_viewer(), to print the SQL output as a HTML table. I will discuss about this class and some other data abstraction classes I used in some later articles, if necessary.

I had the following HTML code for calling the AJAX function using the sendReq() as described earlier.

<a class=”none” href=”#” onClick=”sendReq(1)”>ACTIVE</a>

If a user clicks the above hyperlink, then the JavaScript function sendReq is invoked using the value of status equal to 1. After that the webpage with URL get_lcm.php?status=1 will be invoked. This PHP will get the information from database and shows the result as table. This result will then be displayed within the <div> tag.

Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development is you place all your AJAX related code in a single JavaScript file and reference it from anywhere you need AJAX.

There is another way of getting the same result from PHP without using the XMLHttpRequest object. But I personally do not like the concept, because it is missing one of the main ingredients of Asynchronous JavaScript And XML (AJAX), XML. This concept is good for the old browsers with no supports for XMLHttpRequest object, but as all the newer versions are supporting XMLHttpRequest object you can use AJAX for the common browsers.