DEV Community

Cover image for The Powers of AJAX

The Powers of AJAX

π™Όπš’ πš—πšŠπš–πšŽ πš’πšœ π™ΌπšŠπš—πšž, πšŠπš—πš 𝙸'πš– 𝚊 𝟷𝟹-πš’πšŽπšŠπš›-πš˜πš•πš πšπšžπš•πš• πšœπšπšŠπšŒπš” 𝚍𝚎𝚟 πš πš‘πš˜ πš˜πš πš—πšœ πš πšŽπš‹πšœπš’πšπšŽπšœ πšŠπš—πš πšœπšŽπš›πšŸπšŽπš›πšœ πšŠπšŒπš›πš˜πšœπšœ πšπš‘πšŽ πš πš˜πš›πš•πš. 𝙸 πšŽπš—πš“πš˜πš’ πš™πš›πš˜πšπš›πšŠπš–πš–πš’πš—πš πš’πš— π™·πšƒπ™Όπ™», π™²πš‚πš‚, πš•πš˜πšπšœ 𝚘𝚏 π™Ήπš‚, 𝚁𝚎𝚊𝚌𝚝, 𝙿𝙷𝙿, πšŠπš—πš πš‚πš€π™»
・2 min read

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;
};"GET", "ajax_is_awesome.php", true);
Enter fullscreen mode Exit fullscreen mode

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"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=""></script> line in your code

$("#someform").submit(function(e) {
    var form = $(this);
    var url = form.attr('action');
           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!

Discussion (0)