Submitting the form with Ajax

Submitting the form with Ajax

AJAX (Asynchronous JavaScript and XML) is a great technique usually used for updating the portion of a web page without refreshing the whole page. Through the help of ajax technique it will make the web application much better, faster, and interactive. To submit the form with ajax we will be working with procedural PHP, HTML and ajax.

At the end of this tutorial, we’ll provide you a source code and database link.

Table of Content

  1. Setting up assets file and project folder
  2. Configure Database
  3. Creating the HTML form page to display
  4. Creating the PHP file to process
  5. Submitting the form using Ajax

1. Setting up assets file and Project folder

In this part, we assume that you have downloaded the jQuery file from a jQuery official website. If you haven’t downloaded yet, then click here to download.

First of all, create the project folder named as “submit_from_using_ajax” or something else you wanted and inside that project folder create an another folder named as “jquery” i.e. [submit_form_using_ajax/jquery] which contains the downloaded jquery plugin. Now move or come back to the project folder directory and create three files namely index.php, add.php, and add.js e.g. [submit_form_using_ajax/index.php], [submit_form_using_ajax/add.php], and [submit_form_using_ajax/add.js]. If you have followed the instruction correctly then the folder and file structure should look like below:

submit_form_using_ajax_file_structure

2. Configure Database

Database Name: members
Table Name: members
Table Column: id, fname, lname, contact, active

Copy and paste this following SQL command into your MySQL database to create database and table.

CREATE DATABASE `members`;

CREATE TABLE `members`.`members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) NOT NULL,
  `lname` varchar(255) NOT NULL,
  `contact` varchar(20) NOT NULL,
  `active` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3;

3. Creating the HTML form

We’ll be using HTML form elements to create a simple form since designing is not our main concern. Firstly, go to the index.php file which was created at chapter 1. Copy and paste these codes into index.php file and we will go through them afterwards :

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>


<form action="add.php" method="post" id="submitForm">
	<label>First Name</label>
	<input type="text" name="fname" id="fname" />
	

	<label>Last Name</label>
	<input type="text" name="lname" id="lname" />

	

	<label>Contact</label>
	<input type="text" name="contact" id="contact" />	

	

	<button type="submit">Submit</button>

</form>


<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</body>
</html>

In above codes, input field and button are kept inside the form element. After that, the action of the form is defined as add.php and method is defined as “POST” so when submitting the form, the input value will not be visible to the users. Lastly, the form id is defined as submitForm, which will be using in Ajax’s part in Chapter 5. The highlighted codes are crucial to run the Ajax function. The first script links to the jQuery plugin and the second script links to add.js.

Whenever you submit the form, the page will redirect to a blank page. That part will be done in next chapter.

4. Creating the PHP file to process

This part is the straightforward. To process the form, we will be creating an uncomplicated PHP script to process the form. Copy and paste these codes into add.php file and we will go through them afterward:

<?php if($_POST) { $localhost = "127.0.0.1"; $username = "root"; $password = ""; $dbname = "members"; // connect $connect = new mysqli($localhost, $username, $password, $dbname); // checking the connection if($connect->connect_error) {
		die("connection failed : " . $connect->connect_error);
	} else {
		// echo "Connected Successfully";
	}

	$fname = $_POST['fname'];
	$lname = $_POST['lname'];
	$contact = $_POST['contact'];

	$sql = "INSERT INTO members (fname, lname, contact) VALUES ('$fname', '$lname', '$contact')";
	if($connect->query($sql) == TRUE) {
		echo "Successfully added";
	} else {
		echo "Error while added the information";
	}

	$connect->close();
	// closing the database connection


}

?>

This tutorial guides you to simply submit the ajax form. Hence, the form validation is not implemented in this script. The first line of the script checks a form submitted using a $_POST variable furthermore, creates a database connection and executes the query. After that, it checks query is executed successfully and returns proper messages. At the end of the script, the opened database connection is closed to prevent from an open database connection.

If you try to submit the form then the script will return proper messages.

5. Submitting the form using Ajax

Finally, we reached the main part of this tutorial. To submit the form with Ajax, we’ll need to do several things in our JavaScript file. Firstly, we need to capture the forms’ submit button so that the default action does not occur. Secondly, we need to pass the form data to the server by using Ajax, and display an appropriate message. For now, copy and paste these codes into the add.js file and we will go through them afterward:

$(document).ready(function() {
	$("#submitForm").unbind('submit').bind('submit', function() {
		var form = $(this);

		var url = form.attr('action');
		var type = form.attr('method');

		// sending the request to server
		$.ajax({
			url: url,
			type: type,
			data: form.serialize(),
			dataType: 'text',
			success:function(response) {
				$("#submitForm")[0].reset();
				alert(response);
			}
		});

		return false;
	});
});

Now when you submit the form, the JavaScript code catches that event by #submitForm id which was created in Chapter 3. The variable form holds the input values, and the url and type variable gets the form action and method values respectively. After that, the jquery built-in ajax function will be used to sent the data to a server which was defined in a form element. The serialize function is used to convert the values into an array instead of pulling the form data individually.

The below video displays a detailed tutorial of submitting the form using Ajax. We recommend you to go through the above chapters and then watch this video to fully understand how the Ajax form works.

Download Source Code!!!

Download Database!!!

Posted in Uncategorized

One thought on “Submitting the form with Ajax

Leave a Reply

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