How to send GET and POST AJAX request with JavaScript

AJAX is the only way that allows communicating client-side with the server side.

It is easier to send AJAX requests using JavaScript libraries or frameworks. But it is also good to know how to send AJAX request with plain Javascript.

Use the XMLHttpRequest object to communicate with the server.

In this tutorial, I show how you can send GET and POST AJAX requests with JavaScript and handle the request with PHP.

How to send GET and POST AJAX request with JavaScript


Contents

  1. Create a Table
  2. Database Configuration
  3. Create HTML layout
  4. Create a PHP file to handle AJAX request
  5. How to make an AJAX request with JavaScript
  6. Output
  7. Conclusion

1. Create a Table

Create employee table and added some records.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(80) NOT NULL, 
  `salary` varchar(20) NOT NULL,
  `email` varchar(80) NOT NULL
);

2. Database Configuration

Create a config.php for the database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());
}

3. Create HTML layout

Create 3 input text elements for entering the name, salary, and email. And a button element.

Added onclick event on the button which calls insertNewEmployee() function.

List records in the <table id='emptTable'> using JavaScript and AJAX.

Completed Code

<div>
    Name: <input type="text" id='txt_name'> <br>
    Salary: <input type="text" id='txt_salary'> <br>
    Email: <input type="text" id='txt_email'> <br>
    <input type="button" id="btn_submit" value="Submit" onclick="insertNewEmployee();">
</div>
<table id='empTable' border='1'>
    <thead>
        <tr>
            <th>Name</th>
            <th>Salary</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

4. Create a PHP file to handle AJAX request

Create 'ajaxfile.php' file to handle AJAX request.

For example purpose, I am handling both GET and POST requests in a single file.

Assigned 2 to $request.


GET request (fetch records)

Check if $_GET['request'] is set or not if set then assign $_GET['request'] to $request.

If $request == 1 then fetch all records from employee table and assign to $employeeData. Loop on the fetched records.

Initialize $response with id, emp_name, salary, and email keys.

Return $response Array in JSON format.


POST request (insert record)

If $request == 2 then read POST values using json_decode(file_get_contents("php://input")).

Assign values to variables and prepare INSERT query.

If the INSERT query is executed successfully then return 1 otherwise 0.

Completed Code

<?php

include "config.php";

$request = 2;

// Read $_GET value
if(isset($_GET['request'])){
   $request = $_GET['request'];
}

// Fetch records 
if($request == 1){

   // Select record 
   $sql = "SELECT * FROM employee";
   $employeeData = mysqli_query($con,$sql);

   $response = array();
   while($row = mysqli_fetch_assoc($employeeData)){
      $response[] = array(
         "id" => $row['id'],
         "emp_name" => $row['emp_name'],
         "salary" => $row['salary'],
         "email" => $row['email'],
      );
   }

   echo json_encode($response);
   exit;
}

// Insert record
if($request == 2){

   // Read POST data
   $data = json_decode(file_get_contents("php://input"));

   $name = $data->name;
   $salary = $data->salary;
   $email = $data->email;

   // Insert record
   $sql = "insert into employee(emp_name,salary,email) values('".$name."',".$salary.",'".$email."')";
   if(mysqli_query($con,$sql)){
      echo 1; 
   }else{
      echo 0;
   }

   exit;
}

5. How to make an AJAX request with JavaScript

Use XMLHttpRequest object to send AJAX request.

.open() – Methods takes 3 parameters –

  1. Request method – GET or POST.
  2. AJAX file path. Pass parameter with URL on GET request – ajaxfile.php?name=yogesh&city=bhopal.
  3. It is an optional parameter that takes Boolean value true or false. Default value is true. Pass true for asynchronous and false for synchronous request.

.setRequestHeader() – This method is used to set Content-Type. By default, 'application/x-www-form-urlencoded' content-type is set. You can change its value e.g. – application/jsonmultipart/form-data, etc.

.onreadystatechange – This property calls on request state change. Assign an anonymous function to process the response. If this.readyState == 4 && this.status == 200 means the server response is ready for processing.

.send() – This method send AJAX request. It is also used to send data.


AJAX GET request JavaScript

  • Syntax –
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxfile.php?request=1", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {

        // Response
        var response = this.responseText; 

   }
};
xhttp.send();

Above syntax with jQuery

$.ajax({
    url: 'ajaxfile.php?request=1',
    type: 'get',
    success: function(response){

    }
});

AJAX POST request JavaScript

  • Syntax –

application/x-www-form-urlencoded; charset=UTF-8 is a default Content-Type but you can use any other type e.g. – application/jsonmultipart/form-data, etc.

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true); 
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       // Response
       var response = this.responseText;
   }
};
var data = {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'};
xhttp.send(JSON.stringify(data));

Above syntax with jQuery

$.ajax({
   url: 'ajaxfile.php',
   type: 'post',
   data: {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'},
   success: function(response){

   }
});

Create 2 functions –

  • loadEmployees() – This function calls on page successfully loaded.

Create object of XMLHttpRequest. Specify GET request and AJAX file path with parameter ('ajaxfile.php?request=1') in .open() method. Set Content-type and handle server response with onreadystatechange property.

Parse the this.responseText to JSON object and select <table id='empTable'> <tbody> and empty it.

Loop on the response to read values. Create a new table row element and assign a response value in cell.

Send the request by calling send() method.

  • insertNewEmployee() – This function calls on Submit button click.

Read values from the textboxes and assign them in variables. If variables are not empty then create a data JSON object. Initialize data object with the textbox values.

Create XMLHttpRequest object and specify POST request and AJAX file path ('ajaxfile.php') in .open() method. Set Content-type to 'application/json' and handle server response with onreadystatechange property.

Assign this.responseText in response. If response == 1 then alert a message and call loadEmployees() function to fetch records.

Completed Code

loadEmployees();

// Send AJAX GET request with JavaScript
function loadEmployees() {
    var xhttp = new XMLHttpRequest();

    // Set GET method and ajax file path with parameter
    xhttp.open("GET", "ajaxfile.php?request=1", true);

    // Content-type
    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    // call on request changes state
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

             // Parse this.responseText to JSON object
             var response = JSON.parse(this.responseText);

             // Select <table id='empTable'> <tbody>
             var empTable = 
document.getElementById("empTable").getElementsByTagName("tbody")[0];

             // Empty the table <tbody>
             empTable.innerHTML = "";

             // Loop on response object
             for (var key in response) {
                  if (response.hasOwnProperty(key)) {
                      var val = response[key];

                      // insert new row
                      var NewRow = empTable.insertRow(0); 
                      var name_cell = NewRow.insertCell(0); 
                      var username_cell = NewRow.insertCell(1); 
                      var email_cell = NewRow.insertCell(2);

                      name_cell.innerHTML = val['emp_name']; 
                      username_cell.innerHTML = val['salary']; 
                      email_cell.innerHTML = val['email']; 

                  }
             } 

        }
    };

    // Send request
    xhttp.send();
}

// Send AJAX POST request with JavaScript (Insert new record)
function insertNewEmployee() {

    var name = document.getElementById('txt_name').value;
    var salary = document.getElementById('txt_salary').value;
    var email = document.getElementById('txt_email').value;

    if(name != '' && salary !='' && email != ''){

         var data = {name: name,salary: salary,email: email};
         var xhttp = new XMLHttpRequest();
         // Set POST method and ajax file path
         xhttp.open("POST", "ajaxfile.php", true);

         // call on request changes state
         xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {

                   var response = this.responseText;
                   if(response == 1){
                         alert("Insert successfully.");

                         loadEmployees();
                   }
              }
         };

         // Content-type
         xhttp.setRequestHeader("Content-Type", "application/json");

         // Send request with data
         xhttp.send(JSON.stringify(data));
    }

}

6. Output

View Output


7. Conclusion

A valuable skill for web developers is the ability to send GET and POST AJAX queries using JavaScript. The user experience can be enhanced by using AJAX to retrieve data from the server without reloading the full page.

With the use of XMLHttpRequest object send AJAX GET and POST requests.

In GET request directly pass data with a filename like – ajaxfile.php?name=yogesh&city=bhopal and in POST request pass your data in send() method.

You can also view other AJAX tutorials using JavaScript –

If you found this tutorial helpful then don't forget to share.