jQuery

Submit a Form Using Jquery Ajax

In this tutorial, we are going to see how to submit a form using Jquery Ajax.

AJAX requests are becoming more and more popular as web applications seek to provide personalized elements dynamically. AJAX requests are methods of loading custom content separately from the rest of the HTML document, which allows caching of the entire HTML document, thus improving final load time.
 

Submit a simple HTML form

Let’s start with a simple HTML form, then we’ll see how to submit this form with Jquery Ajax:

<form action="test.php" method="post" id="myForm">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Address</label>
    <input type="text" name="address" />
    <input type="submit" name="submit" value="Submit the form" />
    <div id="res"></div>
</form>

Submit the HTML form data using the jQuery.ajax() method. The ajax() method is used to execute an AJAX (Asynchronous HTTP) request.

$("#myForm").submit(function(e){
	e.preventDefault(); //prevent a default action
	var form_url = $(this).attr("action"); //retrieve the form url
	var form_method = $(this).attr("method"); //retrieve the GET / POST method of the form
	var form_data = $(this).serialize(); //Encode the form elements for submission
	
	$.ajax({
		url : form_url,
		type: form_method,
		data : form_data
	}).done(function(response){ 
		$("#res").html(response);
	});
});

The .serialize() method serializes the form inputs to perform a request that can be sent using Ajax.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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