DEV Community

Cover image for The Powers of AJAX
manu
manu

Posted on

The Powers of AJAX

Ajax is a set of web development techniques using many web
technologies on the client-side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behaviour of the existing page. (Wikipedia)

AJAX is very useful for building single page apps.
It's also very powerful because you can submit forms and send requests, without reloading the page!

How to use AJAX

AJAX is very simple to use.

  • Just create an index.html file, and insert this code in a <script> tag.
  • Create another file named ajax_is_awesome.php. Write whatever you want in that file!
  • View your website!
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("demo").innerHTML = ajax.responseText;
    }
};
ajax.open("GET", "ajax_is_awesome.php", true);
ajax.send();
Enter fullscreen mode Exit fullscreen mode

Explained
var ajax - Creates a new variable for the class XMLHttpRequest
XMLHttpRequest - XMLHttpRequest is an API in the form of an object whose methods transfer data between a web browser and a web server. (Wikipedia)
onreadystatechange - When the file has loaded
this.readyState == 4 && this.status == 200 - If the document's status isn't 404, 500, etc. Must be 200
ajax.open("GET", "index.php", true); - Opens the ajax file. Using GET this time.
ajax.send(); - Sends the request

How to use AJAX in jQuery

Remember to include the <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> line in your code

$("#someform").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var url = form.attr('action');
    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), 
           success: function(data) {          
            document.getElementById("demo").innerHTML = data; 
           }
      });
});
Enter fullscreen mode Exit fullscreen mode

See? AJAX is cool! Implement it, and you won't have redirects when submitting forms, or doing very simple things, such as checking for new notifications every few seconds.

Example of a single page documentation I made using AJAX

pls star it on github if you like this!

Top comments (0)