Javascript VS Ajax when working with JSON

Hello guys,
so i’ve been playing around with some API’s to get a better understanding of how they work. When looking for tutorials on how to work with the JSON data, sometimes it’s done with javascript, and other times it is done with ajax to display it on a webpage. One tutorial mentioned the application PostMate.

I’ve been trying to google how they differ (Javascript and Ajax) when working with JSON data, but I cant seem so figure out how they are different here, or which I would prefer to use in the long run with working with API’s.

Any info would be greatly appriciated.
I

What exactly do you mean by javascript request? And with ajax you mean JQuery.ajax?

To clarify: Ajax = Asynchronous JavaScript And XML.
and uses the built-in browser XMLHttpRequest object to request data to a web server,

mind that even if Ajax imply xml it works with any kind of server respone: plain text, JSON, Blob…

JQuery.ajax is just a wrapper to XMLHttpRequest object, so the two may differ in syntax, but the underlying request is the same.

Example of an XMLHttpRequest from MDN using XMLHttpRequest

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

More recently browsers support another method of requesting data to a server: Fetch API, which uses Promises, Request and Response Objects under the hood.

Likewise, fetch can handle any response type from the server.

An example of a fetch request from MDN using fetch: it uses async-await, but works with Promise.then as well if you are more familiar

const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));

So at the end of the day they are two ways to perform the same task. Either one is fine.
Hope this helps :+1:

1 Like

AJAX is a feature for Cross-browser request. JSON is a format in which the data is received just like txt or XML etc.

If a server is serving data in JSON format which could be extracted from an endpoint eg. https://example.com/apiv2/data then you can use AJAX to get that data given that server has enabled Cross browser requests.

Now, AJAX is a part of browser APIs, likewise there are more such as fetch, JSON-P or simply a script tag in HTML. All of these formats can help you in getting JSON data from an external API.

Thanks for the reply! Turns out I was reffering to an XMLHttpRequest.
I had followed a tutorial and they were referencing ajax, but more research made me realize they were using Jquery.ajax.

Your response led me in the right direction, thanks again!