Javascript Run Same Ajax Function Again Depending on Response
6 Dissimilar ways to exercise Ajax calls in JavaScript
There are so many options in different ways to call Ajax in JavaScript that tin ameliorate user experiences drastically like submitting data to the server, checking the username, creating autocomplete form, voting, and rating, creating conversation rooms, etc.
This article covers the information about the latest list of various options to brand AJAX calls. To go on it uncomplicated, allow'due south focus on what they are, there some pros and cons of each option.
1. XHR
XMLHttpRequest is an object such as (a native component in well-nigh other browsers, an ActiveX object in Microsoft Net Explorer) that permits a spider web page to brand a request to a server and get a response dorsum without reloading the entire folio. The user continues on the same page that is page did non reload, and more than importantly, they will non actually run into or discover the processing occur — that is, they will non come across a new folio loading, not by default at least.
Using the XMLHttpRequest object makes information technology possible for a developer to change a page earlier loaded in the browser with data from the server without having to request the full page from the server once again.
Performing GET request using XHR
const Http = new XMLHttpRequest();
const url='http://yourdomain.com/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}
Performing Post asking using XHR
var xhr = new XMLHttpRequest();
xhr.open up("Mail", '/submit', truthful);
xhr.setRequestHeader("Content-Type", "application/x-world wide web-form-urlencoded"); xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.Washed && this.status === 200) {
// Request finished. Practise processing here.
}
}
xhr.send("name=Ketan&id=i");
2. Fetch API
Fetch API is the new selection to XMLHttpRequest for getting resources from the server. Dissimilar XMLHttpRequest, it has a more powerful feature set and a more meaningful name. Fetch is too flexible and easy to use considering of its syntax and structure. However, the affair that sets it apart from other AJAX HTTP libraries is that information technology is supported by all modern web browsers. Fetch follows a asking-response approach where Fetch makes a request and returns a promise that resolves to the Response object.
Pros of using Fetch API
- Information technology's flexible and easy to use
- Callback hell is avoided past Promises
- Supported by all modern browsers
- Follows request-response approach
Cons of using Fetch API
- Doesn't send cookie past default
- CORS is disabled by default
Performing GET Request in Fetch API
fetch('https://www.yourdomain.com', {
method: 'get'
})
.then(response => response.json())
.so(jsonData => console.log(jsonData))
.catch(err => {
//fault block
}
Performing Post Request in Fetch API
var url = 'https://www.yourdomain.com/updateProfile';
var data = {username: 'courseya'}; fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // information tin be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.so(response => console.log('Success:', JSON.stringify(response)))
.grab(fault => panel.error('Mistake:', error));
3. jQuery
jQuery is a client-side programming language you can be used to create cool and amazing web applications. It's complimentary, notwithstanding powerful, comparatively easy to set and learn, and it has multiple extensions and plugins available to practice anything you could imagine or think off. Y'all tin get started quickly, and you won't outgrow information technology later when you become really good at information technology.
Pros of using Jquery
- The greatest reward of jQuery is its simplicity.
- Information technology is also incredibly flexible because jQuery allows users to add plug-ins.
- It is also a very fast solution to your problems. While there may be "better" solutions, jQuery and its development teamwork to make sure you can implement jQuery quickly and finer, which saves money.
- Open-source software ways quick growth and the freedom of developers to provide the all-time service possible without corporate ruby tape.
Cons of using Jquery
- Information technology is also, frequent updates mean customs members are likewise unlikely to provide solutions.
- There are also multiple varieties of jQuery available currently and some are less uniform than others.
- Sometimes jQuery is slower compared to CSS in some cases. At that time its simplicity becomes a expletive, as it is not meant for client-side interactions.
Performing GET Request in Jquery
$.ajax({
url: '/users',
type: "Become",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (error) {
panel.log(`Error ${error}`);
}
});
Performing POST Request in Jquery
$.ajax({
url: '/users',
blazon: "Mail",
data: {
name: "Ipseeta",
id: 1
},
dataType: "json",
success: office (data) {
console.log(information);
},
error: function (error) {
console.log(`Error ${error}`);
}
});
iv. Axios
Axios is one among many available promise-based HTTP customer that works both in the browser and in a node.js surroundings. It basically provides a single API for dealing with XMLHttpRequest south and node'south HTTP interface. Apart from that, it binds the requests using a polyfill for ES6 new's hope syntax.
Advantages of using Axios
- Out-of-the-box Promise support
- Client-side support for protecting against XSRF
- Can capture requests or responses before they are carried out.
- Automatic transforms for JSON information
- Supports Hope API
- Tin can set up or abolish a request
- Can set a response timeout
- It works on both Nodejs and Browser
Performing Become Request in Axios
axios.get('/become-user', {
params: {
ID: i
}
})
.so(function (response) {
console.log(response);
})
.catch(office (mistake) {
panel.log(error);
})
.then(function () {
// ever executed
});
Performing Post Request in Axios
axios.post('/user', {
name: 'Sanjeev',
id: 1
})
.and so(part (response) {
console.log(response);
})
.grab(office (error) {
console.log(error);
});
five. Request
The Request library is i of the simplest ways to make HTTP calls. The structure and syntax are very like to that of how requests are handled in Node.js. Currently, the project has 18K stars on GitHub and deserves a mention for being one of the popular HTTP libraries bachelor.
Syntax
var request = require('request');
request('http://www.yourdomain.com', function (fault, response, body) {
panel.log('error:', error);
console.log('statusCode:', response && response.statusCode);
panel.log('torso:', torso);
});
six. SuperAgent
SuperAgent is a lightweight and progressive AJAX library that'southward focused more on readability and flexibility. SuperAgent also boasts of a gentle learning curve unlike other libraries out there. SuperAgent has a request object that accepts methods such as Get, Mail, PUT, DELETE, and HEAD.
Pros of SuperAgent
- It has a plugin-based environment and ecosystem where plugins could be congenital and developed for extra or additional functionality.
- Easily Configurable.
- Nice interface for making HTTP requests.
- Multiple functions chaining to send requests.
- Has to support for upload and download progress.
- Has support for chunked transfer encoding.
- One-time-style callbacks are supported
- Numerous plugins available for many common features
Performing Get Asking
request
.get('/user')
.query({ id: ane })
.then(res => { });
Performing Post Request
asking.post('/user')
.set('Content-Type', 'application/json')
.send('{"proper noun":"Ipseeta","id":1}')
.then(callback)
.catch(errorCallback)
Conclusion
The selection depends or differs on your project, its scale, and its target and accepted audience. No pick is neither correct nor wrong. The question might exist answered if you lot select the wrong library for the wrong requirements. Option the right tool for the job.
If yous have whatsoever questions or suggestions regarding this or if y'all recollect I should add, right or remove, experience free to comment.
Thanks for reading!
Source: https://medium.com/@Sharad35386442/6-different-ways-to-do-ajax-calls-in-javascript-b47200fe7a38
0 Response to "Javascript Run Same Ajax Function Again Depending on Response"
Post a Comment