loading...
Cover image for How to use $.ajax()

How to use $.ajax()

williamragstad profile image William Rågstad ・9 min read

What is Ajax?

Important!

When I talk about Ajax in this article, I most often refer to the methods built into JQuery. Please note that Ajax in JQuery is a type of Ajax, but Ajax is not the Ajax in JQuery.

Ajax is a method to send and receive data from servers, API:s or other web pages and have become a standard when communicating at the web.

It is not built in to vanilla JavaScript and therefore you'll need to use a library like JQuery (for example) to get going with Ajax. The name is short for Asynchronous JavaScript and XML.

Definition of Ajax

"Asynchronous JavaScript + 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.
...
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."

MDN web docs, quoted 2019-01-20 from the source article.

How is Ajax often used?

Well, Ajax can be hidden in anything you see on the web, from asynchronously loading you Twitter feed when you scroll around on a Friday afternoon , to adding new products from an administration panel on a shopping site.

Ajax is mostly used to fetch data during runtime from client side.

How do I start using Ajax?

Assuming that you already have an HTML, PHP or similar file, and a working internet connection, you can either download JQuery directly from their website and linking to it as a file on your server, or get it using a CDN.

In this article I will show you how to get it using JQuery's public CDN.

1. Get the latest version of JQuery

Visit this page where you have a list of different versions of JQuery. I suggest you to pick a minified package. Copy the HTML code shown, it should look something like this:

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

2. Open up your HTML/PHP/etc file

Paste the script tag at the top (in the head tag) or at the bottom (under the body tag) of your page. I suggest you put it at the bottom in case something fails when loading the JQuery library, some of you may have other preferences.

<!doctype html>
<html>
    <head>
        <title>My Site</title>
        <!-- Here -->
    </head>
    <body>
        Hello World
    </body>
    <!-- Or Here -->
</html>

3. Done!

HTTP methods

When sending requests and data over the web, we can use one of the two main methods:

  1. Post
  2. Get

(Read more about HTTP Request methods here or here (W3Schools)).

Difference between post and get

Post

Post is used to send data "invisible", in most cases post is the way to go because you can send a ton more data with post than you can with get.

Security

If the client that uses the page is connected to a secure WI-FI with WPA or WPA2, the post method is the most secure method. It may still better that get even if the user where using an unprotected network...

Applications

Post is often used when transferring or receiving little to tons of data. It’s even used when communicating to web servers, databases or APIs as mentioned earlier.

For example when you have a shopping basket with some products you want to buy, when you click “proceed” and are redirected do another page, your products follows you. (This is also possible to be handled by the server using sessions, but that’s not to discuss in this particular article.)

Get

What most people think about when they hear “Get”, is URL queries. The get method is usually the way a user manually communicate with a web page or API, specifying search terms, date ranges, or other information that defines the query.

Wikipedia describes the HTTP get request method as only retrieving information from the server. Where some data can be configured via the web pages URL, or “query string”. (See picture below)

URL Query example

Get is more open to the user. This have both pros and cons.

Pros

If made the right way, get can be a way to talk to the web page and customize his/hers experience. For example; you visit a site with some controls, changing these controls and applying changes causes the page to reload, but also with some additional code in the URL. This is called an URL query. Here you see the values of those controls that you changed, and are now able to change them directly from the URL. Just type a new value and hit enter. This is often used by API services.

Cons

Giving control to the user is always dangerous. One worst scenario is having a reflective form using get to submit comments to an insecure website. If the website is vulnerable to cross site scripting (XSS) and just printing everything users type, into the source page... Get may be exploited as an walk around to ex; chromes XSS detection, built in protection systems, etc.

There are of course many more pros and cons to take into account. But this is just to give you a quick glimpse.

Comparison

Get only allows you to send key-value pairs, unlike post that can send whole object, files, tables and much more. Read more about the capacity of get & post.

Important!

Remember when we pasted the script tag that enabled us to use JQuery? Well, code is always executing in cascading order and code that rely on other code must be executed after the code that it’s relying on. What I’m trying to say is always put your own script tags of depending JavaScript underneath the JQuery tag. This may otherwise stop execution of your website and not run JavaScript as expected.


Usage

Okay... Let's finally get down to business.

The Ajax methods are accessed by typing $. This is the jQuery Object. Following up with a . and you'll see a list of all functions JQuery has to offer.

Functions

$.ajax

jQuery’s core $.ajax() method is a powerful way of creating Ajax requests. It requires an object that contains all the configurations Ajax needs to send the request.

Parameters

Parameter Description
type/method Which type of HTTP method is going to be used?
url Where are we going to send this request to?
data What data are we going to send the destination?

Events

Event Description
success A function that's called when Ajax returns any data.

An Example of this may look like the following:

$.ajax({
    type: "post",
    url: "www.example.com/subfolder/page.php",
    data: {
        myLuckyNumber: 13
    },
    success: function(response) {
        console.log(response);
    }
});

Output:

Lucky number was registered!

$.post

Load or send data from the server using a HTTP POST request. It requires an object that contains all the configurations Ajax needs to send the request.

Parameters

Parameter Description
url Where are we going to send this request to?
data What data are we going to send the destination?

Events

Event Description
success A function that's called when Ajax returns any data.

An Example of this may look like the following:

$.post({
    url: "www.api.mydomain.com/register.php",
    data: {
        users: {
            0: {                // User 1, aka data.users[0]
                name: "Joe",    //data.users[0].name
                age: 54,        //data.users[0].age
                work: "hacker"  //data.users[0].work
            },
            1: {
                name: "Billy",
                age: 28,
                work: "road worker"
            },
            2: {
                name: "Nathan",
                age: 15,
                work: "unemployed"
            }
        }
    },
    success: function(response) {
        console.log(response);
    }
});

Output:

3 new user(s) where registered!

$.get

Load or send data from the server using a HTTP GET request. It requires an object that contains all the configurations Ajax needs to send the request.

Parameters

Parameter Description
url Where are we going to send this request to?
data What data are we going to send the destination?

Events

Event Description
success A function that's called when Ajax returns any data.

An Example of this may look like the following:

$.get({
    url: "https://www.google.se",
    success: function(response) {
        console.log(response);
    }
});

Output:

<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="sv">
    <head>
    <meta charset="UTF-8">
    <meta content="origin" name="referrer">
    <meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image">
    <meta content="origin" name="referrer">
    <title>Google</title>
    <script>
    ...
    </script>
    <style>
    ...
    </style>
...

Execute JavaScript Files with Ajax!

Load and execute a JavaScript file.

$.ajax({
  method: "GET",
  url: "test.js",
  dataType: "script"
});

Parse with Ajax!

Because Ajax sends HTTP request to a web server, it also receives HTTP/HTML/JSON formatted responses. With this in mind, we can pretend that our Ajax is our browser, and send requests to a web server that we want a normal html page for example.

CORS & CORB policies

Cross-Origin Resource Sharing (CORS) is additional HTTP headers that tells the browser to let a web application running at one origin, or domain have permission to access selected resources from a server at a different origin, or domain.This means that web pages that doesn't have the same origin, or domain can share resources (See image below).
As long as the server is configured to allow requests from your or any other web application's origin, XMLHttpRequest and Ajax will work.

Sadly, some websites are protected by something called Cross-Origin Read Blocking (CORB). this is an algorithm that can identify and block "cross-origin" resource loads in web browsers before they reach the web page. This means that web pages that doesn't have the same origin, or domain can not share resources.

CORS principle

If you look at the code below, a new Ajax request is created to a site that is using CORS. This means that we can request the HTML code via an Get method.

$.ajax({
  url: "https://www.google.com",    // This is just an example domain
  method: "GET",
  sucess: function(sourceCode) {
    console.log(sourceCode);
  }
});

Output:

<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="sv">
    <head>
    <meta charset="UTF-8">
    <meta content="origin" name="referrer">
    <meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image">
    <meta content="origin" name="referrer">
    <title>Google</title>
    <script>
    ...
    </script>
    <style>
    ...
    </style>
...

Ajax progress!

In JQuery there's no straight way to fetch the progress that an $.ajax() request have made, but the method supports an custom xhr object.

What we did in the example below, was creating out own xhr object that preforms the HTTP request, and added an event listener for "progress" to it. This made it possible for us to grab the current state in percent of the request.

xhr

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.

JQuery AJAX documentation, quoted 2019-01-20 from the documentation.

$.ajax({
    url: "https://example.url/very/large/image.jpeg",
    method: "get",

    xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    console.log(percentComplete);
                }
            }, false);
            return xhr;
        }
})

Output:

0.2384341119115186
0.7248216529871057
1

It is also possible to fetch the progress on contacting the server instead of capturing the response by replacing xhr.addEventListener(...) to xhr.upload.addEventListener(...)


Closure

Thanks for reading this article! I hope it helped you on your journey to become a JavaScript and JQuery master! Share this with your friends and family that might be interested or benefit of this information.

If you have any questions what so ever, I'd be glad to answer them in the discussion down below.


Credits

People who helped make this article better

Discussion

pic
Editor guide
Collapse
vitalipom profile image
Vitali Pomanitski

Hi William, I'm struggelling to upload an article that everyone will use and read. I have a handy keyboard that I have on the app store (for Android), which is honestly very great. But I cannot publish an article, noone replies me from the cobtact forms. Can you please reply me back and assist me?
Tnx, Vitali

Collapse
williamragstad profile image
William Rågstad Author

Hey, I see... I didn’t know how to publish my first article as well.
You basically go into edit mode on your article, and there at the top you’ll see an “variable” that says “published”, set that to true and save. That will publish it!

Collapse
vitalipom profile image
Vitali Pomanitski

And the readers - do you have to advertize somehow it? Or does it just simply shows up in everyones feed?

Thread Thread
williamragstad profile image
William Rågstad Author

I did not advertise this article, I guess that it shows up in everyone’s feed that follows those tags I entered. Like: Ajax, JQuery, Php and JavaScript...

Thread Thread
vitalipom profile image
Vitali Pomanitski

oooooh tags, okay I got it. Find out a small or average community and use tags in oder to reach everyone. Thaaanks :)))

Thread Thread
vitalipom profile image
Vitali Pomanitski

I have Perl tutorials I've already made, I'll publish them if so that is so easy seemingly to be introduced here :) Thanks William!

Thread Thread
williamragstad profile image
William Rågstad Author

Sounds interesting! No problem :)

Thread Thread
vitalipom profile image
Vitali Pomanitski

Nice suprise, easy to edit here. I will learn the relevant tags like you did though to get published.
I wanted to recommend you Effectedkeyboard if you are writing from your Android, usually people struggleing to get comfortable typing app for long posts, but this one is sreally good and comfortable one.

Collapse
emgodev profile image
Michael

It comes packed within a JavaScript framework called JQuery

This is wrong, unless you are only talking about $.ajax(), and jQuery is a library. Frameworks govern how you build, jQuery (a library) provides utilities/tools to build with.

The limits are your own imagination.

That and CORS.

Nice article, seems rushed, and I felt miss-led. I'd change the 'Ajax' in the title to '$.ajax()'. Anyone reading that will understand you're talking about jQuery.

Collapse
williamragstad profile image
William Rågstad Author

Thanks for the feedback, I worked on this article in about four days, seems like I mixed some concepts and terminology together... I’ll change that as soon as possible.
What made you feel miss-led? Was it only the title? What could Ajax else be?

Collapse
emgodev profile image
Michael

I mean yes it was the title, but then those few mistakes poped up and it was throwing me off. The rest of the article was fine, write about what you want, it was interesting. Ajax just is not jQuery. jQuery does have an ajax method (ie: $.ajax()), so I think it's important to be clear about that is all. You should read through MDNs' documentation if that sounds debatable.

Ajax finds its most native implementation in the XMLHttpRequest API, as much as I know, which is also on that page. That is what I thought you were writing about when I only saw 'Ajax' in the title.

If you really want to go the extra mile you could read through jQuery's source code to see how they perform their ajax?

Thread Thread
williamragstad profile image
William Rågstad Author

Absolutely! Thanks, this helps me improve the article, as a developer and an writer. I really appreciate feedback.

That would be cool, I'll see what I can do.

If you have any ideas of any more "fun facts" you can do with Ajax or $.ajax(), I'd be glad to hear :)

Collapse
amac01 profile image
Alpha Mackie

Thanks for this article, well explained.