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.
Related
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);
In my application I need to conduct an IP lookup as a prerequisite to proceeding with execution of another function that needs that data. Originally, I called the function as follows:
$(document).ready(function(){
var ipUrl = "myURL?callback=?";
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(printIp());
});
function printIp() {
console.log("function is done " + window.ip);
}
However, this outputs as
function is done undefined
inside function <ip_address>
I.e. the printIp() function is called before the $.getJSON is actually complete.
If however, I wrap the printIp() call within an anonymous function as follows:
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(function() {
printIp();
});
I get:
inside function <ip_address>
function is done <ip_address>
As I would expect. What is going on here? Why do I need to wrap the function call in an anonymous function?
your code says
}).done(printIp());
what this does is calling printIp and using the result of the function call as an argument to the done method.
what you actually want is passing the function as a done handler. use }).done(printIp); to do this instead.
You are executing printIp right away. Try it without the ():
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(printIp);
pass the function without parantheses, otherwise you are calling it right away:
.done(printIp)
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.
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);
}
}
);
}
You can I wrap this code so that when a call a function returns the variable contianing the json object?
Example:
function GetNewSomething() {
var newtb = 0;
$.get("/something/new",
function (data) {
newtb = data;
}
);
return newtb; // as of now this always returns undefined...
}
Tried this way, but only return undefined..
Thanks in advance guys!
regards,
You can't. Ajax calls are asynchronous. You have to pass a callback to your function:
function GetNewSomething(cb) {
$.get("/something/new", cb);
}
and call it with:
GetNewSomething(function(data) {
// do something with data
});
I wrote something about it.
Oh and if the response is a JSON string, you might want to use .getJSON which also decodes the response into a JavaScript object.
.get() is a wrapper to $.ajax(). All AJAX request run asyncronously if not explicitly configured otherwise. That in turn means, that your return newtb; statement will occur before $.get() has finished.
A good way to workaround this issue is to invoke another callback on your own. This could look like:
function GetNewSomething(callback) {
$.get("/something/new",
function (data) {
if( typeof callback === 'function' )
callback.apply(this, [data]);
}
);
}
And then call it like
GetNewSomething(function(data) {
// do something with data
});
The $.get is asyncronous, which is the reason you pass it a function to call when the get request returns.
You could change to make the $.get a $.ajax and make it syncronous since $.get is just a wrapper for a $.ajax:
function GetNewSomething() {
var newtb = 0;
$.ajax({url:"/something/new",
type:"GET",
async:false,
success: function (data) {
newtb = data;
}
});
return newtb;
}