πŸŽ‰ New: Top 75 PHP Interview Questions for 2026 β€” Free for all learners

AJAX Cheatsheet β€” The Complete Developer Reference

P
php Guru
Β· November 24, 2025 Β· 5 min read Β· Updated November 24, 2025
ajax cheatsheet, ajax tutorial, ajax javascript, ajax fetch api, ajax example in php, ajax post request, ajax form submission, ajax json response, jquery ajax, asynchronous programming

πŸ“Œ Key Takeaways

  • AJAX Cheatsheet β€” The Complete Developer Reference
  • What is AJAX in Web Development?
  • Basic AJAX Workflow
  • AJAX Using XMLHttpRequest
  • AJAX Using POST Method
  • AJAX with JSON Response
Advertisement

AJAX (Asynchronous JavaScript and XML) is one of the most essential technologies for creating dynamic and interactive web applications. It allows developers to send and receive data from a server without reloading the page.

This AJAX Cheatsheet provides a complete guide for beginners and professionals who want to master AJAX with XMLHttpRequest, Fetch API, and jQuery AJAX methods β€” all in one place.


What is AJAX in Web Development?

AJAX isn’t a programming language β€” it’s a combination of technologies that work together to make asynchronous communication possible between the client and server.

Core Components of AJAX:

  • HTML/CSS β€” Display data and layout
  • JavaScript β€” Handle client-side logic
  • XMLHttpRequest or Fetch API β€” Send/receive data
  • PHP/Python/Node.js β€” Process backend requests
  • JSON/XML β€” Exchange data formats

Example Scenario:
When you type in a search box and results appear instantly β€” that’s AJAX at work!


Basic AJAX Workflow

StepDescription
1User triggers an event (e.g., button click)
2JavaScript creates an AJAX request
3Request is sent to the server
4Server processes the request
5Server sends back data (JSON/XML)
6JavaScript updates the webpage dynamically
ajax cheatsheet, ajax tutorial, ajax javascript, ajax fetch api, ajax example in php, ajax post request, ajax form submission, ajax json response, jquery ajax, asynchronous programming

AJAX Using XMLHttpRequest

Example: Simple AJAX GET Request

<!DOCTYPE html>
<html>
<body>
<h3>AJAX Example with XMLHttpRequest</h3>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>

<script>
function loadData() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "data.php", true);
  xhr.onload = function() {
    if (xhr.status == 200) {
      document.getElementById("result").innerHTML = xhr.responseText;
    }
  };
  xhr.send();
}
</script>
</body>
</html>

data.php

<?php
echo "Hello, this is a response from the server!";
?>

AJAX Using POST Method

<script>
function sendData() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "submit.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.onload = function() {
    alert(xhr.responseText);
  };
  xhr.send("name=John&age=25");
}
</script>

AJAX with JSON Response

fetch('user.php')
  .then(response => response.json())
  .then(data => {
    console.log(data.name);
  });

user.php

<?php
$user = array("name" => "Alice", "email" => "alice@example.com");
echo json_encode($user);
?>

AJAX Using Fetch API (Modern Way)

The Fetch API is the modern replacement for XMLHttpRequest.

fetch('data.php')
  .then(response => response.text())
  .then(data => document.getElementById("output").innerHTML = data)
  .catch(error => console.error('Error:', error));

AJAX in jQuery

jQuery simplifies AJAX syntax dramatically:

$.ajax({
  url: "server.php",
  type: "POST",
  data: { name: "John", age: 30 },
  success: function(response) {
    $("#output").html(response);
  },
  error: function() {
    alert("Error fetching data!");
  }
});

Shortcut Methods:

$.get("data.php", function(response){ console.log(response); });
$.post("submit.php", {id:1}, function(data){ console.log(data); });

Handling JSON with jQuery AJAX

$.getJSON("user.php", function(data){
  $("#name").text(data.name);
  $("#email").text(data.email);
});

AJAX Error Handling

Use .catch() or error callbacks to manage request failures:

fetch('invalid.php')
  .then(response => {
    if (!response.ok) throw new Error('Network error');
    return response.json();
  })
  .catch(error => console.error('Error:', error));

Common AJAX Status Codes

Status CodeMeaning
200OK β€” Request succeeded
201Created β€” Resource created
400Bad Request
401Unauthorized
404Not Found
500Internal Server Error

AJAX Security Best Practices

βœ… Validate and sanitize all input on the server side
βœ… Use HTTPS to secure data transfer
βœ… Set proper CORS headers
βœ… Prevent CSRF attacks with tokens
βœ… Never expose sensitive data in AJAX responses


AJAX Examples with PHP Backend

Form Submission Without Page Reload:

<form id="contactForm">
  <input type="text" name="name" placeholder="Enter your name">
  <input type="email" name="email" placeholder="Enter your email">
  <button type="submit">Send</button>
</form>

<div id="response"></div>

<script>
document.getElementById("contactForm").onsubmit = function(e) {
  e.preventDefault();
  fetch("submit.php", {
    method: "POST",
    body: new FormData(this)
  })
  .then(res => res.text())
  .then(data => document.getElementById("response").innerHTML = data);
};
</script>

submit.php

<?php
echo "Thank you, " . htmlspecialchars($_POST['name']) . "! We received your message.";
?>

Advantages of Using AJAX

  • Enhances user experience
  • Reduces server load and bandwidth usage
  • Enables real-time updates (used in chat, notifications)
  • Improves page responsiveness
  • Supports asynchronous form submissions


FAQ β€” AJAX Cheatsheet

Q1: What does AJAX stand for?
AJAX stands for Asynchronous JavaScript and XML. It enables web pages to fetch data from a server without reloading.

Q2: Can AJAX work with JSON instead of XML?
Yes, modern web apps mostly use JSON for data exchange due to its simplicity.

Q3: Is AJAX used in React or Vue.js?
Yes, both frameworks support AJAX through the Fetch API or Axios library.

Q4: How can I debug AJAX requests?
Use browser DevTools β†’ Network tab to inspect requests and responses.

Q5: What is the difference between Fetch and XMLHttpRequest?
Fetch API provides a modern, promise-based interface, whereas XMLHttpRequest uses callbacks.

P
php Guru
← Previous Post
JSON Cheatsheet β€” The Ultimate Developer Reference
Next Post β†’
API Integration Cheatsheet β€” The Complete Developer Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove your humanity: 4   +   10   =