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:
- Post
- Get
(Read more about HTTP Request methods here or here (W3Schools)).
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)
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.
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
- Cover Image by Christopher Keefer
- Difference between post and get by Me
- Url Query Example by Hari Prasad
- CORS principle by MDN web docs
People who helped make this article better
- Michael Goldspinner with feedback
Top comments (8)
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.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.
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?
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?
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 :)
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!
Thanks for this article, well explained.
Sounds interesting! No problem :)
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...