AJAX and how to best deal with it server side in PHP

Active3 hr before
Viewed126 times

6 Answers


In this section, we’ll build an example that fetches JSON content from a PHP file on the server side using AJAX.,Today, we’re going to explore the concept of AJAX with PHP and JavaScript. The AJAX  technique helps you to improve your application's user interface and enhance the overall end user experience.,So that's how you can use JavaScript Promises for AJAX. In the next section, we’ll see how to use the jQuery library to perform AJAX calls.,So as you can see, it's easy to perform AJAX operations using the jQuery library. In fact, the process is more or less the same, irrespective of the JavaScript library with which you choose to perform AJAX calls.

Let’s have a look at the following vanilla JavaScript code, which performs the AJAX call and fetches a response from the server asynchronously.

var objXMLHttpRequest = new XMLHttpRequest();
objXMLHttpRequest.onreadystatechange = function() {
  if(objXMLHttpRequest.readyState === 4) {
    if(objXMLHttpRequest.status === 200) {
    } else {
          alert('Error Code: ' +  objXMLHttpRequest.status);
          alert('Error Message: ' + objXMLHttpRequest.statusText);
objXMLHttpRequest.open('GET', 'request_ajax_data.php');
load more v

Replace the existing content for the file as follows., Replace the existing content for the file as follows. ,create a URL that contains data that can be utilized by the server-side,, create a URL that contains data that can be utilized by the server-side,

    // put your code here
    *echo "<h2>Hello World!</h2>";*
load more v

AJAX full form is 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 server without page refresh. ,JavaScript is a client side scripting language. It is executed on the client side by the web browsers that support JavaScript.JavaScript code only works in browsers that have JavaScript enabled.,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, The above example demonstrates the concept of AJAX and how it can help us create rich interaction applications.



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

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



   <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>


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


load more v

The term AJAX was publicly used on 18 February 2005 by Jesse James Garrett in an article titled Ajax: A New Approach to Web Applications, based on techniques used on Google pages.[1] ,The term Ajax has come to represent a broad group of Web technologies that can be used to implement a Web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax,[1][3] Jesse James Garrett explained that the following technologies are incorporated: ,Fetch is a new native JavaScript API.[16] According to Google Developers Documentation, "Fetch makes it easier to make web requests and handle responses than with the older XMLHttpRequest." ,fetch() won't send cross-origin cookies unless you set the credentials init option. (Since April 2018. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)

// This is the client-side script.

// Initialize the HTTP request.
var xhr = new XMLHttpRequest();
// define the request
xhr.open('GET', 'send-ajax-data.php');

// Track the state changes of the request.
xhr.onreadystatechange = function() {
   var DONE = 4; // readyState 4 means the request is done.
   var OK = 200; // status 200 is a successful return.
   if (xhr.readyState === DONE) {
      if (xhr.status === OK) {
         console.log(xhr.responseText); // 'This is the output.'
      } else {
         console.log('Error: ' + xhr.status); // An error occurred during the request.

// Send the request to send-ajax-data.php
load more v

There are two parts to the server side PHP script that are needed to implement AJAX communication. First we need to enqueue the jQuery script on the web page and localize any PHP values that the jQuery script needs. Second is the actual handling of the AJAX request.,Finally we can send the response back to the jQuery script. There’s several ways to transmit data. Let’s look at some of the options before we deal with the specifics of our example.,The parameter title_example can be any arbitrary string. It’s suggested the string be related to what the nonce is used for, but it can really be anything that suits you.,Then we build a query in order to get the post count for the selected title tag.

   plugins_url('/js/myjquery.js', __FILE__),
load more v

It used to be a daunting challenge for a developer to upload files through a browser. Poor client-side facilities hampered the equation, and server-side components needed to exist to handle the incoming data stream.,A component must exist on the server to handle the file upload and save the resource locally;,In this example, the JavaScript file upload target is an Apache Web Server. As a result, the server-side component that handles the Ajax request will be written in PHP. If a Tomcat or Jetty server was the upload target, a developer could code a Java based uploader on the server-side.,The server-side resource is passed the FormData which contains the file

The following HTML5 tags provide the required components to add a file selector and an upload button to any web page:

<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>

The button kicks off a method named uploadFile(), which contains the JavaScript file upload logic.

async function uploadFile() {
    let formData = new FormData();           
    formData.append("file", fileupload.files[0]);
    await fetch('/upload.php', {
      method: "POST", 
      body: formData
    alert('The file has been uploaded successfully.');
load more v

Other "undefined-undefined" queries related to "AJAX and how to best deal with it server side in PHP"