jQuery ajax POST example with PHP

jQuery Ajax is the powerful tool of jQuery, You can create an attractive webpage with the help of JQuery ajax. jQuery's Ajax methods return a superset of the XMLHttpRequest object.

There are two commonly used methods for a request between a client and server: GET and POST.

GET - Requests data from a specified resource, basically used for just retrieving some data from the server.

POST - Submits data to be processed to a specified resource, used for setting some data to the server and also can retrieving tha data. POST method never caches data.

Download Now Laravel Project with Admin Dashboard

Ajax request is just like a web page call. Only difference is that the user doesn’t have to reload the page and user operation will be performed. Before you call a Ajax request you need to set JQuery link in your page, You can also download it.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Let’s get start with a basic JQuery Ajax POST request:

    type: "POST",
    url: 'server.php',
    success: function(data){
    error: function (Status, errorThrown) {

Now create a Ajax page on your project where you can place your MySQL code with php script. You can set your file name like server_ajax.php

if(isset($_POST['firstname']) && isset($_POST['lastname']) && && isset($_POST['email']) ){
  $firstname = $_POST['firstname'];
  $lastname = $_POST['lastname'];
  $email = $_POST['email'];
  $sql = "INSERT INTO my_ajax (firstname, lastname, email)
  VALUES ($firstname, $lastname, $email)";
  if (mysqli_query($conn, $sql)) {
    echo "New record inserted successfully";
  } else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  echo "Something went wrong";

Finally create your index page to call server_ajax.php:

<!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8">
    <title>JQuery Ajax POST Example</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
            type: "POST",
            url: 'server_ajax.php',
            data: {firstname: 'Tony', lastname: 'stark', email: 'tony@mymail.com'},
            success: function(data){
        <div id="result"></div>

Did you find this page helpful? X