How to handle ajax response in FLUX - javascript

I'm new in FLUX and I have problem how to handle ajax in FLUX.
My situation is following :
I have file commentAPI.js
//all js files are compiled from coffescript
// fetching all comments from server
_fetchComments: function() {
var promise;
promise = $.ajax({
url: "comments/show",
type: "GET",
dataType: "json"
});
return promise.then(function(response) {
// here should be any action ?
}, function(error) {
return console.log(error);
}); }
Then I have commentActions.js
fetchComments: function () {
allcomments=commentAPI._fetchComments();
return Dispatcher.dispatch({
actionType: ActionTypes.ALL_COMMENTS,
comments: allcomments
});
}
This code actually doesnt work because function _fetchComments called in commentActions.js return whole promise.
What I want to do: I would like to get response from ajax callback function and pass the result to my payload object and then dispatch it by Dispatcher in my _fetchComments() function in commentActions.js
How is the best way to do it? How can I get the access to the ajax callback function response ?

You should dispatch _fetchComments function and when that promise is resolved, invoke the action fetchComments.
In the react code you should invoke the async function (i.e. _fetchComments).
In your example:
// fetching all comments from server
_fetchComments: function() {
var promise;
promise = $.ajax({
url: "comments/show",
type: "GET",
dataType: "json"
});
return promise.then(function(response) {
// put the sync action here
fetchComments(response)
}, function(error) {
return console.log(error);
}); }
And don't forget to remove it from the action (i.e fetchComments)

Related

ajax promise data undefined

I'm somewhat breaking my head over this. I have an ajax call like this:
function genericname()
{
var domain = $('#input').val();
var sendData = {
'domain': domain
};
var promise = $.ajax(
{
type: 'POST',
url: '/functions.php',
data:
{
module: 'modulename',
operation: 'functionname',
parameters: sendData
},
dataType: 'json'
}).promise();
promise.then(function(data)
{
console.log(data);
return data;
});
promise.fail(function(data)
{
console.log(data);
});
}
Now the problem is that when debugging I notice that both promise.then and promise.fail are just skipped. The php proces I am calling to output is true. Actually when I look in the network tab of the debug tools the response says true.
Could anyone explain what the mistake is here?
EDIT: the result being output by the php function is json_encoded
This function is being called in the .then portion of another ajax call
remove .promise at the end of ajax request:
var domain = $('#input').val();
var sendData = {
'domain': domain
};
var promise = $.ajax(
{
type: 'POST',
url: '/functions.php',
data:
{
module: 'modulename',
operation: 'functionname',
parameters: sendData
},
dataType: 'json'
})
The issue is fixed now and here is how I solved it.
The function was required to return a boolean which was used in the if statement in another .then statement of another ajax call to change some html.
In the end I resorted to placing the html changes in the .then portion if this function.
Hope I can help someone with this information.

How to replace 'Async=false' with promise in javascript?

I have read a lot about promises but I'm still not sure how to implement it.
I wrote the folowing AJAX call with async=false in order for it to work, but I want to replace it with promise as I saw that async=false is deprecated.
self.getBalance = function (order) {
var balance;
$.ajax({
url: "/API/balance/" + order,
type: "GET",
async: false,
success: function (data) {
balance = data;
},
done: function (date) {
}
});
return balance;
}
Would you be able to help me? I just need an example to understand it.
As first point, you don't want to set an asynchronous call to false as it will lock the UI.
You could simplify your method returning the ajax object and the handle it as a promise.
self.getBalance = function (orderNumber) {
return $.ajax({
url: "/Exchange.API/accountInfo/balance/" + orderNumber,
type: "GET",
});
};
var demoNumber = 12;
self.getBalance(demoNumber).then(function(data){
console.log(data);
},function(err){
console.log("An error ocurred");
console.log(err);
});
Return promise object from getBalance method:
self.getBalance = function (orderNumber) {
return $.ajax({
url: "/Exchange.API/accountInfo/balance/" + orderNumber,
type: "GET"
});
}
and use it later like this:
service.getBalance().then(function(balance) {
// use balance here
});

returned object is undefined in a custom ajax service

I created an AngularJS service which does ajax request to the server and returns the response object to the controller. Below is my service
app.factory('ajaxService', function() {
return {
ajaxcall: function(url, type, data, handler) {
$.ajax({
url: url,
type: type,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-OCTOBER-REQUEST-HANDLER", handler);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
})
.done(function(response) {
console.log("ajaxService done: ");
console.log(response);
return response;
})
.fail(function(response) {
console.log("in onCheckUser-error: ajaxService ");
});
}
}
});
The controller is defined as below
var app = angular.module('starter', [])
app.controller('myCtrl', function(ajaxService) {
var res = {};
res = ajaxService.ajaxcall("https://www.travelmg.in/check-login",'POST','',"onCheckLogin");
console.log(res);
});
Here, i get the expected response in console in the ajaxService service. When i return the response, i see an "undefined" value in res variable in console.
I don't understand why the res variable is undefined. Please suggest
Thats because your making an asynchronous call, which means it will not return the result immediately.
only way to resolve this is to receive the promise object returned from $.ajax & use the .done() function on it to receive the successful data.
What you need to do:
Move the done() & fail() outside service factory.
return the ajax promise object all the way to the consumer, i.e controller.
JS CODE:
//service factory code
return {
ajaxcall: function(url, type, data, handler) {
return $.ajax({
url: url,
type: type,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-OCTOBER-REQUEST-HANDLER", handler);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
});
}
}
//controller code
app.controller('myCtrl', function(ajaxService) {
var res = {};
ajaxService.ajaxcall("https://www.travelmg.in/check- login",'POST','',"onCheckLogin")
.done(function(response) {
console.log("ajaxService done: ");
console.log(response);
//return response; // dont return instead process the result here
})
.fail(function(response) {
console.log("in onCheckUser-error: ajaxService ");
});
});
Note:
I would personally dont prefer mixing jquery and angularjs library unless jquery is really needed for some third party library. both are two different frameworks with different ideology,so dont mix them.
also if your referring to jquery only for $.ajax api ? then i would suggest you to use $http, whose API is same as $.ajax. ref: https://docs.angularjs.org/api/ng/service/$http
You have built the application in angular so it would be convenient to use $http directive to make ajax calls. Inject $http is your service, then you can handle the response as such:
ajaxService.ajaxcall("https://www.travelmg.in/check-login",'POST','',"onCheckLogin").then(function(response) {
console.log(response.data);
});

Turn several ajax requests into Observables with RxJS

I'm struggling with something - which I'm guessing means I've misunderstood and am doing something silly
I have an observable and need to use it to create some object, send that to the server for processing, combine a result from the server with the object I sent, and then turn that into an observable so what I want to do (I think) is something like
var theNewObservable = my.observable.things.select(function(thing) {
var dataToSend = generateMyJavascriptObjectFrom(thing);
var promise = $.ajax({
type: 'POST',
url: http://somewhere.com,
data: dataToSend
}).promise();
return rx.Observable.fromPromise(promise).subscribe(function(data, status, jqXHR) {
var infoFromServer = jqXHR.getResponseHeader('custom-header-returned');
// I'm wanting this to be the thing other code can subscribe to
return { infoFromServer: dataToSend };
}, function(err) {
alert('PC LOAD LETTER!');
console.error(err);
});
}
});
theNewObservable.subscribe(function(combinedInfo) { console.log(combinedInfo) };
where I'm expecting {infoFromServer: dataToSend} I'm getting an AutoDetachObserver and I can see that has an onNext with the ajax onSuccess signature so I'm obviously doing something silly
A couple things that should help a bit:
1) The subscribe method is a terminal method, as in, it won't return anything. It is where the Observer attaches so there should be no further data propagation after the subscribe
2) The onNext method of subscribe can only take a single value which you will need to have all the message data wrapped in.
Since jQuery's Promise will not behave well with this, you have two options. First, you can use the RX-DOM project for an Observable ajax version. Or you will need to wrap the promise method. If you further need to wait on the response you should be using selectMany instead, which will allow you to fire off the promise, then await its return and map the response to the original request.
var theNewObservable = my.observable.things
//Preprocess this so that `selectMany` will use
//dataToSend as the request object
.map(function(thing) { return generateMyJavascriptObjectFrom(thing); })
.selectMany(function(dataToSend) {
var promise = $.ajax({
type: 'POST',
url: http://somewhere.com,
data: dataToSend
}).promise();
//Rewrap this into a promise that RxJS can handle
return promise.then(function(data, status, jqXHR) {
return {data : data, status : status, jqXHR : jqXHR};
});
}, function(request, response) {
return {
infoFromServer : response.jqXHR.getResponse('custom-header'),
dataToSend : request
};
});
theNewObservable.subscribe(
function(combinedInfo) {
console.log(combinedInfo)
},
function(err) {
alert('PC LOAD LETTER!');
console.error(err);
});

Using custom function as parameter for another

I'm currently dealing with refactoring my code, and trying to automate AJAX requests as follows:
The goal is to have a context-independent function to launch AJAX requests. The data gathered is handled differently based on the context.
This is my function:
function ajaxParameter(routeName, method, array, callback){
//Ajax request on silex route
var URL = routeName;
$.ajax({
type: method,
url: URL,
beforeSend: function(){
DOM.spinner.fadeIn('fast');
},
})
.done(function(response) {
DOM.spinner.fadeOut('fast');
callback(response);
})
.fail(function(error){
var response = [];
response.status = 0;
response.message = "Request failed, error : "+error;
callback(response);
})
}
My problem essentially comes from the fact that my callback function is not defined.
I would like to call the function as such (example)
ajaxParameter(URL_base, 'POST', dataBase, function(response){
if(response.status == 1 ){
console.log('Request succeeded');
}
showMessage(response);
});
I thought of returning response to a variable and deal with it later, but if the request fails or is slow, this won't work (because response will not have been set).
That version would allow me to benefit the .done() and .fail().
EDIT : So there is no mistake, I changed my code a bit. The goal is to be able to deal with a callback function used in both .done() and .fail() context (two separate functions would also work in my case though).
As far as I can see there really is nothing wrong with your script. I've neatened it up a bit here, but it's essentially what you had before:
function ajaxParameter (url, method, data, callback) {
$.ajax({
type: method,
url: url,
data: data,
beforeSend: function(){
DOM.spinner.fadeIn('fast');
}
})
.done( function (response) {
DOM.spinner.fadeOut('fast');
if (callback)
callback(response);
})
.fail( function (error){
var response = [];
response.status = 0;
response.message = "Request failed, error : " + error;
if (callback)
callback(response);
});
}
And now let's go and test it here on JSFiddle.
As you can see (using the JSFiddle AJAX API), it works. So the issue is probably with something else in your script. Are you sure the script you've posted here is the same one you are using in your development environment?
In regards to your error; be absolutely sure that you are passing in the right arguments in the right order to your ajaxParameter function. Here's what I am passing in the fiddle:
the url endpoint (e.g http://example.com/)
the method (e.g 'post')
some data (e.g {foo:'bar'})
the callback (e.g function(response){ };)
Do you mean something like this, passing the success and fail callbacks:
function ajaxParameter(routeName, method, array, success, failure) {
//Ajax request on silex route
var URL = routeName;
$.ajax({
type: method,
url: URL,
beforeSend: function () {
DOM.spinner.fadeIn('fast');
}
}).done(function (response) {
DOM.spinner.fadeOut('fast');
success(response);
}).fail(function (error) {
var response = [];
response.status = 0;
response.message = "Request failed, error : " + error;
failure(response);
})
}
Called like:
ajaxParameter(
URL_base,
'POST',
dataBase,
function(response){
//success function
},
function(response){
// fail function
}
);

Categories

Resources