How to upload image with ajax and php

AJAX (Asynchronous JavaScript and XML) is a popular technique to update part of a web page without reloading the whole page. The Ajax method will enhance the web application better, faster, and more interactive.

To upload the image into the database, we will be working with procedural PHP, and using the Ajax functionality to send the request to the server.

At the end of this tutorial, we have provided a source code and database link below section.

Table of Content

  1. Setting up assets file and project folder
  2. Configure the Database
  3. Creating a form
  4. Creating the PHP file to process
  5. Submitting the form using Ajax
  6. Display all uploaded data

1. Setting up assets file and project folder

The asset file that we will be working with in this tutorial is jquery, bootstrap, and fileinput. To download these files click on the asset name which will redirect to their official website.

Firstly, create the project folder named as upload_image or something else you desire. Secondly, after creating the project folder, go inside that project folder and create three folders (assets, php_action, uploads) i.e. [upload_image/assets], [upload_image/php_action] and [upload_image/uploads], and two php files namely i.e. [upload_image/index.php] and [upload_image/view.php].

In the assets folder, create the three folders namely bootstrap, jquery, and file input, and paste those downloaded plugins respectively. In the php_action folder create a php file and name the file an uploadImage.php which will be processing the image information into the database. The uploads folder contains the uploaded images.

If you have followed the instruction correctly then the project folder and file structure could look like the below:

Upload Image Folder and file structure

2. Configure the Database

Database Name: upload_image
Table Name: users
Table Column: id, name, image

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


CREATE DATABASE `upload_image`;

CREATE TABLE `upload_image`.`users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 

3. Creating a form

We will be using the Bootstrap framework to create a simple form for better UI. For now, go to the index.php file and paste these codes and we will go through them afterward.


<!DOCTYPE html>
<html>
<head>
	<title></title>
	<!-- boostrap css-->
	<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">

	<!-- file input css -->
	<link rel="stylesheet" type="text/css" href="assets/fileinput/css/fileinput.min.css">
</head>
<body>

	<div class="col-md-5 col-sm-5 col-md-offset-4 col-sm-offset-4">
		<div class="page-header">
			<h3>Upload Image with Ajax</h3>

			<a href="view.php" class="btn btn-default">View User</a>
		</div>

		<div id="messages"></div>

		<form action="php_action/uploadImage.php" method="post" enctype="multipart/form-data" id="uploadImageForm">
		  <div class="form-group">
		    <label for="fullName">Name</label>
		    <input type="text" class="form-control" id="fullName" name="fullName" placeholder="Name">
		  </div>
		  <div class="form-group">
		    <label for="exampleInputPassword1">Photo</label>		    
		    <div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>

            <div class="kv-avatar center-block" style="width:200px">
		        <input id="avatar-2" name="userImage" type="file" class="file-loading">
		    </div>
		  </div>
		  <button type="submit" class="btn btn-default">Submit</button>
		</form>

	</div>
	
	<!-- jquery -->
	<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
	<!-- bootsrap js -->
	<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js"></script>
	<!-- file input -->
	<script src="assets/fileinput/js/plugins/canvas-to-blob.min.js" type="text/javascript"></script>	
	<script src="assets/fileinput/js/plugins/sortable.min.js" type="text/javascript"></script>	
	<script src="assets/fileinput/js/plugins/purify.min.js" type="text/javascript"></script>
	<script src="assets/fileinput/js/fileinput.min.js"></script>

	<script type="text/javascript">
		var btnCust = '<button type="button" class="btn btn-default" title="Add picture tags" ' + 
		    'onclick="alert(\'Call your custom code here.\')">' +
	    	'<i class="glyphicon glyphicon-tag"></i>' +
		    '</button>'; 
		    
		$("#avatar-2").fileinput({
	    overwriteInitial: true,
	    maxFileSize: 1500,
	    showClose: false,
	    showCaption: false,
	    showBrowse: false,
	    browseOnZoneClick: true,
	    removeLabel: '',
	    removeIcon: '<i class="glyphicon glyphicon-remove"></i>',
	    removeTitle: 'Cancel or reset changes',
	    elErrorContainer: '#kv-avatar-errors-2',
	    msgErrorClass: 'alert alert-block alert-danger',
	    defaultPreviewContent: '<img src="uploads/default-avatar.jpg" alt="Your Avatar" style="width:160px"><h6 class="text-muted">Click to select</h6>',
	    layoutTemplates: {main2: '{preview} ' +  btnCust + ' {remove} {browse}'},
	    allowedFileExtensions: ["jpg", "png", "gif"]
		});
	</script>
</body>
</html>

In this file, we will be including the downloaded plugins and create the form to upload the images. In the above code at the head section, we will be including the bootstrap and fileinput css file. At the bottom of the body section, we will be including the jquery, bootstrap, and fileinput js files.

4. Creating the PHP file to Process

In this section, we will be creating a simple PHP script to store the uploaded image file in the server directory by giving a unique name and storing that name in the database. For now, copy and paste these codes into the uploadImage.php file which is located in the php_action folder i.e. [upload_image/php_ation/uploadImage.php].


<?php 

if($_POST) {
	// database connection
	$server = '127.0.0.1';
	$username = 'root';
	$password = '';
	$dbname = 'upload_image';

	$conn = new mysqli($server, $username, $password, $dbname);

	// check db connection
	if($conn->connect_error) {
		die("Connection Failed : " . $conn->connect_error);
	} 
	else {
		// echo "Successfully Connected";
	}

	$valid = array('success' => false, 'messages' => array());

	$name = $_POST['fullName'];

	$type = explode('.', $_FILES['userImage']['name']);
	$type = $type[count($type) - 1];
	$url = '../uploads/' . uniqid(rand()) . '.' . $type;

	if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
		if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
			if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {

				// insert into database
				$sql = "INSERT INTO users (name, image) VALUES ('$name', '$url')";

				if($conn->query($sql) === TRUE) {
					$valid['success'] = true;
					$valid['messages'] = "Successfully Uploaded";
				} 
				else {
					$valid['success'] = false;
					$valid['messages'] = "Error while uploading";
				}

				$conn->close();

			}
			else {
				$valid['success'] = false;
				$valid['messages'] = "Error while uploading";
			}
		}
	}

	echo json_encode($valid);

	// upload the file 
}

In the above codes, the first script checks if the form is submitted.  After that, the database connection is created and stored in the conn variable for further processing. Secondly, the uploaded image type is checked and creates a unique id for the image name and moves to the uploads folder, and stores the information in the database.

5. Submitting the form using Ajax

To upload the form using Ajax, we will need to do several things in the index.php file. Copy and paste these codes into the index.php file at the end of the script where avatar-2 is initiated.


<script>
   $(document).ready(function() {
      $("#uploadImageForm").unbind('submit').bind('submit', function() {

         var form = $(this);
         var formData = new FormData($(this)[0]);

         $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: formData,
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            async: false,
            success:function(response) {
               if(response.success == true) {
                  $("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                  response.messages + 
               '</div>');

                  $('input[type="text"]').val('');
                  $(".fileinput-remove-button").click();
               }
               else {
                  $("#messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                  response.messages + 
               '</div>');
               }
            }
         });

         return false;
      });
   });
</script>

In the above codes, the form on submit event is caught by #uploadImageForm id which was created in Chapter 3. The form variable holds the action, and method values of the form element, whereas the formData variable holds the data of the form. After that, the jquery built-in Ajax function will be used to process the data to the server and respond with the message state.

6. Display all uploaded data

In this section, we will be displaying the users’ information that is stored in the database. Copy and paste these codes into the view.php file which is located at [upload_image/view.php].


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

	<!-- boostrap css-->
	<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">
</head>
<body>

<br /> <br /> <br />
<div class="col-md-5 col-sm-5 col-md-offset-4 col-sm-offset-4">
	<a href="index.php" class="btn btn-default">Back</a>
	<table class="table table-bordered">
		<tr>
			<th>S.no</th>
			<th>Name</th>
			<th>Photo</th>
		</tr>

		<?php 
		// database connection
		$server = '127.0.0.1';
		$username = 'root';
		$password = '';
		$dbname = 'upload_image';

		$conn = new mysqli($server, $username, $password, $dbname);

		// check db connection
		if($conn->connect_error) {
			die("Connection Failed : " . $conn->connect_error);
		} 
		else {
			// echo "Successfully Connected";
		}

		$sql = "SELECT * FROM users";
		$query = $conn->query($sql);

		$x = 1;
		while ($result = $query->fetch_assoc()) {
			$image = substr($result['image'], 3);

			echo "<tr>
				<td>".$x."</td>
				<td>".$result['name']."</td>
				<td> <img src='".$image."' style='height:100px; width:100px;' /> </td>
			</tr>";
			$x++;
		}

		?>
	</table>
</div>

</body>
</html>

Download Source Code

Download

Simple CRUD with PHP, MYSQLI

CRUD (Create, Retrieve, Update, Delete) is a usual job in web development. In Later Career, as a web developer, you’ll encounter lots of CRUD functionality in your career. The design of a CRUD will allow the users to create/retrieve/update/remove the data from the front end of the system. Generally, with the help of PHP as a server-side programming language, the data will be stored in MYSQL Database. PHP as a server-side language will be manipulating MYSQL Database tables to perform a particular action triggered by the users.

Table of Content

  1. PHP CRUD Part 1 Introduction
  2. PHP CRUD Part 2 Configure Database
  3. PHP CRUD Part 3 Setting up project folder
  4. PHP CRUD Part 4 Database Connection
  5. PHP CRUD Part 5 Create
  6. PHP CRUD Part 6 Retrieve
  7. PHP CRUD Part 7 Update
  8. PHP CRUD Part 8 Remove

1. PHP CRUD Part 1 Introduction

In this section, the overall CRUD operation is introduced as well as we are going to develop a simple CRUD (Create, Retrieve, Update, Delete) PHP operation. In a web application, these are the basic stuff required to create, retrieve, update, and delete the data using PHP with MYSQL Database. You will be creating the database tables and inserting the data into the database tables without any fatal errors. This is an uncomplicated and easy tutorial to learn a CRUD operation. To understand how CRUD operations work, I recommend you go through each part of this tutorial.

The below video illustrates the final system of this tutorial. The source code of this application will be provided at the end of this tutorial.

2. PHP CRUD Part 2 Configure Database

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

To create the database in this tutorial, there are two ways.

2.1 First way to create database

Copy and paste the following SQL command in your MySQL database to create a database and table



CREATE DATABASE `php_crud`; 

// create table
CREATE TABLE `php_crud`.`members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`contact` varchar(255) NOT NULL,
`age` varchar(255) NOT NULL,
`active` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;



2.2 Second way to create database

A tutorial video to demonstrate to you, how to create a database and tables for this tutorial

3. PHP CRUD Part 3 Setting up project folder

In this part, we will be creating a project folder and files for this tutorial. First of all, create the project folder as “crud_php”. After that create the create.php, edit.php, index.php, and remove.php files inside this project folder as shown [crud_php/create.php], [crud_php/edit.php] and so on.

Second, Create a folder named “php_action” inside this project folder as [crud_php/php_action] which will handle the server-side processing actions. In this directory create a create.php, db_connect.php, remove.php and update.php file as shown [crud_php/php_action/create.php], [crud_php/php_action/db_connect.php], and so on.

The current file structure should look like the below if you have followed the steps correctly:

CRUD_PHP_FOLDER

The video displays you to create a project folder and files for this tutorial.

4. PHP CRUD Part 4 Database Connection

The db_connect.php file i.e. [php_action/db_connect.php], this file contains a database connection. In this application, the db_connect.php file will be used to perform any action for CRUD. Such as connecting to the database, executing the query, and closing the connection.


<?php 

$localhost = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "php_crud"; 

// create connection 
$connect = new mysqli($localhost, $username, $password, $dbname); 

// check connection 
if($connect->connect_error) {
	die("connection failed : " . $connect->connect_error);
} else {
	// echo "Successfully Connected";
}

?>

5. PHP CRUD Part 5 Create

5.1 Adding “Add Member” Button and “Action” button

To start with the create.php page we need a button that will lead to create.php page. Open index.php file which we created in Chapter 3 in this tutorial. And add an “Add Member” button at the top of the table, and an “Edit”, and “Remove” buttons at each row of the table.

Now the index.php file’s code should look like below, the highlighted code is what we need to implement in this tutorial.



<?php require_once 'php_action/db_connect.php'; ?>

<!DOCTYPE html>
<html>
<head>
	<title>PHP CRUD</title>

	<style type="text/css">
		.manageMember {
			width: 50%;
			margin: auto;
		}

		table {
			width: 100%;
			margin-top: 20px;
		}

	</style>

</head>
<body>

<div class="manageMember">
	<a href="create.php"><button type="button">Add Member</button></a>
	<table border="1" cellspacing="0" cellpadding="0">
		<thead>
			<tr>
				<th>Name</th>
				<th>Age</th>
				<th>Contact</th>
				<th>Option</th>
			</tr>
		</thead>
		<tbody>
			
		</tbody>
	</table>
</div>

</body>
</html>

Now if you go to the index.php page, you’ll see the “Add member” button. Eventually, the create.php is created at Chapter 3 and it will lead to a blank page when you click the “Add Member” button. In the next step, we will create a form to enter the member information into the system and add the member’s information to the database.

add member btn

5.2 Creating a Create page

In create.php file which you created in Chapter 3. This file contains an HTML form where the user’s input data will pass to the server side and add the information to the database.

The first part of this code is to create an HTML form with the required input field and pass the data to the server.


<!DOCTYPE html>
<html>
<head>
	<title>Add Member</title>

	<style type="text/css">
		fieldset {
			margin: auto;
			margin-top: 100px;
			width: 50%;
		}

		table tr th {
			padding-top: 20px;
		}
	</style>

</head>
<body>

<fieldset>
	<legend>Add Member</legend>

	<form action="php_action/create.php" method="post">
		<table cellspacing="0" cellpadding="0">
			<tr>
				<th>First Name</th>
				<td><input type="text" name="fname" placeholder="First Name" /></td>
			</tr>		
			<tr>
				<th>Last Name</th>
				<td><input type="text" name="lname" placeholder="Last Name" /></td>
			</tr>
			<tr>
				<th>Age</th>
				<td><input type="text" name="age" placeholder="Age" /></td>
			</tr>
			<tr>
				<th>Contact</th>
				<td><input type="text" name="contact" placeholder="Contact" /></td>
			</tr>
			<tr>
				<td><button type="submit">Save Changes</button></td>
				<td><a href="index.php"><button type="button">Back</button></a></td>
			</tr>
		</table>
	</form>

</fieldset>

</body>
</html>


The second part of this code insert process happens. Look through the codes and we will go through them afterward:


<?php 

require_once 'db_connect.php';

if($_POST) {
	$fname = $_POST['fname'];
	$lname = $_POST['lname'];
	$age = $_POST['age'];
	$contact = $_POST['contact'];

	$sql = "INSERT INTO members (fname, lname, contact, age, active) VALUES ('$fname', '$lname', '$contact', '$age', 1)";
	if($connect->query($sql) === TRUE) {
		echo "<p>New Record Successfully Created</p>";
		echo "<a href='../create.php'><button type='button'>Back</button></a>";
		echo "<a href='../index.php'><button type='button'>Home</button></a>";
	} else {
		echo "Error " . $sql . ' ' . $connect->connect_error;
	}

	$connect->close();
}

?>

Let us look at the beginning of the code. It first checks if the form is submitted by using a $_POST global variable. If a form is submitted then it inserts the data into the database by using $_POST. And check if the query is executed successfully then it displays a successful message and link button.

The end result should look like this if you have followed the instruction correctly. Click on Add Member on the index page and enter the member information into the input field. Click on the Save Changes button.

create

After creating some records by entering the member information, you should be able to see a CRUD grid as below:

create2

6. PHP CRUD Part 6 Retrieve

In the index.php page, we are going to retrieve the data that are stored in the database. This part is quite easy. We need a database connection file to execute the SQL command.
The highlighted codes are created for the edit and remove buttons. You can copy all the codes below.


<?php require_once 'php_action/db_connect.php'; ?>

<!DOCTYPE html>
<html>
<head>
	<title>PHP CRUD</title>

	<style type="text/css">
		.manageMember {
			width: 50%;
			margin: auto;
		}

		table {
			width: 100%;
			margin-top: 20px;
		}

	</style>

</head>
<body>

<div class="manageMember">
	<a href="create.php"><button type="button">Add Member</button></a>
	<table border="1" cellspacing="0" cellpadding="0">
		<thead>
			<tr>
				<th>Name</th>
				<th>Age</th>
				<th>Contact</th>
				<th>Option</th>
			</tr>
		</thead>
		<tbody>
			<?php
			$sql = "SELECT * FROM members WHERE active = 1";
			$result = $connect->query($sql);

			if($result->num_rows > 0) {
				while($row = $result->fetch_assoc()) {
					echo "<tr>
						<td>".$row['fname']." ".$row['lname']."</td>
						<td>".$row['age']."</td>
						<td>".$row['contact']."</td>
						<td>
							<a href='edit.php?id=".$row['id']."'><button type='button'>Edit</button></a>
							<a href='remove.php?id=".$row['id']."'><button type='button'>Remove</button></a>
						</td>
					</tr>";
				}
			} else {
				echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
			}
			?>
		</tbody>
	</table>
</div>

</body>
</html>

Now if you open this page “index.php”, you should see the member’s information on the table. As well as you should notice the “Edit” and “Remove” buttons at each table row data. They are not functional for this part. In the next part, we are going to learn about the update functionality for this tutorial.

index

7. PHP CRUD Part 7 Update

Go to edit.php file in [crud_php/edit.php] which was creating in Chapter 3. We will teach in two parts; the first part creating HTML form, and the second part server-side processing. The first part of the code is an HTML form to update the information of members. But it will not only update the data, but it will also display the member information. Copy the code below to the edit.php file at [crud_php/edit.php]:


<?php 

require_once 'php_action/db_connect.php';

if($_GET['id']) {
	$id = $_GET['id'];

	$sql = "SELECT * FROM members WHERE id = {$id}";
	$result = $connect->query($sql);

	$data = $result->fetch_assoc();

	$connect->close();

?>

<!DOCTYPE html>
<html>
<head>
	<title>Edit Member</title>

	<style type="text/css">
		fieldset {
			margin: auto;
			margin-top: 100px;
			width: 50%;
		}

		table tr th {
			padding-top: 20px;
		}
	</style>

</head>
<body>

<fieldset>
	<legend>Edit Member</legend>

	<form action="php_action/update.php" method="post">
		<table cellspacing="0" cellpadding="0">
			<tr>
				<th>First Name</th>
				<td><input type="text" name="fname" placeholder="First Name" value="<?php echo $data['fname'] ?>" /></td>
			</tr>		
			<tr>
				<th>Last Name</th>
				<td><input type="text" name="lname" placeholder="Last Name" value="<?php echo $data['lname'] ?>" /></td>
			</tr>
			<tr>
				<th>Age</th>
				<td><input type="text" name="age" placeholder="Age" value="<?php echo $data['age'] ?>" /></td>
			</tr>
			<tr>
				<th>Contact</th>
				<td><input type="text" name="contact" placeholder="Contact" value="<?php echo $data['contact'] ?>" /></td>
			</tr>
			<tr>
				<input type="hidden" name="id" value="<?php echo $data['id']?>" />
				<td><button type="submit">Save Changes</button></td>
				<td><a href="index.php"><button type="button">Back</button></a></td>
			</tr>
		</table>
	</form>

</fieldset>

</body>
</html>

<?php
}
?>

Let’s look at the code. At the beginning of the code, it catches the $id from a $_GET request. Then it fetches the information by that $id variable. After the data is retrieved from the database, the information is added to the input field. As well as the new input field is also appended to a name “id” to match the specific member data when the form is submitted.

In the Second part, the data update process is coded here. Open the update.php file in crud_php/php_action/update.php which was creating in Chapter 3. Open the file and copy and paste these codes.


<?php 

require_once 'db_connect.php';

if($_POST) {
	$fname = $_POST['fname'];
	$lname = $_POST['lname'];
	$age = $_POST['age'];
	$contact = $_POST['contact'];

	$id = $_POST['id'];

	$sql = "UPDATE members SET fname = '$fname', lname = '$lname', age = '$age', contact = '$contact' WHERE id = {$id}";
	if($connect->query($sql) === TRUE) {
		echo "<p>Succcessfully Updated</p>";
		echo "<a href='../edit.php?id=".$id."'><button type='button'>Back</button></a>";
		echo "<a href='../index.php'><button type='button'>Home</button></a>";
	} else {
		echo "Erorr while updating record : ". $connect->error;
	}

	$connect->close();

}

?>

Let us look at the beginning of the code. It first checks if the form is submitted by using a $_POST global variable. If a form is submitted then it updates the data in the database by using $_POST. And check if the query is executed successfully then it displays a successful message and link button.

If you followed the step correctly then your edit.php file should look like the below:

update

8. PHP CRUD Part 8 Remove

Go to remove.php file in [crud_php/remove.php] which was creating in Chapter 3. The logic is the same as we learned in Chapter 7 Update . In the first part, we’ll create HTML, and in the second part a server-side processing file. Copy the code below to the edit.php file at [crud_php/remove.php]:


<?php 

require_once 'php_action/db_connect.php';

if($_GET['id']) {
	$id = $_GET['id'];

	$sql = "SELECT * FROM members WHERE id = {$id}";
	$result = $connect->query($sql);
	$data = $result->fetch_assoc();

	$connect->close();
?>

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

<h3>Do you really want to remove ?</h3>
<form action="php_action/remove.php" method="post">

	<input type="hidden" name="id" value="<?php echo $data['id'] ?>" />
	<button type="submit">Save Changes</button>
	<a href="index.php"><button type="button">Back</button></a>
</form>

</body>
</html>

<?php
}
?>

Let’s look at the code. At the beginning of the code, it catches the $id from a $_GET request. Then it fetches the information by that $id variable. After the data is retrieved from the database, a new input field is also appended named “id” to match the specific member data when the form is submitted.

If you followed correctly, then the remove.php page should be similar to the below:

remove



<?php 

require_once 'db_connect.php';

if($_POST) {
	$id = $_POST['id'];

	$sql = "UPDATE members SET active = 2 WHERE id = {$id}";
	if($connect->query($sql) === TRUE) {
		echo "<p>Successfully removed!!</p>";
		echo "<a href='../index.php'><button type='button'>Back</button></a>";
	} else {
		echo "Error updating record : " . $connect->error;
	}

	$connect->close();
}

?>


Let’s look at the beginning of the code. It first checks if the form is submitted by using a $_POST global variable. If a form is submitted then it removes the data. And checks if the query is executed successfully then it displays a successful message and button link.

Download Source Code!!!!

Download

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. The help of the Ajax technique it will make the web application much better, faster, and more 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 with 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 it yet, then click here to download.

First of all, create the project folder named “submit_from_using_ajax” or something else you wanted and inside that project, folder create another folder named “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 the 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 the following SQL command into your MySQL database to create a 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 the index.php file and we will go through them afterward:


<!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 the above codes, the input field and button are kept inside the form element. After that, the action of the form is defined as add.php and the 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 the next chapter.

4. Creating the PHP file to process

This part is 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 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 send 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 for submitting the form using Ajax. We recommend you go through the above chapters and then watch this video to fully understand how the Ajax form works.

Download Source Code!!!

Download

Online Inventory Management Software with PHP, Open Source

Online Inventory Management Software is an open-source project developed by procedural PHP, MySQL, bootstrap, and jquery. This application is based on a web application and developed with procedural PHP, MySQL database, jquery, datatables plugins, and Bootstrap. This application provides users to manage brands, categories, products, orders, and reports. This system provides the best inventory management software features. This system can be also used for small businesses. It is free web-based inventory management software.

On the brand’s page, the admin can add, update, and remove the brand’s information. In the product section, the admin can add product information and manage the stock. In the order section, the application will manage the stock of the product and generates the total amount of payment to be paid by the client. The application can also generate the orders report based on the month you select.

Requirements

  • PHP Version +5.4.4
  • Web Server ( Recommended: Apache with PHP and Mysqli )

Features

  • View of the total number of brands, categories, products, and orders.
  • Add, update, and remove brand information.
  • Add, update, and remove categories information.
  • Add, update, and remove product details.
  • Add, update, and remove order details.
  • Print orders invoice.
  • Update order payment.
  • Generate the orders report by selecting specific start and end dates.
  • Change Password
  • Change Username

Users

  • Admin
    • Username: admin
    • password: password

Change the VAT

To change the vat number, all you have to do is go to the order.js file which is located at [custom/js/order.js] and search for subAmount function. In line 555, you will see the VAT variable, change the VAT number that you desired. To change the vat number in the front end of the application, go to orders.php, and at line 369, you will see the VAT label, change it to the number you desire.

Download Online Stock Management System

Please Read:

While creating the database for this system, either you can create the name of the database as a stock or change the name at the php_action/db_connect.php file. As shown below:


<php 
$localhost = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "stock"; 

// db connection 
$connect = new mysqli($localhost, $username, $password, $dbname);

// check connection 
if($connect->connect_error) {
   die("Connection Failed : " . $connect->connect_error);
} else {
   // echo "Successfully connected";
}

?>

System Live Preview

Live Preview

For Source Code:

Download