+ 3
[Solved]How can I make a javascript function that return ajax response?
If use ajax in a javascript code many time then how can I make a function so that I can use it as function and call it when necessary (no jQuery)
13 ответов
+ 3
Code :
const dataReady = (link) => {
return new Promise((resolve, reject) => {
$.ajax({
url: data',
dataType: 'json',
type: 'GET',
success : data => {resolve(data)},
error: () => {reject('Something went wrong!');}
});
});
}
Usage :
Pass the link as the argument of the function, and then use the '.then()' function to get the data, like below :
dataReady('https://data-link.com').then(data => {
console.log(data);
});
+ 2
Sure, here is the explanation :))
I am using the .ajax method to set an ajax request.
$.ajax();
This method takes an objective as an argument which contains information about the request like url, dataType, etc.
$.ajax({
url : 'url',
dataType: 'json'
});
However, most importantly it has success and error property :
$.ajax({
url : 'url',
dataType: 'json',
success: (data) => {
console.log("I got the data");
console.log(data);
},
error: (err) => {
console.log("Something went wrong");
console.log(err);
}
});
+ 1
Arb Rahim Badsa What is the meaning of the line
return new Promise ((resolve,reject)
Can we do this without jQuery?
Promise means?
+ 1
Sure, it is a new addition of ES6. You can now make promise with only javascript! Promise is actually a better way to fetch data from. The function is just returning a new javascript Promise which resolving the data we get from the ajax request. I suggest you to research a bit on what is promise, if you are curious :))
+ 1
async function fetchApi () {
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json(); // or response.text() for get text string
console.log(JSON.stringify(json));
// document.body.innerHTML = contents;
} else {
alert("HTTP-Error: " + response.status);
}
}
fetchApi()
+ 1
Function takes argument of api endpoint
+ 1
SOUPTIK NATH Your code was almost correct :)) Just a bit correction :
this.status == 200
Not
this.status == 20
Here's the code :))
https://code.sololearn.com/WApBRrc6CHB8/?ref=app
0
Aren't you allowed to use jQuery? I can explain you the function if you are allowed to use :))
0
Arb Rahim Badsa ok tell
0
Arb Rahim Badsa Can you please explain cause I don't know jQuery
0
Why your code gives an error?
https://code.sololearn.com/W2wTaUX81M8G/?ref=app
0
Calviղ Is there an api for that?
0
Calviղ I am not able to understand please explain