jQuery ajax GET example with PHP with complete example

jQuery ajax GET example with PHP with complete example

jQuery Ajax is the powefull tool of jQuery, You can create attractive webpage with the help of JQuery ajax. jQuery's Ajax methods return a superset of the XMLHTTPResuest 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.

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.

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

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

$.ajax({
    type: "GET",
    url: 'server.php',
    success: function(data){
        alert(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

<?php 
require_once('config.php');
if(isset($_GET['action']) && $_GET['action'] == 'get_record'])){
  
  $mysql_query = mysqli_query($conn, "Select * from my_ajax");
  while($mysql_rows = mysqli_fetch_array($mysql_query)){
     $firstname = $mysql_rows['firstname'];
     $lastname = $mysql_rows['lastname'];
     $email = $mysql_rows['email'];
     echo 'firstname: '.$firstname.'<br>';
     echo 'lastname : '.$lastname .'<br>';
     echo 'email : '.$email .'<br>';
  }
}
else{
  echo "Something went wrong";
}
mysqli_close($conn);
?> 

Finally create your index page to call server_ajax.php:

<!DOCTYPE html>
    <html lang="en">
    <head>
    <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">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: 'server_ajax.php',
            data: {action: 'get_record'},
            success: function(data){
               $("#result").append(data);
            }
        });
    });
    </script>
    </head>
    <body>
        <div id="result"></div>
    </body>
</html>

Related posts

Write a comment