How to submit form without refreshing page with jquery and ajax

May 2, 2011 | In: JQuery

This is very simple artical for submit HTML form data without refreshing page with the help of JQuery and Ajax.
jQuery provides a rich set of methods for AJAX web development.
With jQuery AJAX, you can request TXT, HTML, XML or JSON data from a remote server using both HTTP Get and HTTP Post.

$.ajax(options) is the syntax of the low level AJAX function.
$.ajax offers more functionality than higher level functions like load, get, and post.
The option parameter takes name|value pairs defining url data, passwords, data types, filters, character sets, timeout and error functions.

Below is code for HTML form.

<form method="post" name="form">
	<ul>
		<li><input id="name" name="name" type="text" /></li>
		<li><input id="username" name="username" type="text" /></li>
		<li><input id="password" name="password" type="password" /></li>
		<li>
			<select id="gender" name="gender">
			<option value="">Gender</option>
			<option value="1">Male</option>
			<option value="2">Female</option>
			</select>
		</li>
	</ul>
	<div >
		<input type="submit" value="Submit" class="submit"/>
		<span class="error" style="display:none"> Please Enter Valid Data</span>
		<span class="success" style="display:none"> Registration Successfully</span>
	</div>
</form>


Javascript code for jquery ajax form submit

.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
	$(".submit").click(function() {
		var name = $("#name").val();
		var username = $("#username").val();
		var password = $("#password").val();
		var gender = $("#gender").val();
		var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender;
		
		if(name=='' || username=='' || password=='' || gender=='')
		{
			$('.success').fadeOut(200).hide();
			$('.error').fadeOut(200).show();
		}else{
			$.ajax({
			type: "POST",
			url: "result.php",
			data: dataString,
			success: function(){
				$('.success').fadeIn(200).show();
				$('.error').fadeOut(200).hide();}
			});
		}
		return false;
	});
});
</script>

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Inquire Now

 

Categories


PSD to Magento Advertisement Advertisement Advertisement


Latest comments

  • None found