Can't implement deferred promise in jquery ajax - javascript

I'm struggling to implement deferred to get async ajax response. I have this setup:
report.js
function getReport(ref)
{
$.ajax({
url: "report.php",
dataType: 'json',
data: {
ref: ref,
},
success: function(result){
return (result);
}
}
});
}
index.html
<script>
function firstFunction() {
console.log ("start");
getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
var test = firstFunction();
alert(test);
</script>
Currently I get "undefined" returned straight away because the alert box doesn't wait for the ajax function to run. Using some tutorials online i've tried to implement it this way:
report.js
function getReport(ref)
{
var deferred = $.Deferred();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
ref: ref,
},
success: function(result){
deferred.resolve(result);
}
}
});
returned deferred.promise();
}
index.html
<script>
function firstFunction() {
console.log ("start");
getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
$.when(getData()).done(function(value) {
alert(value);
});
getData().then(function(value) {
alert(value);
});
</script>
I've obviously made a few mistakes on the way because I'm getting the errors below and I can't seem to get past it:
Uncaught SyntaxError: Unexpected identifier
index2.html:12 start
index2.html:13 Uncaught ReferenceError: getReport is not defined
at firstFunction (index2.html:13)
at index2.html:16

I think the addition of the deferred object in getReport is unnecessary because $.ajax already creates one for you. It might be better to modify your original code this way:
function getReport(ref)
{
return $.ajax({ // Return the deferred object here. It is returned by .ajax()
url: "report.php",
dataType: 'json',
data: {
ref: ref,
} // Remove the callback here.
// You cannot call return in the way you're trying here.
// The context is different and outside of normal flow.
});
}
then in your index file:
<script>
function firstFunction() {
console.log ("start");
// You must return the returned value here as well, otherwise variable `test` is going to be undefined.
return getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
var test = firstFunction(); // test is now a deferred object
test.done(function(data) {
alert(data);
});
</script>

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
});

Synchronous AJAX (broken promises)

I'm attempting to coax JavaScript into synchronous behaviour, but I've so far failed.
I've tried 30 or more different methods, and here is the latest attempt, based on another answer, here on StackOverflow:
function fnc () {
$.ajax({
type: 'GET',
url: "libraries/resources/data.json",
dataType: 'json',
success: function (data) {
...
objSomething = {
...
};
},
error: function () {}
});
}
fnc().then(function(objSomething) {
google.maps.event.addDomListener(window, 'load', function(){ initialize(objSomething); });
}).catch(function(objSomething) {
...
});
However, I'm getting an error:
TypeError: undefined is not an object (evaluating
'fnc().then')
Most of the methods I've tried have resulted in similar errors.
As for the Google Maps code, it does work (although not always, due to the asynchronous nature of the code execution).
It's worth noting that while I'm able to write complex code from scratch, when it comes to the underlying mechanics, I'm not that proficient.
I'm using jQuery 2.2.2, via the Google API CDN.
This is a solution you are looking for.
function fnc () {
var dfd = jQuery.Deferred();
$.ajax({
type: 'GET',
url: "libraries/resources/data.json",
dataType: 'json',
success: function (data) {
...
objSomething = {
...
};
dfd.resolve(objSomething);
},
error: function (error) { dfd.reject(error); }
});
return dfd.promise();
}
$.when(fnc()).then(function(objSomething) {
google.maps.event.addDomListener(window, 'load', function(){
initialize(objSomething);
});
}, function(error){
//Handle Error
});
use $.ajax function you can use the then function. Refer the following link:
http://wildermuth.com/2013/8/3/JavaScript_Promises

How to wrap object in a Promise?

I have a code that searches for some data in memory storage and if not found searches that data on server and caches it in memory.
How can I return an object as a Promise so that the caller can just invoke a "done" on it?
The code looks like that:
if (foundInLocalStorage)
{
// This part I cannot make to work, caller does not have its 'done' fired
var defered = $.Deferred();
defered.resolve();
defered.promise(dataFound);
}
else
{
return $.ajax
(
{
url: someUrl,
dataType: 'json',
data: { id: 101 }
}
)
.done
(
//That part is fine
......
);
}
You need to return a promise
if (foundInLocalStorage) {
var defered = $.Deferred();
defered.resolve(dataFound);//resolve the promise with the data found
//or setTimeout(defered.resolve.bind(promise, 5)); if you want to maintain the async nature
return defered.promise();//return a promise
} else {
return $.ajax({
url: someUrl,
dataType: 'json',
data: {
id: 101
}
}).done(
//That part is fine
......
);
}

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)

Categories

Resources