How to use $.ajax()
Tags: ajax, javascript, jquery, php
Published: 2019-01-19 19:36:37

---
title: How to use $.ajax()
published: true
description: The complete guide to learning JQuery's $.ajax().
tags: Ajax, javascript, JQuery, PHP
cover_image: https://cdn.artandlogic.com/wp-content/uploads/2000px-AJAX_logo_by_gengns.svg_.png
---

##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](https://jquery.com/) *(for example)* to get going with Ajax. The name is short for **A**synchronous **Ja**vaScript and **X**ML.

> ####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](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX).


##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](https://sv.wikipedia.org/wiki/HTML), [PHP](http://www.php.net/) 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](https://en.wikipedia.org/wiki/Content_delivery_network).

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](https://code.jquery.com/) 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:

```html
<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.

```html
<!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](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) or [here (W3Schools)](https://www.w3schools.com/tags/ref_httpmethods.asp)).

![Difference between post and get](https://thepracticaldev.s3.amazonaws.com/i/ytxdmm71yvt3zokkrpn4.jpg)



##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](https://sv.wikipedia.org/wiki/WPA), 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](https://www-growyourgk-com.cdn.ampproject.org/i/s/www.growyourgk.com/wp-content/uploads/2017/08/querystring-in-javascript.jpg)

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](https://en.m.wikipedia.org/wiki/POST_(HTTP)).

> ##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](https://learn.jquery.com/using-jquery-core/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:

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

Output:

```html
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:

```javascript
$.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:

```html
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:

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

Output:

```html
<!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.
```javascript
$.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](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) & [CORB](https://www.chromestatus.com/feature/5629709824032768) 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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://mdn.mozillademos.org/files/14295/CORS_principle.png)

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.

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

Output:

```html
<!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](https://api.jquery.com/jQuery.ajax/).

```javascript
$.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:

```html
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
* [Cover Image](https://cdn.artandlogic.com/wp-content/uploads/2000px-AJAX_logo_by_gengns.svg_.png) by Christopher Keefer
* [Difference between post and get](https://thepracticaldev.s3.amazonaws.com/i/ytxdmm71yvt3zokkrpn4.jpg) by Me
* [Url Query Example](https://www-growyourgk-com.cdn.ampproject.org/i/s/www.growyourgk.com/wp-content/uploads/2017/08/querystring-in-javascript.jpg) by Hari Prasad
* [CORS principle](https://mdn.mozillademos.org/files/14295/CORS_principle.png) by MDN web docs

###People who helped make this article better
* [Michael Goldspinner](https://dev.to/emgodev) with feedback