PHP Ajax Tutorial with Example

โšก Smart Summary

Ajax in PHP lets a web page exchange small amounts of data with the server and update part of the page without a full reload. This walkthrough builds a live framework search, explaining the classic XMLHttpRequest approach and the modern Fetch API alternative.

  • ๐Ÿ”„ What Ajax Is: Ajax, Asynchronous JavaScript and XML, updates part of a page by exchanging data with the server without a full refresh.
  • โšก Why Use It: Ajax powers rich, desktop-like features such as autocomplete, live validation, and dependent dropdowns.
  • ๐Ÿ–ฅ๏ธ Client and Server: JavaScript runs in the browser and calls a PHP script, which returns just the data needed to update the page.
  • ๐Ÿ” Live Search: An onkeyup handler sends each keystroke to a PHP script that returns matching framework names instantly.
  • ๐Ÿ“œ XMLHttpRequest: The classic approach creates an XMLHttpRequest object and reads responseText when the request completes.
  • ๐Ÿ†• Fetch API: Modern code replaces XMLHttpRequest with the promise-based fetch function for cleaner, readable requests.
  • ๐Ÿค– AI Assist: AI tools can convert old XMLHttpRequest code to fetch or axios and help debug failing Ajax requests.

PHP Ajax

What is Ajax?

AJAX stands for Asynchronous JavaScript & XML. It is a technology that reduces the interactions between the server and client. It does this by updating only part of a web page rather than the whole page. The asynchronous interactions are initiated by JavaScript. The purpose of AJAX is to exchange small amounts of data with the server without a page refresh.

JavaScript is a client-side scripting language. It is executed on the client side by web browsers that support JavaScript. JavaScript code only works in browsers that have JavaScript enabled.

XML is the acronym for Extensible Markup Language. It is used to encode messages in both human and machine readable formats. It is like HTML but allows you to create your own custom tags. For more details on XML, see the article on XML.

Why use AJAX?

  • It allows developing rich, interactive web applications just like desktop applications.
  • Validation can be performed as the user fills in a form without submitting it. This can be achieved using auto completion. The words that the user types in are submitted to the server for processing, and the server responds with keywords that match what the user entered.
  • It can be used to populate a dropdown box depending on the value of another dropdown box.
  • Data can be retrieved from the server and only a certain part of a page updated without loading the whole page. This is very useful for web page parts that load things like:
    • Tweets
    • Comments
    • Users visiting the site, and similar live data.

How to Create a PHP Ajax application

We will create a simple application that allows users to search for popular PHP MVC frameworks.

Our application will have a text box where users type in the names of the frameworks.

We will then use AJAX to search for a match, then display the framework’s complete name just below the search form.

Step 1) Creating the index page

index.php

<html>

<head>

<title>PHP MVC Frameworks - Search Engine</title>

<script type="text/javascript" src="auto_complete.js"></script>

</head>

<body>

<h2>PHP MVC Frameworks - Search Engine</h2>

<p><b>Type the first letter of the PHP MVC Framework</b></p>

<form method="POST" action="index.php">

<p><input type="text" size="40" id="txtHint" onkeyup="showName(this.value)"></p>

</form>

<p>Matches: <span id="txtName"></span></p>

</body>

</html>

HERE,

  • “onkeyup=”showName(this.value)”” executes the JavaScript function showName every time a key is typed in the textbox. This feature is called auto complete.

Step 2) Creating the frameworks page

frameworks.php

<?php

$frameworks = array("CodeIgniter","Zend Framework","Cake PHP","Kohana") ;

$name = $_GET["name"];

if (strlen($name) > 0) {

$match = "";

for ($i = 0; $i < count($frameworks); $i++) {

if (strtolower($name) == strtolower(substr($frameworks[$i], 0, strlen($name)))) {

if ($match == "") {

$match = $frameworks[$i];

} else {

$match = $match . " , " . $frameworks[$i];

}

}

}

}

echo ($match == "") ? 'no match found' : $match;

?>

Step 3) Creating the JS script

auto_complete.js

function showName(str){

if (str.length == 0){ // exit function if nothing has been typed in the textbox

document.getElementById("txtName").innerHTML=""; // clear previous results

return;

}

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

} else {// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange=function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200){

document.getElementById("txtName").innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open("GET","frameworks.php?name="+str,true);

xmlhttp.send();

}

HERE,

  • “if (str.length == 0)” checks the length of the string. If it is 0, then the rest of the script is not executed.
  • “if (window.XMLHttpRequest)โ€ฆ” Internet Explorer versions 5 and 6 use ActiveXObject for the AJAX implementation. Other versions and browsers such as Chrome and Firefox use XMLHttpRequest. This code ensures that our application works in both IE 5 & 6 and modern browsers.
  • “xmlhttp.onreadystatechange=functionโ€ฆ” checks if the AJAX interaction is complete and the status is 200, then updates the txtName span with the returned results.

Step 4) Testing our PHP Ajax application

Assuming you have saved the file index.php in phptuts/ajax, browse to the URL http://localhost/phptuts/ajax/index.php

Testing our PHP Ajax Application

Type the letter C in the text box. You will get the following results.

Testing our PHP Ajax Application

The above example demonstrates the concept of AJAX and how it can help us create rich, interactive applications.

Modern AJAX with the Fetch API

The XMLHttpRequest object above still works, but its ActiveXObject branch for old Internet Explorer is no longer needed. Modern browsers provide the promise-based Fetch API, which makes the same request with far less code.

function showName(str) {
    if (str.length === 0) {
        document.getElementById("txtName").innerHTML = "";
        return;
    }
    fetch("frameworks.php?name=" + encodeURIComponent(str))
        .then(response => response.text())
        .then(text => {
            document.getElementById("txtName").innerHTML = text;
        });
}

This version does the same job: it sends the typed text to frameworks.php and puts the response into the txtName span. It also uses encodeURIComponent to safely escape the input, and its promise chain is easy to extend with error handling using a catch block.

FAQs

A synchronous request blocks the browser until the server responds, freezing the page. An asynchronous request runs in the background, so the page stays responsive and updates when the data arrives. Ajax uses the asynchronous model.

With fetch, pass a second argument setting method to POST and a body, then read $_POST in PHP. With XMLHttpRequest, call open(‘POST’, url), set the Content-Type header, and send the encoded data.

CORS, Cross-Origin Resource Sharing, blocks browser requests to a different domain unless that server sends the right Access-Control-Allow-Origin header. Add the header on the PHP side or call a same-origin URL to fix it.

Yes. Paste the XMLHttpRequest code, and AI can rewrite it using the promise-based fetch API or axios, add error handling, and keep the same behavior. Test the result, since response handling differs slightly.

Yes. Share the request code and the browser console or network error, and AI can spot a wrong URL, a CORS block, a missing parameter, or a server error, then suggest the fix to try.

Summarize this post with: