Submit Form Using JQuery Ajax

Submit Form Using JQuery Ajax

Here we will show how you can submit form without page refresh. For submitting form we use JQuery and Ajax with PHP and MySQl.

First we create a table where we store user input data. 

Below we create a table user_data

				
					--
-- Table structure for table `user_data`
--
CREATE TABLE `user_data` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `mobile` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for table `user_data`
--
ALTER TABLE `user_data`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `user_data`
--
ALTER TABLE `user_data`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

				
			

Now we create a connection file for built connect between PHP and MySQL Database . File name is “connection.php .

				
					<?php
  $mysql_hostname = "localhost";
  $mysql_user     = "root";
  $mysql_password = "";
  $mysql_database = "DATABASE_NAME"; # Enter your Database name
  $bd = ($GLOBALS["___mysqli_ston"] = mysqli_connect($mysql_hostname,  $mysql_user,  $mysql_password)) or die("Opps some thing went wrong");
  mysqli_select_db( $bd, $mysql_database) or die("wrong");
?>
				
			

Now we create a form to take user inputs. create a file index.php.

				
					<!DOCTYPE html>
<html>
  <head>
    <title>Inflay.com | Submit a form without page refresh using jQuery Ajax PHP MySQL</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h3>Submit a form without page refresh using jQuery, Ajax, PHP and MySQL</h3>
      <br />
      <!-- Here the form to take input form user -->
      <form action="" method="post" name = "user_data" id = "user_data">
        <div class="row form-group">  
          <div class="col-md-4">
            <label for="name">Name</label>
              <input type = "text" class="form-control" id="name" name="name" value = "">
          </div>
        </div>
        <div class="row form-group">  
          <div class="col-md-4">
            <label for="email">Email</label>
              <input type = "email" class="form-control" id="email" name="email" value = "">
          </div>
        </div>
        <div class="row form-group">  
          <div class="col-md-4">
            <label for="email">Mobile</label>
              <input type = "text" class="form-control" id="mobile" name="mobile" value = "">
          </div>
        </div>
        <div class="row form-group">  
          <div class="col-md-4">
              <input type = "submit" class="btn btn-primary" name="submit" id="submit" value="Send">
          </div>
        </div>
      </form>
      <div class = "row">
        <strong>USER LIST</strong> 
      </div>  
      <div class = "row">
        <!-- Here we show input data to fetch from table -->
        <table border="1px solid">
          <thead><tr><th width="200px">Name</th><th width="200px">Email</th><th width="200px">Mobile</th></tr></thead>
          <tbody>
            <?php
              include_once('connection.php');
              $query = "SELECT * FROM user_data";
              $result  = mysqli_query($GLOBALS["___mysqli_ston"], $query);
              $num_result = mysqli_num_rows($result);
              if ($num_result > 0) 
              {
                while($row = mysqli_fetch_array($result))
                {
            ?>
                  <tr><td><?php echo $row["name"];?></td><td><?php echo $row["email"];?></td><td><?php echo $row["mobile"];?></td></tr>
            <?php
                }
              }
            ?>    
          </tbody>
        </table>
      </div>  
    </div>
  </body>
</html>
				
			

In above code we are taking data from user and show it in table format.

Below is code to submit user data via ajax to php file and take response from server without refresh page.

				
					<script type="text/javascript">
  $(document).ready(function(){
    $("#user_data").on("submit", function (e) {
      e.preventDefault();
      $.ajax({
              type: "POST",
              url: "insert.php",
              data: $(this).serialize(),       
              dataType: "json",
              success: function (result) {
                if(result.trim()=='Done')
                {
                  alert("User Data Inderted successfully!");
                  $('#user_data')[0].reset();
                }
                else
                {
                  alert("Something Wrong! Please Try again.");
                  return false;
                }
              }
      });
    }); 
  });  
</script>
				
			

Now we need file to perform insert operation request send by ajax  and return response to ajax.

So, we create a php file name “insert.php“.

				
					<?php include_once('connection.php');
 
  if (isset($_POST) && !empty($_POST)) 
  {
    $query = "INSERT INTO user_data (name, email, mobile) VALUES ( '".$_POST['name']."' , '".$_POST['email']."', '".$_POST['mobile']."')";
    $send = mysqli_query($GLOBALS["___mysqli_ston"], $query);
    $id = mysqli_insert_id($GLOBALS["___mysqli_ston"]);
    if ($id > 0) 
    {
      $result = "Done";
    }
    else
    {
      $result =  "Fail"; 
    }   
    echo json_encode($result);
  } 

?> 
				
			

I hope this article helps you.
Thanks for visiting Inflay.com .