DEV Community

Cover image for Sending asynchronous POST requests with pure JS: ditching jQuery's ajax
Lourenço Costa
Lourenço Costa

Posted on

2

Sending asynchronous POST requests with pure JS: ditching jQuery's ajax

If you ended up here, chances are you have to deal with jQuery. As you may know, nowadays, lots of things that used to be made with jQuery can be done with pure JS. An interesting fact is that Bootstrap has announced that they would stop using jQuery as of version 5 (the current at the moment). And that says a lot if you think about it!
Here, I would like to demonstrate a very common practice that is usually made with jQuery, but can be easily replaced with pure JS: sending asynchronous POST/GET requests.

async function getData(){
let url = 'https://jsonplaceholder.typicode.com/posts/1';
let page = await fetch(url);
let json = await page.json();
console.log(json);
}
async function postData(){
let url = 'https://jsonplaceholder.typicode.com/posts';
let person = {
firstName:"jason",
lastName:"bourne"
};
let headers = {
'Content-type': 'application/json; charset=UTF-8'
};
let request = {
method:"POST",
body:JSON.stringify(person),
headers
};
let page = await fetch(url,request);
let json = await page.json();
console.log(json);
}

That's it, people.

Thanks for the time reading this!

Follow me:
LinkedIn | Dev.to | Buy me a coffee | GitHub

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay