Introduction

Useful Links:

http://voidcanvas.com/

https://www.w3schools.com/

AJAX is a developer's dream, because you can:

  • Update a web page without reloading the page
  • Request data from a server - after the page has loaded
  • Receive data from a server - after the page has loaded
  • Send data to a server - in the background

When you should use

1. Form validation:

As I said earlier, if every time if the user gets the validation results only after submitting the form it will be irritating. So you can use ajax in form validation.

2. Light Box:

Popups are always irritating and maximum browsers block them too. So a nice and cool alternative of popup is lightbox which is a nice implementation of ajax.

3. Sort or Filter:

Sometimes we want to filter the search results or some other thing by date, popularity, cost and blah blah. In that case ajax is a really nice technique.

4. Vote or Rating:

The whole site need not to be refreshed if a user votes for something or rates your product. The voting and displaying result can be done using ajax.

5. Chat websites:

Chatting is always real time. That’s why you must use ajax if you are going to make a chatting panel in your website.

6. Blog Comments:

Comments of your blogs are not useful for search engines. So you can load the previous comments or can post a new one with ajax.

7. Captcha:

To make captcha (reloading captcha basically) you should use ajax.

What is AJAX

AJAX =AsynchronousJavaScriptAndXML.

AJAX is not a programming language.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

How AJAX Works

  1. An event occurs in a web page (the page is loaded, a button is clicked)

  2. An XMLHttpRequest object is created by JavaScript

  3. The XMLHttpRequest object sends a request to a web server

  4. The server processes the request

  5. The server sends a response back to the web page

  6. The response is read by JavaScript

  7. Proper action (like page update) is performed by JavaScript

AJAX - The XMLHttpRequest Object

The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

var xhttp = new XMLHttpRequest();

XMLHttpRequest Object Methods

Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,psw) Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password
send() Sends the request to the server Used for GET requests
send(string) Sends the request to the server. Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to theHttp Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")

AJAX - Send aRequestTo a Server

The XMLHttpRequest object is used to exchange data with a server.

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
open(method, url, async) Specifies the type of request method: the type of request: GET or POST url: the server (file) location async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

  • A cached file is not an option (update a file or database on the server).
  • Sending a large amount of data to the server (POST has no size limitations).
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
Method Description
setRequestHeader(header, value) Adds HTTP headers to the request header: specifies the header name value: specifies the header value

The onreadystatechange Property

With the XMLHttpRequest object you can define a function to be executed when the request receives an answer.

The function is defined the in theonreadystatechangeproperty of the XMLHttpResponse object:

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

Ajax Raw Code

// The following ajax function assumes that all data sent and received is in
// the form of a json encoded object sent using an http POST.
function ajax(url, requestObject, responseHandler) {
    var httpRequest = new XMLHttpRequest();
    if (!httpRequest) {
        alert('Browser not supported.');
        return;
    }
    httpRequest.onreadystatechange = function() {
        var responseObject;
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                if (httpRequest.responseText.trim().length === 0) {
                    responseHandler({});
                    return;
                }
                try {
                    responseObject = JSON.parse(httpRequest.responseText);
                } catch(e) {
                    responseHandler({ 
                        result: 'error', 
                        msg: 'JSON.parse exception.\n' + httpRequest.responseText
                    });
                }
                responseHandler(responseObject);
            } else {
                responseHandler({ result: 'error', msg: 'Ajax error, status: ' + this.status});
            }
        }
    };
    httpRequest.open('POST', url);
    httpRequest.setRequestHeader("Content-type", "application/json");
    httpRequest.send(JSON.stringify(requestObject));
}

To update a content simultaneously, Front End and Back End

<button id="button">clickme</button><p>Counter: </p><p id="counter"><?php print($count) ?></p>
<script>
    var count= <?php print($count) ?>;
    var counter=document.getElementById('counter');
    var button=document.getElementById('button');
    button.onclick = function() {
        counter.innerHTML = ++count;    // Update front end
        ajax('counter.php', null, function(responseObject){})    // Update back end
    }
</script>
  • To receive with PHP(counter.php), Goto PHP "Send variable with URL"

results matching ""

    No results matching ""