I try to manipulate a variable inside a function. But it seems to forget the values once I exit the function, eventhough the variable is declared outside the function.
The essential code:
var posts = {};
// Perform a data request
// skjutsgruppens-page
$.oajax({
url: "https://graph.facebook.com/197214710347172/feed?limit=500",
*SNIP*
success: function(data) {
$.extend(posts, data);
}
});
// Gruppen
$.oajax({
url: "https://graph.facebook.com/2388163605/feed?limit=500",
*snip*
success: function(data) {
$.extend(posts, data);
}
});
The oajax retrievies data from facebook. I want to make a variable that contains the data from both oajax methods.
The actual code: http://eco.nolgren.se/demo/resihop/#
The issue is likely that the success function executes at an arbitrary time in the future--unless you specifically access posts after you know the success function has executed, you will receive undefined results, completely dependent on function and access timing.
The best approach is to handle this correctly by doing necessary work inside in the success function, or use something like jQuery's .when function.
Related
Sorry folk, I know that my question asked many guys in different form, but I'm disappointed to find a decision my problem.
function testAjax(){
var result = "";
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://api.novaposhta.ua/v2.0/json/",
data: {
"modelName": "Address",
"calledMethod": "getCities",
"methodProperties": {},
"apiKey": "6f94a6391cb5134ee68ddb7924de2a3d"
},
success: function(msg) { result = msg }});
return result;
}
var kor = testAjax();
console.log(kor);
I need to take out data from the ajax request and assign this data to a global variable. But function testAjax returns nothing. I think testAjax returns nothing because it's an async request to server and completes later than return result.
My question - how do I take out a value from $.ajax() and assign this value to a global variable? I tried googling and try decide this problem, but ...
Yes, your hunch is correct - the function is returning result as an empty string because the success handler is called later when the server response is returned. If you wish to do something specific when the response comes in, do so in the success response handler like so:
...
success: function(msg) {
// now you have the response so do something with it
console.log(msg);
}
...
most of the time the logic go inside the success function, whatever you will do with the response do it inside the success function.I think you may bay more time for the code structure and the flow of data inside your app.
good luck
I am wondering is these is any way to access the results of a jquery ajax call in the form a traditional var set to function fashion. For example consider:
function getPoints(){
//An array of JSON objects
var Points;
$.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST',
}).done(function(data){
//console.log(data);
Points.append(data);
});
console.log(Points);
return Points;
}
The commented out console.log show the array of json objects whereas the outer one does not. Now, i have tries this:
var Points = $.ajax({ ...});
And i see the response text within a larger object, but am unsure how to access the responseText. console.log(Points.responseText) yields an undefined variable.
Is this possible with this approach? Here is another question that received a check mark with a similar issue.
I have another solutions, which is the encapsulate my code within the done() function and i will have access to all my data. I was just curious if what i am attempting to do is even doable.
Thank you.
yes it is possible, however, you must wait for the request to be complete before doing so. However, since you can't effectively force the return to wait until the data exists, you're only options are to return a deferred object instead, or re-write the function in such a way that allows it to accept a callback.
function getPoints(){
return $.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST'
});
}
getPoints().done(function(data){
console.log(data);
});
or
function getPoints(callback){
return $.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST',
success: callback
});
}
getPoints(function(data){
console.log(data);
});
Because the Ajax call is done asynchronously you shouldn't return it from the outside function. This would require that you somehow block until the asynchronous call completes. Instead you could pass in a callback function to the getPoints function that will handle the logic of using the points.
function getPoints(callback){
$.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST',
}).done(function(data){
callback(data);
});
}
The asynchronous nature of ajax can make things harder if your used to imperative programming, but it will make your user interface much more responsive.
The log you're calling in the outer function is working with an undefined variable because the function is asynchronous. You can't return it from getPoints because it won't have finished. Any work with the Points variable needs to happen inside the callback (the function passed to done).
I have an AJAX request:
var foo = [],
parse = '';
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
});
Now the string parse is the data that I want. How can I access that data? I tried showing it using alert(), but it's not displaying anything. I think this has to do with the variable scope.
How can I get that data?
parse looks like a global variable so it will be available anywhere. The issue is probably when you're trying to access it. You can ONLY access parse in your .done() handler or some function you call from that.
The reason for this is that your ajax call is asynchronous. That means that the operation starts, the rest of your javascript continues to execute and then SOMETIME LATER the ajax call completes and ONLY then is the parse variable valid. Because of this, there really is no reason to declare the parse variable the way you have. You should just use its value inside the .done() handler.
This is asynchronous programming and works differently than synchronous, sequential programming. You must use asynchronous programming techniques with asynchronous ajax calls.
If you try to access parse inside the .done() handler and it's still empty in there, then the issue is likely that data.item isn't what you think it is and maybe isn't triggering the .each() loop and thus nothing is getting put into foo or parse. To debug this case, you should look at what exactly is in data and data.item.
This would be my suggestion:
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
// no reason for these variables to be wider scope than here
var foo = [], parse;
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
// look at parse here
console.log(parse);
// if parse still empty, then look at data and data.item here
// to see what they are for debug reasons
console.log(data);
console.log(data.item);
// now, you can use parse here
callSomeFunction(parse);
});
I have a javascript function to which I am being passed a functionName that I need to call after making a ajax call. The ajax call is returning some html that contains a reference to a js file. The functionName being passed to my function is in the html but it is referencing an object in the js file. What I am noticing that the object sometimes exists and sometimes doesn't. Is there a way to ensure that the object always exists(or wait till it exists) and then only call the javascript function. Please note that I have no idea what the object variable is, so is there a way to ensure that the script file has been loaded in dom and then make the call to the function.
function(functionName)
{
$.ajax({
url: properties.url,
type: properties.type,
data: properties.data,
dataType: properties.format,
success: function (data) {
// data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script>
// Put the data in some div
BindData(data);
// How to ensure that the script myfile.js is loaded in dom before I call eval
eval(functionName);
} );
}
function(functionName)
{
$.ajax({
url: properties.url,
type: properties.type,
data: properties.data,
dataType: properties.format,
success: function (data) {
// data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script>
// Put the data in some div
BindData(data);
//ensure the script has loaded.
$.getScript($('script:first',data).attr('src'), function(){
eval(functionName);
});
});
}
You can try to watch what is data before the ajax call end.
Not sure but, if data is "undefined" you can check something like this
var data = GetAjaxData();
while(typeof data === undefined);
bind, eval ecc ecc
But this will change if GetAjaxData return something else.
You can try the same thing but before do:
var data = null;
data = GetAjaxData();
while(data == null);
do stuff
You can also try $.ajax jquery with the success handler callback
Hope help
I hope this is not too much of a newbe question but I've been pulling my hair out for a while now so thought I'd give in and ask for my first piece of advice on here.
I'm trying to read an external xml file using javascript / jQuery / ajax and place the retrieved data into an array so that I can then reference it later.
So far I seem to be doing everything right upto the point I put the data into the array but then I'm struggling to to read the data anywhere other than inside the function where I create it. Why am I not able to access the Array from anywhere other than in that function?
Here is my code...
Please help!!
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser
});
function do_xmlParser(xml)
{
var myArray = new Array();
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
console.log("inside "+myArray); // This outputs the array I am expecting
return myArray; // is this right???
}
console.log("outside: "+myArray); // This does NOT output the array but instead I get "myArray is not defined"
You're defining do_xmlParser as a callback to an asynchronous function (success of the jquery ajax call). Anything you want to happen after the ajax call succeeds has to occur within that callback function, or you have to chain functions from the success callback.
The way you have it now, the actual execution of code will go:
ajax -> file being requested -> console.log ->
file transfer done -> success handler
If you're doing some critical stuff and you want the call be to synchronous, you can supply the
async : false
setting to the ajax call. Then, you should be able to do something like this:
var myArray = [],
do_xmlParser = function (xml)
{
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
};
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser,
async: false
});
console.log("outside: " + myArray);
The async option doesn't work for cross-domain requests, though.
NOTE
I don't recommend doing this. AJAX calls are supposed to be asynchronous, and I always use the success callback to perform all of the processing on the returned data.
Edit:
Also, if you're into reading... I'd recommend jQuery Pocket Reference and JavaScript: The Definitive Guide (both by David Flanagan).
look close and you will see. You are actually firing up an array that dosen't exist. You have declared myArray inside function. Try do something like this.
console.lod("outside :"+do_xmlParser(xml)); // I think that when you merge a string and an array it will output only string, but I can be wrong.