JavaScript – POST data via AJAX call

Here’s how I used the old school way to POST data to a URL using AJAX.

function getNextHost() {
	var $hostname = $( '[name="eval|hostname"]' ); //Input provided to check if it already exists in DB
	var _hostname = $hostname.val();
	var $spanHostname = $( "#id_availableHostname" );	//Span where the result will be displayed

	var xmlhttp;
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var jsn = eval ("(" + xmlhttp.responseText + ")");
			//alert(jsn["ResultCode"]);
			
			//--- Setting the available Hostname adjacent to the input field ---
			$spanHostname.text(jsn['AvailableHost']);
		}
	}
	xmlhttp.open("POST","getHostnameProxy.php",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("hostname=".concat(_hostname).concat("&domain=yourDomain.com"));
	return true;
}

The data submitted can be accessed by the server via $_POST[‘hostname’], $_POST[‘domain’]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s