javaScript AJAX

Hello, my Name is Christopher. I'm learning Frontend Web Devlopment on my own. I've found several resourses available to anyone wanting to learn web development.

I use a few different web sites for free courses and reference material, like "Free code Camp", "W3 Schools" and "MDN Web Docs". I use these sites for theory, testing and documentation. I also found lots of videos on YouTube that were great for beginers right up to more advanced programming. I did find the theory and having lectures from videos beneficial but they just didn't complete the learning process, I had to take notes too. I try to reference the sites I used for source material when possible in my notes.

I've started to build several reference document web pages to practice building web pages while taking notes on different subjects.

Welcome to AJAX

Traversy Media

AJAX Crash Course

What is AJAX?

Asynchronous JavaScript & XML

Set of Web Technologies

Send & Receive Data Asynchronously

Does Not Interfere With Current Web Page

JSON Has Replaced XML For The Most Part

Asynchronous JavaScript And XML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together, including HTML or XHTML, CSS, JavaScript, DOM, XML, XSLT, and most importantly the XMLHttpRequest object. When these technologies are combined in the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.

Although X in Ajax stands for XML, JSON is preferred over XML nowadays because of its many advantages such as being a part of JavaScript, thus being lighter in size. Both JSON and XML are used for packaging information in the Ajax model.


In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX's most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.

The two major features of AJAX allow you to do the following:

Make requests to the server without reloading the page

Receive and work with data from the server



XHR Object MDN Web Docs

How to make an HTTP request

In order to make an HTTP request to the server with JavaScript, you need an instance of an object with the necessary functionality. This is where XMLHttpRequest comes in. Its predecessor originated in Internet Explorer as an ActiveX object called XMLHTTP. Then, Mozilla, Safari, and other browsers followed, implementing an XMLHttpRequest object that supported the methods and properties of Microsoft's original ActiveX object. Meanwhile, Microsoft implemented XMLHttpRequest as well.

.onreadystatechange

After making a request, you will receive a response back. At this stage, you need to tell the XMLHttp request object which JavaScript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to call when the request changes state, like this:

          
  httpRequest.onreadystatechange = nameOfTheFunction;
          
        

Note that there are no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually calling it. Alternatively, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous functions") to define the actions that will process the response, like this:

          
  httpRequest.onreadystatechange = function(){
    // Process the server response here.
};
          
        

Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send() methods of the HTTP request object, like this:

          
  httpRequest.open('GET', 'http://www.example.org/some.file', true);
  httpRequest.send();
          
        

.open parameters

  • The first parameter of the call to open() is the HTTP request method - GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods, check the W3C specs.
  • The second parameter is the URL you're sending the request to. As a security feature, you cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on all of your pages or you will get a "permission denied" error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. If you really need to send a request to another domain, see HTTP access control (CORS).
  • The optional third parameter sets whether the request is asynchronous. If true (the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive. This is the first A in AJAX.

.send parameters

The parameter to the send() method can be any data you want to send to the server if POST-ing the request. Form data should be sent in a format that the server can parse, like a query string:

          
  "name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
          
        

or other formats, like multipart/form-data, JSON, XML, and so on.

Note that if you want to POST data, you may have to set the MIME type of the request. For example, use the following before calling send() for form data sent as a query string:

          
  httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          
        


Handling the server response

When you sent the request, you provided the name of a JavaScript function to handle the response:

            
  httpRequest.onreadystatechange = nameOfTheFunction;
            
          

What should this function do? First, the function needs to check the request's state. If the state has the value of XMLHttpRequest.DONE (corresponding to 4), that means that the full server response was received and it's OK for you to continue processing it.

            
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    // Everything is good, the response was received.
  } else {
    // Not ready yet.
  }
            
          

The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as follows:

  • 0 (uninitialized) or (request not initialized)
  • 1 (loading) or (server connection established)
  • 2 (loaded) or (request received)
  • 3 (interactive) or (processing request)
  • 4 (complete) or (request finished and response is ready)

Next, check the HTTP response status codes of the HTTP response. The possible codes are listed at the W3C. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a 200 OK response code.

            
  if (httpRequest.status === 200) {
    // Perfect!
  } else {
    // There was a problem with the request.
    // For example, the response may have a 404 (Not Found)
    // or 500 (Internal Server Error) response code.
  }
            
          

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

  1. Informational responses (100-199)
  2. Successful responses (200-299)
  3. Redirection messages (300-399)
  4. Client error responses (400-499)
  5. Server error responses (500-599)

After checking the state of the request and the HTTP status code of the response, you can do whatever you want with the data the server sent. You have two options to access that data:

  • httpRequest.responseText - returns the server response as a string of text
  • httpRequest.responseXML - returns the response as an XMLDocument object you can traverse with JavaScript DOM functions

Note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don't need to specify a function, but this is highly discouraged as it makes for an awful user experience.


A Simple Example

Let's put it all together with a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." Then we'll alert() the contents of the response. Note that this example uses vanilla JavaScript — no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory.

            
  <button id="ajaxButton" type="button">Make a request</button>

  <script>
    (function() {
    var httpRequest;
    document.getElementById("ajaxButton").addEventListener('click', makeRequest);

    function makeRequest() {
    httpRequest = new XMLHttpRequest();

      if (!httpRequest) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
      }
      httpRequest.onreadystatechange = alertContents;
      httpRequest.open('GET', 'test.html');
      httpRequest.send();
    }

    function alertContents() {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          alert(httpRequest.responseText);
        } else {
          alert('There was a problem with the request.');
        }
      }
    }
  })();
  </script>
            
          

In this example:

  • The user clicks the "Make a request" button;
  • The event handler calls the makeRequest() function;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and OK, then alert()s the contents of the test.html file.

Error Handling

In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange method when accessing the response status. To mitigate this problem, you could wrap your if...then statement in a try...catch:

            
  function alertContents() {
    try {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          alert(httpRequest.responseText);
        } else {
          alert('There was a problem with the request.');
        }
      }
    }
    catch( e ) {
      alert('Caught Exception: ' + e.description);
    }
  }
            
          

Working with the XML response

In the previous example, after receiving the response to the HTTP request we used the request object's responseText property , which contained the contents of the test.html file. Now let's try the responseXML property.

First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:

            
  <?xml version="1.0" ?>
  <root>
    I'm a test.
  </root>
            
          

In the script we only need to change the request line to:

            
  ...
  onclick="makeRequest('test.xml')">
  ...
            
          

Then in alertContents(), we need to replace the line alert(httpRequest.responseText); with:

            
  var xmldoc = httpRequest.responseXML;
  var root_node = xmldoc.getElementsByTagName('root').item(0);
  alert(root_node.firstChild.data);
            
          

This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document.


Working with data

Finally, let's send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, test.php, which will take the data we send and return a "computed" string - "Hello, [user data]!" - which we'll alert().

First we'll add a text box to our HTML so the user can enter their name:

            
  <label>Your name:
    <input type="text" id="ajaxTextbox" />
  </label>
  <span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
  </span>
            
          

We'll also add a line to our event handler to get the user's data from the text box and send it to the makeRequest() function along with the URL of our server-side script:

            
  document.getElementById("ajaxButton").onclick = function() {
      var userName = document.getElementById("ajaxTextbox").value;
      makeRequest('test.php',userName);
  };
            
          

We need to modify makeRequest() to accept the user data and pass it along to the server. We'll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send():

            
  function makeRequest(url, userName) {

    ...

    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('POST', url);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send('userName=' + encodeURIComponent(userName));
  }
            
          

The function alertContents() can be written the same way it was in "A Simple Example" to alert our computed string, if that's all the server returns. However, let's say the server is going to return both the computed string and the original user data. So if our user typed "Jane" in the text box, the server's response would look like this:

{"userData":"Jane","computedString":"Hi, Jane!"}

To use this data within alertContents(), we can't just alert the responseText, we have to parse it and alert computedString, the property we want:

            
  function alertContents() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        var response = JSON.parse(httpRequest.responseText);
        alert(response.computedString);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
            
          

The test.php file should contain the following:

            
  $name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
  $computedString = "Hi, " . $name . "!";
  $array = ['userName' => $name, 'computedString' =>  $computedString];
  echo json_encode($array);
            
          

Timed XHR Example

Another simple example follows — here we are loading a text file via XHR, the structure of which is assumed to be like this:

            
  TIME: 312.05
  TIME: 312.07
  TIME: 312.10
  TIME: 312.12
  TIME: 312.14
  TIME: 312.15
            
          

Once the text file is loaded, we split() the items into an array at each newline character (\n — basically where each line break is in the text file), and then print the complete list of timestamps, and the last timestamp, onto the page.

This is repeated every 5 seconds, using a setInterval() call. The idea would be that a server-side script of some kind would continually update the text file with new timestamps, and our XHR code would be used to report the latest timestamp on the client-side.

            
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <title>XHR log time</title>
      <style>

      </style>
    </head>
    <body>
      <p id="writeData" class="data">Off-Line</p>
      <p id="lastStamp">No Data yet</p>

      <script> 
      const fullData = document.getElementById('writeData');
      const lastData = document.getElementById('lastStamp');

      function fetchData() {
        console.log('Fetching updated data.');
        let xhr = new XMLHttpRequest();
        xhr.open("GET", "time-log.txt", true);
        xhr.onload = function() {
          updateDisplay(xhr.response);
        }
        xhr.send();
      }

      function updateDisplay(text) {
        fullData.textContent = text;

        let timeArray = text.split('\n');

        // included because some file systems always include a blank line at the end of text files.
        if(timeArray[timeArray.length-1] === '') {
          timeArray.pop();
        }

        lastData.textContent = timeArray[timeArray.length-1];
      }

      setInterval(fetchData, 5000);
      </script>
    </body>
  </html>
            
          

MDN XMLHttpRequest



Ubuntu

XAMPP

Change User Permission for htdocs Directory


Terminal Prompt


Enter this Code for Granting Write Permission for All Users

<!-- $sudo chmod -R 777 /opt/lampp/htdocs -->

Use this code to Remove Write Permission for All Users

<!-- $sudo chmod -R 755 /opt/lampp/htdocs -->

****

Enter this Code to see current user name & primary group name

<!-- $whoami -->

// this will show the username of the current user

<!-- $id -gn -->

// this will show the primary group name of the current user


Once you know the names of both

Enter this Code to Change Ownership

<!-- sudo chown -R [Username]:[Groupname] /opt/lampp/htdocs -->


Start XAMPP

You can use one of the commands below.


Terminal Prompt

If you use a 32-bit system:

<!-- sudo /opt/lampp/manager-linux.run -->

If you use a 64-bit system:

<!-- sudo /opt/lampp/manager-linux-x64.run -->


Using mySQL with XAMPP

If mySQL is stopped in XAMPP

use the following Code


Terminal Prompt

Use this Code to Stop the mysql-server service

<!-- sudo service mysql stop -->

Restart mySQL with the XAMPP control panel Manage Servers Tab