Learn PHP,HTML,CSS,Javascript,MySQL,Jquery

Monday, 19 October 2020

PHP Insert Data into MySQL Database Without Page Refresh Using JQuery Ajax


 PHP Insert Data without Page Refresh

Insert data into mysql database without page refresh or page reload can be achieved in php with the use of jquery and ajax. Its a very simple method of inserting html form data into mysql in php. After reading this post you will be able to save data into database without page reload using php,mysql and jquery ajax. 

PHP insert data into mysql table without page reloading
PHP AJAX insert data without page reload


What is JQuery ?

JQuery is a javascript library and it is used to perform different types of operations in websites ,web pages on front end. Jquery is mostly used to deal with the front end of web page. Jquery library is build with the use of javadcript. 

What is AJAX ?

AJAX stands for Asynchronous Javascript and XML.AJAX is a new technique for creating better,faster and more interactive web applications with the help of XML,HTML,CSSand Javascript. Web applications send and receive information from server.

PHP and JQuery insert data without page refresh or reload

Php Insert data Step-1

First step is to write html mark up code to build front end web page. For this purpose you can use any css design here I am using bulma css to build front end web page. Create a html form within this web page and a button at the end but within the closing form tag. This button type must be button. When we talk about insert,update data  using jquery ajax in php html form tag is not much important we can achieve our goals with or without html form. Simply write input fields. But if you enclose the input fields into html form it is a good practice of coding and in ajax coding you don't need to do much work. 
php insert data into mysql jquery ajax


Include below code within body tag of html
  
  <section class="hero is-fullheight is-success">
<div class="container">
<form id="user_form" method="post">
<div class="column">
<div class="box">
<h1 class="title has-text-centered" style="color: black;">Insert Data Without Page Refreshing Using Jquery and PHP</h1>
<div class="field is-horizontal">
<div class="field-body">
<div class="field">
<p class="control">
<label class="label">First Name</label>
<input class="input is-info is-large" id="txt_fname" name="txt_fname" type="text" />
</p>
</div>
<div class="field">
<p class="control">
<label class="label">Last Name</label>
<input class="input is-info is-large" id="txt_lname" name="txt_lname" type="text" />
</p>
</div>
</div>
</div>
<div class="field is-horizontal">
<div class="field-body">
<div class="field">
<p class="control">
<label class="label">Email</label>
<input class="input is-info is-large" id="txt_email" name="txt_email" type="email" />
</p>
</div>
<div class="field">
<p class="control">
<label class="label">Address</label>
<input class="input is-info is-large" id="txt_address" name="txt_address" type="text" />
</p>
</div>
</div>
</div>
<div class="field is-horizontal">
<div class="field-body">
<div class="field">
<p class="control">
</p>
</div>
<div class="field">
<p class="control">
<b id="mesg"></b>
<input class="button is-info is-large" id="btn_save" name="btn_save" type="button" value="Save" />
</p>
</div>`
</div>
</div>
</div>
</div>

</form>
</div>
</section>
 
  

Php insert data step-2

Write jquery code to insert data without page reload using php. At the very bottom but before closing body tag write jquery script and within this script tags write document.ready function of jquery.
 
      
      <script>
$(document).ready(function(){
$('#btn_save').click(function(){
	var data=$('#user_form').serialize()+'&btn_save=btn_save';
	$.ajax({
		url:'insert_data.php',
		type:'post',
		data:data,
		success:function(response){
		$('#mesg').text(response);
	$('#txt_fname').text('');
	$('#txt_lname').text('');
	$('#txt_email').text('');
	$('#txt_address').text('');
		}
	});
});
});
</script>
      
Within this document.ready function write button click function. You can call this function by using button id which is the most common way.

Within this button click function I am initializing a variable and storing form fields with jquery serialize function. In the next line I am using ajax. 
Within the ajax first place url state,herr you have to write url path of the php file where you will write php code to insert data into mysql database. Next state will be type i.e GET,POST. It recognize the form field type to php server. 

Third state will be data,in this state put the varibale name we have initialized first which is actually html form fields. Next state which is important in this scenario is success state of ajax. Here I will use a function which will execute after jquery perform the click event and it is used receive response from server side.

There are some other states of ajax if you want to learn about all ajax states you can learn from here. 

php insert data step-3 create a table in mysql database

Open phpmyadmin in anew tab of your browser and create a test database within this database create a table of any name here I have created person table and test database.


CREATE TABLE `person` (
  `id` int(11) NOT NULL,
  `firstname` varchar(100) NOT NULL,
  `lastname` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `address` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `person`
  ADD PRIMARY KEY (`id`);
  ALTER TABLE `person`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Php insert data step-4

In this step you have to create a new php file. In this file you will write backend or server side code to save data from html form into mysql database. In this way you will call,execute server side code using jquery ajax. Create a new file here the file name is insert_data.php, within this file we will write insert query ,execute insert query and display a response message after clicking either data is successfully inserted or failed to insert data.
I have created a separate config.php file for database connection code. This file is a common file with database connection variable initialization with php mysqli connection function.
Below is the code of config.php file

  < ? php
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password
$db_name="test"; // Database name
$conn=mysqli_connect($host,$username,$password,$db_name) or die ("Failed to connect with DB");
$base_url ='http://localhost/tutorials'; //plz change this url
? >
  
Below is the insert_data.php file code to insert data into database table

< ? php
include 'config.php';
if(isset($_POST['btn_save']))
{
$fname=mysqli_real_escape_string($conn,$_POST['txt_fname']);
$lname=$_POST['txt_lname'];
$email=$_POST['txt_email'];
$address=$_POST['txt_address'];
$sql="INSERT INTO `person`(`firstname`, `lastname`, `email`, `address`) VALUES ('$fname','$lname','$email','$address')";
$query=mysqli_query($conn,$sql) or die(mysqli_error($conn));
if($query)
{
	echo "Data Saved Successfully";
	
} else {
	echo "Failed to save data";
}
}
? >
When you will complete these three steps thenyou will be able to insert data without page reload. This is a very small basic example you can do more complex tasks with the help of jquery ajax and php.

4 comments:

  1. Can you add exanple files to download?
    I have a problem that POST variables are not sent to the insert_data.php file.

    ReplyDelete