jQuery: AJAX Form Submission


A strategy to send data to server is using form. User fill out form and then data send to server. Rather then using on normal form submission mechanism, which will load the response in the entire browser window, you can use jQuery's AJAX. Ya, jQuery's AJAX toolkit have power to submit the form asynchronously and place the response inside the current page.

Ok. For practice, we have simple form:

<div id="form">
<form>
Name : <input type="text" name="urname"><br />
<input type="submit" name="submit" value="Submit">
</form>
</div>

we will cath data that sent to server. This is server code. Save as "data.php".

<?
$name = strtoupper($_REQUEST['name']);
if(isset($name)){
	$html = "<p>Your name: <b>".$name."</b></p>";
	print($html);
}
?>

Following code for our jQuery:

	$(document).ready(function() {
		$('#form form').submit(function(){
			$('#content').load('data.php', { 'name': $('input[name="urname"]').val()});						
			return false;
		});
	});

Below, complete code for "page.html"

<html>
<head>
	<script src="jquery.js" type="text/javascript"></script>
	<script type="text/javascript">
	$(document).ready(function() {
		$('#form form').submit(function(){
			$('#content').load('data.php', { 'name': $('input[name="urname"]').val()});						
			return false;
		});
	});
	</script>
</head>
<body>
<div id="form">
<form>
Name : <input type="text" name="urname"><br />
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div id="content">
</div>
</body>
</html>
jQuery AJAX Form Submission Simple Tutorial

If you want to sent more than one parameter. You can use .serialize(). To be more clear, try following code for page.html:

<html>
<head>
	<script src="jquery.js" type="text/javascript"></script>
	<script type="text/javascript">
	$(document).ready(function() {
		$('#form form').submit(function(){
			$.get('data.php', $(this).serialize(), function(data){
				$('#content').html(data);
			});				
			return false;
		});
	});
	</script>
</head>
<body>
<div id="form">
<form>
Name : <input type="text" name="urname"><br />
Birthplace : <input type="text" name="urbirth"><br />
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div id="content">
</div>
</body>
</html>

Following for data.php

<?
$name = strtoupper($_REQUEST['urname']);
$birth = strtoupper($_REQUEST['urbirth']);
if(isset($name)){
	$html = "<p>Your name: <b>".$name."</b></p>";
	$html .= "<p>Your birthplace: <b>".$birth."</b></p>";	
	print($html);
}
?>
jQuery AJAX Form Serialize Tutorial



Bookmark and Share Tag: jquery, JavaScript, JavaScript Framework Category: JavaScript Post : September 10th 2010 Read: 61,026

advertisements


blog comments powered by Disqus