jQuery – POST Data via jquery.POST

The previous post shows the old school way to POST data using Ajax (XMLHttp). jQuery surprisingly does all that for you within a wrapper. Here’s an equivalent for the jQuery post:


$(document).ready(function(){
	$( '[name="eval|hostname"]' ).bind("blur", getAvailableHost);
});

function getAvailableHost() {
	var $hostname = $( this );  //-- getAvailableHost() was set as an eventHandler on bind. So this refers to the hostname textbox
	var $spanHostname = $( "#id_availableHostname" ); //-- Span where the available hostname from post response will be set
	
	if ($hostname.val().match(/^[a-z0-9]+[a-z0-9-]*[a-z0-9]+$/g) == null) {
		alert("Enter valid hostname. Only Alphanumeric and Hyphens (in the middle of string) allowed.");
		$hostname.focus();
		return false;
	}
	$.post("getHostnameProxy.php",
		{
			hostname : $hostname.val(),
			domain : "yourdomain.com"
		},
		function(data, status) {
			//-- Expected data and status are returned by the server
	})
		.done(function(data) {
			var obj = jQuery.parseJSON(data);
			$spanHostname.text(obj.AvailableHost);	//-- Can also be accessed via obj['AvailableHost']
		})
		.fail(function() {
			$spanHostname.text('');
	});
	return true;
}

PS: The ‘hostname’ and ‘domain’ posted by the Ajax call can be accessed on the server using from the POST packet. e.g. PHP server script can access via $_POST[‘hostname’] and $_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