How can I wrap an ajax request into a function? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
Here is my code:
function ajaxRequest(value, path, website){
window[website] = $.ajax({
url : path,
type : 'GET',
data: { "name": value,
"_token": $('meta[name="_token"]').attr('content')
},
beforeSend: function(){
if(window[website] != null) {
window[website].abort();
}
},
success: function (people) {
return [status, people];
},
error: function (jqXHR, textStatus, errorThrown) {
return [status, textStatus];
},
timeout: 15000
});
}
As you see, it's a function that sends ajax requests. I call it like this:
var res = ajaxRequest('Jack', 'search/twitter', 'twitter');
console.log(res);
It returns:
Why I don't see the result in the console? Noted that I can see the result in the console if I send that ajax out of function. (the result is an array of data)
How can I fix the problem?

function ajaxRequest(value, path, website){
return new Promise(function (resolve, reject) {
window[website] = $.ajax({
url : path,
type : 'GET',
data: { "name": value,
"_token": $('meta[name="_token"]').attr('content')
},
beforeSend: function(){
if(window[website] != null) {
window[website].abort();
}
},
success: function (people) {
resolve([status, people]);
},
error: function (jqXHR, textStatus, errorThrown) {
reject([status, textStatus]);
},
timeout: 15000
});
});
}
then do this, to get the result:
ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)})`;

For first you haven't return anything from your function, default is undefined.
Second, your res will not be the result of your ajax call. Because ajax is an asynchronous call, the result which will you get is accessible only in the function success or error.
See here. You can't return this. All other logic which you need to implement based on the data you need to write here.
success: function (people) {
// Your logic here
},

Related

Return Data from Ajax request [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I recover data from a Requette in ajax. I want to use this data in a function and return it but when I call the function it returns nothing
function getdata(nom_produit) {
$.ajax({
type: "POST",
url: "traitement/panne/test_panne.php",
data: {
nom_produit: nom_produit
},
success: function(data) {
var obj = jQuery.parseJSON(data);
jQuery.each(obj["resultat"], function(index, value) {
})
}
});
return obj;
}
how i can return the data?
you can't return from like this. $.ajax is an asynchronous call so when return is called your success function is still pending execution. you can do something like below though to achieve same result.
function getdata(nom_produit, callback) {
$.ajax({
type: "POST",
url: "traitement/panne/test_panne.php",
data: {
nom_produit: nom_produit
},
success: callback
});
}
and from the place you are calling this function you can do something like below
var successFunction = function(data) {
hideOverlay(); // hide overlay once response is there
// your code to process data and show in UI
}
showOverlay(); // code to show loading image in UI till response comes
getData(someId, successFunction);

Why can't I wrap js promise resolve in a jquery object?

I wanted to be able to send the data from a successful jquery ajax call to other methods in my application because its quite large and it made coding sense to have one api method to work from, so I opted to try out promises. This is my first shot. I am getting some good results but clearly I am still a bit confused on context and timing.
When I run the following code, I am unable to wrap my return data from the ajax call as a jquery object without getting an error:
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
var $selectTarget = $(this),
widgetid = $(this).data('widgetid');
apiRequestData = widgetSystem.makeApiRequestForSingleWidget(widgetid);
apiRequestData.then(function(result) {
widgetSystem.showWidget(result);
}).catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: "localhost",
dataType: 'json',
data: {
data: {
widgetId: widgetid
},
action: 'apiMethod'
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
reject();
},
success: function (data) {
resolve(data);
}
});
});
},
showWidget: function(data){
$(data).appendTo('body');
//this causes an exception in my apiRequestData.then function in listenForClick
}
}
I am running un minified jquery and getting the following error in my console:
no way big error TypeError: context is undefined
I don't know exactly what your HTML looks like or how the API is set up, but assuming that the API is working correctly and the data sent via POST is correct, I was able to get it working using jsonplaceholder api with the following code (you can find it on JSbin).
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
console.log('clicked');
var $selectTarget = $(this);
var widgetid = $(this).data('widgetid');
widgetSystem.makeApiRequest(widgetid)
.then(function(result) {
widgetSystem.showWidget(result);
return result;
})
.catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
method: "POST",
url: root+'/posts/',
dataType: 'json',
data: {
userId:1,
title:"Havanagila",
body:"Testing the greatness"
},
success: function(xData, status){
resolve(xData);
//reject('whoops');
},
error: function(xhr, status, error){
reject(status);
}
});
});
},
showWidget: function(data){
$('#space').append(document.createTextNode(JSON.stringify(data)));
}
}
widgetSystem.listenForClick()
I don't think there is an issue which how you are calling resolve(data) within the ajax success callback. There may be an issue with the data being sent to your API such that the error callback is called, which in turn calls reject and causes the callback passed to .catch to be called instead of the intended callback passed to .then.

Using Deferred in React.js or callback in my success function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a React/ Flux app I am trying to return my "promiseSuccessData" but it has to be done outside of the ajax promise. Within the getChallengeData().
getChallengeData : function() {
$.ajax({
type: 'GET',
url: baseUrl + '1.0/challenge/result/' + challengeId,
crossDomain: true,
xhrFields : {
withCredentials : true
},
})
.done(function(promiseSuccessData) {
_challenges = promiseSuccessData;
})
.fail(function(jqXhr) {
console.log(jqXhr)
console.log('failed to register');
});
//This is where I want to "return _challenges" but _challenges isn't available here
},
You should return the promise instead, and add the done handler outside where you need to use the value (I will assume that getChallengeData is a method of an object called myObj for the sake of the example):
getChallengeData : function() {
return $.ajax({
type: 'GET',
url: baseUrl + '1.0/challenge/result/' + challengeId,
crossDomain: true,
xhrFields : {
withCredentials : true
},
}).fail(function(jqXhr) {
console.log(jqXhr)
console.log('failed to register');
});
},
And then, when you use it:
myObj.getChallengeData().done(function(promiseSuccessData) {
_challenges = promiseSuccessData;
//do something with challenges.
});
Edit: Saw that the OP wanted to return the value of _challenges, not just work with it somehow.
You can't work with _challenges until the done function has run. When working with asynchronous Promises, you'll want to return the actual Promise (jQuery Deferred?) and have the caller attach his own handler.
function foo() {
obj.getChallengeData()
.done(function(challenges) {
// Work with challenges here
});
}
var obj = {
getChallengeData : function() {
return $.ajax({
type: 'GET',
url: baseUrl + '1.0/challenge/result/' + challengeId,
crossDomain: true,
xhrFields : {
withCredentials : true
},
})
.fail(function(jqXhr) {
console.log(jqXhr)
console.log('failed to register');
});
},
// Other props
}

Dojo Get data from server and store in a variable using xhrGet

I have the following function:
loadMsgBody: function (id) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
return response;
},
error: function (response) {
alert(response);
}
});
}
And calling it:
var text = "";
this.loadMsgBody(this.msgId).then(function (response) {
text = response;
});
Now I expect to get the return value of the function but instead I am getting an empty value for text. However, in Firebug I do see the response from the server with the correct value. I've searched and found these links : DOJO xhrGet how to use returned json object?
and:
Using hitch / deferred with an xhrGet request
But I still can't get and store the data with the above code. I don't want to do the manipulation inside the xhrGet call, I want to retrieve the data and use as it will be used multiple times.
Is there anything I am missing?
Dojo's XHR methods return instances of the class dojo/Deferred, because they are asynchronous. What this means is that the functions returns before the value of the response is available. In order to work with the results of the asynchronous response you need to wait for it to return. Dojo exposes this using a uniform API, Deferreds. Instances of the dojo/Deferred class have a method then. The then method takes a function as a parameter. That function will execute once the Deferred have been resolved (in this case, when the request has completed).
var deferred = loadMsgBody();
deferred.then(function(response){
//work with response
});
I would try changing your load function to evoke your callback function:
loadMsgBody: function (id, callback) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
if(callback) {
callback(response);
}
},
error: function (response) {
alert(response);
}
});
}
Try this:
loadMsgBody: function (id, callback) {
return dojo.xhrGet({
url: "myurl",
handleAs: "text",
content: {
id: id
},
load: function (response) {
callback.apply(null,[response]);
},
error: function (response) {
alert(response);
}
});
}
Then:
var text = "";
this.loadMsgBody(this.msgId, function (response) {
text = response;
console.log("text:",text); // this will show your return data
});
console.log("text:",text); // this will show empty data because ajax call is asynchrize, at this time , data not return yet.
setTimeout(function(){
console.log("text:",text); // this will show your return data again because ajax call should have finished after 30000 ms
},30000)

Can I get the return code of a function called with Ajax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can't get correct return value from an jQuery Ajax call
This is an extension of my previous question:
Can I check the return code from a function called with Ajax like this below:
rc = submitHandler($link, $modal);
function submitHandler($link, $modal) {
$.ajax({
url: oSubmit.href,
dataType: 'json',
type: 'POST',
data: $form.serializeArray()
})
.done(function (json, textStatus, XMLHttpRequest) {
json = json || {};
if (json.success) {
submitSuccessModal(oSubmit, json);
return true; <---------------------------------------
} else {
submitFailModal(oSubmit, json);
return false; <--------------------------------------
}
return false;
})
}
You can add a function block for each status code respectively
$.ajax({
statusCode: {
404: function() {
alert("page not found");
},
500: function() {
alert("internal server error")
},
...
}
});

Categories

Resources