I am struggling to totally understand callbacks and i am stumbling at the final hurdle.
Within JS I am calling a function which then calls a PHP function using a dojo rpc Json Service. I have stepped through the function in firebug and the PHP is executing and returning me the correct response via the callback but I don’t know how to return the value to the initial JS variable that invoked the JS function? E.g.
JS Function 1
Function one(){
Var test = getPhp(number);
}
function getPhp(number)
{
this.serviceBroker = new dojo.rpc.JsonService(baseUrl + '/index/json-rpc/');
var result = serviceBroker.phpFunc(number);
result.addCallback(
function (response)
{
if (response.result == 'success')
{
return response.description;
//I am trying to pass this value back to the
//var test value in function one
}
}
);
}
Basically i now need to pass response.description back to my var test variable in function one.
Any help is appreciated
This is not possible, since the callback is run asynchronously. This means that the getPhp function returns before the callback is executed (this is the definition of a callback, and one of the reasons asynchronous programming is hard ;-) ).
What you want to do is create a new method that uses the test variable. You need to call this method when the callback is executed.
i.e.
function one(result) {
var test = result;
// Do anything you like
}
function getPhp(number, callback) {
this.serviceBroker = new dojo.rpc.JsonService(baseUrl + '/index/json-rpc/');
result.addCallback(
function (response)
{
if (response.result == 'success')
{
callback(response.description);
}
}
);
}
getPhp(number, function(result) { one(result); });
This last method creates an 'anonymous function' that is passed to the getPhp function. This function gets executed at the time the response arrives. This way you can pass data to the one(number) function after the data arrives.
The short answer is that you can't.
Do whatever you want to do with the data in the callback or functions you call from the callback. You can't return anything from it.
A much cleaner answer:
getPhp(number);
function one(data){
var test = data;
// do what you want
}
function getPhp(number)
{
this.serviceBroker = new dojo.rpc.JsonService(baseUrl + '/index/json-rpc/');
var result = serviceBroker.phpFunc(number);
result.addCallback(
function (response)
{
if (response.result == 'success')
{
one(response.description);
}
}
);
}
Related
I'm trying to get some data in multiple functions and would like to chain them in order to execute the last function only when all data was properly loaded.
The problem is that the functions in the .done() part will be called instantly and don't wait until the Deferred-Object is resolved. I also tried it by chaining them with .then() but this also didn't work.
var array1, array2;
function doStuffWithReceivedData() {
// Working with the data
}
function getArray1() {
var defArray1 = $.Deferred();
$.getJSON(url, function(data) {
if (data.success) {
array1 = data.payload;
defArray1.resolve();
} else {
// Information displayed that there was an error
}
})
return defArray1;
}
// Function 2 is like the first one
function getArray2() {...};
$(document).read(function() {
getArray1()
.done(getArray2()
.done(doStuffWithReceivedData()));
}
The argument to .done() must be a function. You're calling the function, not passing it. Take off the parentheses.
$(document).ready(function() {
getArray1()
.done(function() {
getArray2().done(doStuffWithReceivedData));
}
}
i have a little understanding problem with my current code...
i create a new require js module.
define(['jquery','apiomat'],function($,Apiomat) {
var getLocation = function(data, callback) {
Apiomat.Localization.getLocalizations("locale like 'de'", {
data: data,
onOk: function (data) {
callback(data);
}
});
};
return {
getData: function(data, callback) {
getLocation(data, callback);
}
}
});
And if i try to access these function with:
var test = easy.getData();
app.logger("CALLBACK FROM COMMON: " + JSON.stringify(test));
I always get this error message.
TypeError: callback is not a function. (In 'callback(data)', 'callback' is undefined)
Im not really sure what i have done wrong.
getData takes two arguments. The second one is supposed to be a function, but you aren't passing any arguments at all, so it gets the value undefined.
It then calls getLocation with the same arguments and Apiomat.Localization.getLocalizations does its thing. Eventually getLocalizations (or another function called by it) calls getOK which attempts to call callback.
undefined is not a function, so you get the error message.
Additionally the getData function doesn't have a return statement so will be returning undefined. This means there is no point in assigning the return value to test.
You need to pass a function which does whatever you want to do:
function myCallback(test) {
app.logger("CALLBACK FROM COMMON: " + JSON.stringify(test));
}
… and pass arguments to getData.
easy.getData("some data", myCallback);
This works:
function getDataJSON() {
var queryString = "https://www.examplesite.com/someJSON.json";
$.getJSON(queryString, function(data) {
doStuffWithData(data)
});
}
function doStuffWithData(JSON) {
// some code that refers to JSON
}
getDataJSON();
But this complains that a variable (JSON) is undefined somewhere in doStuffWithData():
function getDataJSON(callback) {
// Gets share data and runs callback when received
var queryString = "https://www.examplesite.com/someJSON.json";
$.getJSON(queryString, function(data) {
if(typeof callback === "function") {
callback(data);
}
});
}
function doStuffWithData(JSON) {
// some code that refers to JSON
}
getDataJSON(doStuffWithData());
What am I likely to be doing wrong? The $.getJSON() call takes a second or two so I do need to wait for that and do stuff after it. I think the issue is with the code execution order, but it could be that I've misunderstood how to properly pass the data to the callback function.
It would be better if I could just load the data into a variable all my other functions can access.
This:
getDataJSON(doStuffWithData());
should be this:
getDataJSON(doStuffWithData);
Otherwise it invoked that function immediately and attempts to pass the result of the function into getDataJSON
You need to leave out the parenthesis in this call
getDataJSON(doStuffWithData()); should be getDataJSON(doStuffWithData). The reason is that doStuffWithData is the function and doStuffWithData() is the retrun value from the function.
I'm using a jQuery json function inside another function, how can I return an array made in the jQuery function as the return value of my parent function?
this is the basic setup
function getFlickrSet(flickr_photoset_id){
var images = [];
images = $.getJSON(url, function(data){ return data; // I HAVE THE DATA HERE };
return images // I HAVE NO DATA HERE
}
var myImages = getFlickrSet(23409823423423);
alert(myImages); // this gives me nothing
I have set up an example on jsfiddle right here, if you could tell me where my code is wrong, I would greatly appreciate it.
Thank you!
You can't. Instead, pass in a function:
function getFlickrSet(flickr_photoset_id, when_ready){
var images = [];
$.getJSON(url, function(data){
// prepare images
when_ready( images );
});
}
getFlickrSet(nnnn, function(images) {
alert(images);
});
Why can't you do that? Because the "$.getJSON()" call is asynchronous. By the time that the callback function is called (where you wrote, "I HAVE THE DATA HERE"), the outer function has returned already. You can't make the browser wait for that call to complete, so instead you design the API such that code can be passed in and run later when the result is available.
Well, Ajax is asynchronous (that's what the 'A' stands for), so you must do this in an asynchronous way, which boils down to callbacks. What you need to do is pass a callback function to your outer function that you want to be called ("called back," if you will) when the Ajax request completes. You could just give it 'alert' like this:
function getFlickrSet(flickr_photoset_id) {
images = $.getJSON(url, alert); // <-- just the name of the function, no ()
}
var myImages = getFlickrSet(23409823423423);
// => An alert pops up with the data!
...but more likely you'd write something like this:
function doSomethingWithData(data) { // we'll use this later
alert(data); // or whatever you want
}
function getFlickrSet(flickr_photoset_id, callback) {
// new parameter here for a function ------^
// to be given here -------v
images = $.getJSON(url, callback);
return images // I HAVE NO DATA HERE
}
var myImages = getFlickrSet(23409823423423, doSomethingWithData);
// => Your function `doSomethingWithData` will be called the data as a parameter
// when the $.getJSON request returns.
This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 6 years ago.
I want to something similar to this:
function AjaxService()
{
this.Remove = function (id, call_back)
{
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
call_back(res);
}
}
so my calling program will be like this:
var xx = new AjaxService();
xx.Remove(1,success);
function success(res)
{
}
Also if I want to add more parameters to success function how will I achieve it.
Say if I have success function like this:
var xx = new AjaxService();
//how to call back success function with these parameters
//xx.Remove(1,success(22,33));
function success(res,val1, val2)
{
}
Help will be appreciated.
Use a closure and a function factory:
function generateSuccess (var1,var2) {
return function (res) {
// use res, var1 and var2 in here
}
}
xx.Remove(1,generateSuccess(val1,val2));
What you're passing here is not the generateSuccess function but the anonymous function returned by generateSuccess that looks like the callback expected by Remove. val1 and val2 are passed into generateSuccess and captured by a closure in the returned anonymous function.
To be more clear, this is what's happening:
function generateSuccess (var1,var2) {
return function (res) {
// use res, var1 and var2 in here
}
}
var success = generateSuccess(val1,val2);
xx.Remove(1,success);
Or if you prefer to do it inline:
xx.Remove(1,(function(var1,var2) {
return function (res) {
// this is your success function
}
})(val1,val2));
not as readable but saves you from naming the factory function. If you're not doing this in a loop then Xinus's solution would also be fine and simpler than my inline version. But be aware that in a loop you need the double closure mechanism to disconnect the variable passed into the callback function from the variable in the current scope.
You can pass it as anonymous function pointer
xx.Remove(1,function(){
//function call will go here
success(res,val1, val2);
});
one way to do this:
function AjaxService {
var args_to_cb = [];
this.Remove = function (id, call_back, args_to_callback_as_array) {
if( args_to_callback_as_array!=undefined )
args_to_cb = args_to_callback_as_array;
else
args_to_cb = [];
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
setTimeout( function(){ call_back(res, args_to_cb); }, 0 );
}
}
So you can use it like this:
var service = new AjaxService();
service.Remove(1,success, [22,33]);
function success(res,val1, val2)
{
alert("result = "+res);
alert("values are "+val1+" and "+val2);
}
I usually have the callback execute using a setTimeout. This way, your callback will execute when it gets the time to do so. Your code will continue to execute meanwhile, e.g:
var service = new AjaxService();
service.remove(1, function(){ alert('done'); }); // alert#1
alert('called service.remove'); // alert#2
Your callback will execute after alert#2.
Of course, in case of your application, it will happen so automatically since the ajax callback itself is asynchronous. So in your application, you had better not do this.
Cheers!
jrh