Inserting Data using Ajax in PHP

Inserting data using ajax is really a very simple job if you already know a form submit and calling a JavaScript function, I am sure after reading this article you will think ajax is a child code.

What is the role of Ajax?

First of all, why do we need ajax? Let go back to my previous lecture http://jinnahsoft.net/learn/form-submit-in-php/ when we hit submit button it will call receive.php and through data where we receive data and insert in database but our current form file not remain open as we called other file receive.php we may go back with header function but point it will take time loading, reloading all page again and again we don't need this. What we need we click on the submit button current page will remain open and all the submit process will be done in backend and we get message of insert is successfully This will be done by Ajax.

Basic requirements before ajax

Before inserting data using ajax, we simply know how to insert data in php and calling a JavaScript function which is handling ajax functionality.

Let's create a table, a simple html form, a javascript function having ajax functionality and php script for submitting data in database. First create a table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Secondly a simple html form will connect it with JavaScript after it.

<html>
<head>
</head>
<body>
<div id="response"> </div>
<form  name="formData">
<input name="user_name" value="" type="text" required /> <br />
<input name="password" value="" type="text" required /> <br />
<input name="email" value="" type="text" required /> <br />
<input name="phone" value="" type="text" /> <br />
<input name="address" value="" type="text" /> <br />
<input type="button" onclick="return submitData()" Value="Submit" />
</form>
</body>
</html>

simple JavaScript function having ajax functionality. I am doing simple coding so new students understand easily.

<script>
function submitData() {
  var user_name=document.formData.user_name.value;
  var password=document.formData.password.value;
  var email=document.formData.email.value;
  var phone=document.formData.phone.value;
  var address=document.formData.address.value;
  
  if (user_name == "") {
    document.getElementById("response").innerHTML = "Please fill required fields";
    return false;
  } else {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
      document.getElementById("response").innerHTML = this.responseText;
    }
  xmlhttp.open("GET", "receive.php?user_name=" + user_name + "&password=" + password+"&email=" + email+"&phone=" + phone+"&address=" + address);
  xmlhttp.send();
  }
}
</script>

Finally, we write the receive.php which receives data, inserts it in database and prints response text.

<?php
$server_name = "localhost";
$db_user_name = "username";
$db_password = "password";

// Create connection
$con = mysqli_connect($server_name , $db_user_name , $db_password );

// Check connection
if (!$con) {
  die("Connection Error: " . mysqli_connect_error());
}

// receiving form fields
$user_name= $_REQUEST['user_name'];
$password= $_REQUEST['password'];
$email= $_REQUEST['email'];
$phone= $_REQUEST['phone'];
$address= $_REQUEST['address'];

// running insert query
$sql = "INSERT INTO users (`user_name`, `password`, `email`, `phone`, `address`) VALUES ('".$user_name."', '".$password."', '".$email."', '".$phone."', '".$address."')";
if(mysqli_query($con, $sql)){
    echo "User created successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}

Testing Ajax working

Whatever you print in php file will get back in JavaScript function

this.responseText;

this line containing all print text of php file so it important for developers some time we doing all things but nothing doing then we use this feature.

First of all, we simple print in php file and check response is coming from php file, at least this is checking our ajax start working

Secondly, we receive parameters and then print these so it is confirmed we got parameter.

Next, we insert and print finally reply previous print need to delete as these are for only testing.

Form and JavaScript should be in same file like

<html>
<head>
<script>
function submitData() {
  var user_name=document.formData.user_name.value;
  var password=document.formData.password.value;
  var email=document.formData.email.value;
  var phone=document.formData.phone.value;
  var address=document.formData.address.value;
  
  if (user_name == "") {
    document.getElementById("response").innerHTML = "Please fill required fields";
    return false;
  } else {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
      document.getElementById("response").innerHTML = this.responseText;
    }
  xmlhttp.open("GET", "receive.php?user_name=" + user_name + "&password=" + password+"&email=" + email+"&phone=" + phone+"&address=" + address);
  xmlhttp.send();
  }
}
</script>
</head>
<body>
<div id="response"> </div>
<form  name="formData">
<input name="user_name" value="" type="text" required /> <br />
<input name="password" value="" type="text" required /> <br />
<input name="email" value="" type="text" required /> <br />
<input name="phone" value="" type="text" /> <br />
<input name="address" value="" type="text" /> <br />
<input type="button" onclick="return submitData()" Value="Submit" />
</form>
</body>
</html>

and both these files should be in the same folder.