How to submit a form using JQuery Ajax and PHP

10

In this tutorial we learn how to submit a form using Ajax and PHP in a Simple Example.



Introduction

Ajax (Asynchronous JavaScript and XML) is a Technic that allow the web application to be updated asynchronously with data without load server side.

In this tutorial, we will submit a form by using Ajax. After Click the submit button, Ajax will post the data asynchronously. We can post any type of data like simple text field, Images, Files, Dropdown list etc. For that we will create a simple form and send the data by Ajax. PHP(Any backend script) is used to get post data in the server side.

Create a HTML Form

We will create a simple form in html. We need to define form Id. In the below form, form id is ‘myform’. We will use form id to get all input data by Ajax.

<!DOCTYPE html>
<html>
  <head>
    <title>Form Validation</title>
    <!-- Latest compiled and minified BootStarp CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  </head>
  <body>
    <div id="page-wrapper" >
      <div class="container" >
        <h1>
          Send Post Data to AJAX
        </h1>
        <form name="myForm" class="form-horizontal" id ="myform" action="#"  
                 method="POST" enctype="multipart/form-datam">
          <div class="panel panel-info">
            <div class="panel-heading">Form</div>
            <div class="panel-body">
              <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="name" class="col-md-4">Name *</label>
                      <div class="col-md-6">
                        <input type="text" class="form-control" id="name" name="name" 
                                placeholder="Enter Name" required/>
                      </div>
                    </div>
                    <div class="form-group" >
                      <label for="Mobile" class="col-md-4">Mobile *</label>
                      <div class="col-md-6">
                        <input type="text" class="form-control"  id="mobile" name="phone"
                                 placeholder="Enter Mobile Number" required/>
                      </div>
                    </div>
                    <div class="form-group  ">
                      <label for="email" class="col-md-4">Email </label>
                      <div class="col-md-6">
                        <input type="text" class="form-control" name="email" 
                             placeholder="Enter  Email" >
                      </div>
                    </div>
                     <div class="form-group  ">
                      <label for="image" class="col-md-4">Select Image </label>
                      <div class="col-md-6">
                        <input type="file" class="form-control" name="image" >
                      </div>
                    </div>
                  </div>
              </div>
            </div>
          </div>
          <div class="col-md-4 col-md-offset-4" style="margin-bottom: 50px;">
            <center>
              <input type="submit" class="btn btn-primary" value="Submit" />
            </center>
          </div>
        </form>
      </div>
    </div>
  </body>
</html>

send_post_from_ajax


Create Js Function

Now, We will create a method in the js file. This method is used to send POST data by using AJAX.

<script>
function submitForm() {
           
  var form_data = new FormData(document.getElementById("myform"));
  form_data.append("label", "WEBUPLOAD");
  $.ajax({
      url: "YOUR URL HERE",
      type: "POST",
      data: form_data,
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
  }).done(function( data ) {
    console.log(data);
    //Perform ANy action after successfuly post data
      
  });
  return false;     
}
</script>

Call JS function on Click submit button

We will add onsubmit=”return submitForm();” in the <form> tag. When we add onsubmit in the form tag, then it will be call submitform() method after click on the submit form to send post data to server.

<form name="myForm" class="form-horizontal" id ="myform" action="#"  
        onsubmit="return submitForm();"method="POST" enctype="multipart/form-datam">

Get POST Request in the backend

We can use any back-end script to get post request but here we will use PHP.

<?php 
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$image = $_FILES['image'];
?>
  • ekta

    hello, my question is relate for codeigniter, when i use bootbox than how can i pass Ajax value for comparison to database for password is correct or not?

    when admin delete a record before doing this action admin re-enter the password if is this correct then delete this record otherwise error message was display.

    my javascript value is under:

    $(document).on(“click”, “.confirm”, function(e)
    {
    e.preventDefault();
    var lHref = $(this).attr(‘href’);
    var base_url = ”;
    bootbox.prompt({
    title: “are u sure delete?Enter Password”,
    inputType: ‘password’,
    url:base_url + ‘admin/user.php/login’,
    $.post(“user.php”, { password: password },
    callback:function(result) {
    if(result)
    {
    top.location.href = e.target.href;

    }

    }
    });

    });

    https://uploads.disquscdn.com/images/406a077fa140a3cb0e64025ce40608b837e8c0514d5b10a4ef07a8cb001965e9.png

    this is my prompt and when i press ok record delete but password not compare, if i enter wrong password also delete the record, i want if admin enter correct password after take action otherwise error display

    • Hi Ekta,
      You can also use Ajax,

      var confirm_call = confirm(“are u sure delete?Enter Password”);

      if (confirm_call === true) {

      $.ajax({
      type: ‘POST’,
      url: base_url + ‘admin/user.php/login’,
      data: {password: “Your Password”},
      success: function (response) {
      if (response === “ERROR”) {
      alert(“Please Enter Correct Password”);
      } else {
      // Success
      }

      }
      });
      } else {
      return false;
      }

      • ekta

        in this code how i add the prompt box for enter password?

    • To compare Password, you need to use backend. If success then echo “Success” else echo “ERROR”.