#native_company# #native_desc#
#native_cta#

Using Get and Post Methodology in AJAX Applications

By Anthony Corbelli
on December 15, 2008

GET is typically used when you simply need to retrieve data and POST is used when you want to change the state of the server (i.e. send/update data on the server). This article will discuss how we use GET and POST methodology in our Ajax applications!
In our last adventure we learned how to interface basic AJAX with PHP to return data from a server on the fly. This is all very well and good if the only thing you need, or want, is to retrieve basic string values from the server without refreshing the page. As soon as you want to do anything more complicated you will need a slightly larger toolset.
AJAX interacts with the server via typical GET or POST methods just like an HTML form submission to a server-side script. Let’s jump into some basic JavaScript to see the difference.
I’ll use the same “city and state” example as last time and then explain the changes in the code:

difference.js

var xmlHttp;

function createXMLHttpRequest()
{
	if (window.ActiveXObject){xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}
	else if (window.XMLHttpRequest){xmlHttp = newXMLHttpRequest();}
}

function createQueryString()
{
	var querystring = "city=Beverly%20Hills&zip=90210";
	return querystring;
}

function makeGETRequest()
{
	createXMLHttpRequest();
	var querystring = "myserver.com/myfolder/myfile.php?";
	querystring += createQueryString() + "&ts=" + new Date().getTime(); //the timestamp is new, but optional
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open("GET", querystring, true);
	xmlHttp.send(null);
}

function makePOSTRequest()
{
	createXMLHttpRequest();
	var url = "myserver.com/myfolder/myfile.php?ts=" + new Date().getTime();
	var querystring = createQueryString();
	xmlHttp.open("POST", url, true);
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(querystring);
}

function handleStateChange()
{
	if (xmlHttp.readyState == 4)
	{
		if (xmlHttp.status == 200)
		{
			parseResults();
		}
	}
}

function parseResults()
{
	alert(xmlHttp.responseText);
}

As you can see (refer to the code in the previous article), the only major change is the addition of a new function – makePOSTRequest(). The POST request differs from the GET request in a few important ways:

  1. xmlHttp.open MUST be called before xmlHttp.onreadystatechange.
  2. We set request headers (Content-Type) to (application/x-www-form-urlencoded) to simulate a proper browser POST request to the server, it needs to know what type of data we’re sending.
  3. We separate the querystring from the url, because in a POST request the query is not embedded into the url.
As of this writing there have been some small changes to other parts of the code, such as the addition of the timestamp to the query string and doGETRequest was renamed to makeGETRequest. The timestamp is added to help prevent caching of data from the server where it is not desirable, as may be the case if your code is changing data on the server. With an added timestamp you “trick” your browser into thinking you’re sending a completely new request and, thus, it should not serve you the same data you recieved in your last request. doGETRequest was renamed for purely aesthetic reasons.

myfile.php

<?php
$city = null;
$zip = null;
$method = null;
if (empty($_POST) == false)
{
	$city = $_POST['city'];
	$zip = $_POST['zip'];
	$method = "POST";
}
else if (empty($_GET) == false)
{
	$city = $_GET['city'];
	$zip = $_GET['zip'];
	$method = "GET";
}
/*
This is where you do things with the data, like consult your database for a query, update a database row, insert a new row or perform calculations, and then return the result. I am simply repeating the data sent, and putting it into $response;
*/
$response = "You requested city=$city and zip=$zip via $method";
echo $response;
?>

Notice the small additional check to see which method the request was sent by; if you are only using one method in your code you may not need this check, but it is a good programming practice to prepare for it, in case of a malformed request.
You can see how similar the two methods are, and how easy it is to send/update/recieve data from the server on the fly using AJAX. This sort of simple query will suit the majority of your programming needs as long as you don’t need to send complex data to the server (such as objects).
If you need to send data that doesn’t fit very well into string concatenation, such as objects created in classes on the client or data structures, then you will need to use a slightly more powerful variation on AJAX. That’s where the XML portion of Asynchronous Javascript and XML (AJAX) comes in, sending an XML structure to the server and recieving an XML response.
Play around with using POST as a query method and come back soon, as we will be forming XML queries and receiving XML responses!