Accessing JSONP data outside of ajax call in jQuery - javascript

Now that every google link in the first 5 pages of results is :visited in my browser, I needed to ask...
How can I get the JSON data working so that I can access it/manipulate it in other methods?
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
// works here
console.log(data);
// works here as well & fires local function
testing(data);
// doesnt store
var testvar_1 = data;
}
});
// undefined
console.log(testvar_1);
function testing(data) {
// logs when called from above
console.log(data);
// doesnt store
var testvar_2 = data;
}
// undefined
console.log(testvar_2);
// havent found this yet...
return magicVariableThatLetsMeAccessJSON
}, ...
any ideas? i know theres a lot of other similar questions on stack overflow, but i have found nothing that solves this.
thanks
UPDATE
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
// logs correctly
console.log(storage);
}
});
}
}
//undefined
console.log(storage);
yourobj._requestText();
//undefined
console.log(storage);

Firstly as noted elsewhere, you need a variable that's in scope, secondly you need to make sure it's not evaluated before the callback is called.
The only way to ensure that is to make the call to _otherMethod inside the success call back method
_otherMethod: function(text) {
//...do what ever you need to do with text
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
_otherMethod(data);
},
}
});
}
callbacks are asyncronous meaning they are called at some point in time that's not determined by the sequence of code lines.
If you know the code using the returned data is never going to be call before the success call back has executed and you need to hold on to the data you can change the code to
_otherMethod: null, //not strictly needed
_requestText: function() {
self = this;
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
self._otherMethod = function(data){
return function(){
//do what you need to with data. Data will be stored
//every execution of _otherMethod will use the same data
console.log(data);
}
}
},
}
});
}

Very simple. You need a storage variable outside of the context of the callback function.
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
}
});
}
}
Alternatively, storage can be a property on the same object.

By adding var before your variable name, you create a local variable in the current scope.
This doesn't work:
var a = 2;
(function() {
var a = 3;
})();
console.log(a); // 2
While this does:
var a = 2;
(function() {
a = 3;
})();
console.log(a); // 3
Since the variable that you're trying to set is in an outer scope, get rid of var when working with it in an inner scope.

might be this way:
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
var testvar_1;
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
console.log(data);
testing(data);
testvar_1 = data;
}
});
// should work here
console.log(testvar_1);
Actually you were creating a new instance of that var there.

Related

Declaring global variable not working (returning undefined)

I have this basic set up and the problem I have is the variable locations_map in my function load_heat2. I indicated below where I'm getting the undefined:
//declare global variables
var full_map;
var locations_map;
function callIndex() {
$(document).ready(function() {
//call some functions
load_map();
load_test_map2();
super_test_map();
load_heat2();
});
$.ajax({
url: 'php/get_map_tables.php',
type: 'POST',
dataType: 'JSON',
data: {
client_id: client_id, //defined elsewhere
},
success: function(data) { //this gives me the correct data in the right variables
var locations_map = data[0].locations_map;
var full_map = data[0].full_map;
}
});
function load_heat2(){
console.log(locations_map); //this yields undefined
}
} //end of callIndex function
I'm trying to avoid wrapping everything in my AJAX/success function, so I need the global variable to work.
Thanks.
You're declaring a local variable called locations_map in your success statement
$.ajax({
url: 'php/get_map_tables.php',
type: 'POST',
dataType: 'JSON',
data: {
client_id: client_id, //defined elsewhere
},
success: function(data) { //this gives me the correct data in the right variables
**var** locations_map = data[0].locations_map;
var full_map = data[0].full_map;
}
You are re-declaring the two variables in the ajax function.
var full_map;
var locations_map;
This is declaring them as global but when you set them here
success: function(data) { //this gives me the correct data in the right variables
var locations_map = data[0].locations_map;
var full_map = data[0].full_map;
}
It becomes local. In order for them to remain global you need to remove the
var
so it would look like
success: function(data) { //this gives me the correct data in the right variables
locations_map = data[0].locations_map;
full_map = data[0].full_map;
}
Call the load_heat2() function after you have the response of the ajax request. Also, remove the "var" of both variables like the other answers are pointing.
//declare global variables
var full_map;
var locations_map;
function load_heat2(){
console.log(locations_map); //this yields undefined
}
function callIndex() {
$(document).ready(function() {
//call some functions
load_map();
load_test_map2();
super_test_map();
});
$.ajax({
url: 'php/get_map_tables.php',
type: 'POST',
dataType: 'JSON',
data: {
client_id: client_id, //defined elsewhere
},
success: function(data) { //this gives me the correct data in the right variables
locations_map = data[0].locations_map;
full_map = data[0].full_map;
load_heat2();
}
});
} //end of callIndex function

Javascript, create a global variable with window[]

So, i'm in an ajax request, in the success callback :
var just_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {search:tw_search, type:'tw_search'},
success: function (html) {
window[just_id] = $(this).attr('tw_username');
}
});
With this code, after i call with ajax my script, i need to create a variable with the name of a specific element.
So, if i'm on a <div id="test"></div>, in var just_id i have test and then, i create a variable test with window[just_id].
But i need to retrieve this variable in an other function on my page.. How can i do that ? I need to create a global variable with windows[]... Thanks !
Use window to declare global variable:
window.globalVar[];// i have not give window as varible name this may cause error it must be reserved
var just_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {search:tw_search, type:'tw_search'},
success: function (html) {
globalVar[just_id] = $(this).attr('tw_username');
}
});
NB! First of all, if you are using this in success callback in ajax, this would have different context, not what you are expecting.
Answer: you can define some variable in top of function declaration
var just_id = $(this).attr('id'),
attrUsername;
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {
search: tw_search,
type: 'tw_search'
},
success: function (html) {
attrUsername = $(this).attr('tw_username');
}
});
Then, you can access to this variable. Avoid to use global variable for your purpose
Can't directly assign indexed value to window object. But you can do in this way:
window.x = new Array();
window.x[4] = 'value here';
// And can read from any function like here
;(function(){
alert(window.x[4]);
})();
For your script above:
window.global = new Array();
window.global[just_id] = $(this).attr('id');
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {search:tw_search, type:'tw_search'},
success: function (html) {
window.global[just_id] = $(this).attr('tw_username');
}
});

return ajax.done data gives error on jquery

I have data in my ajax.done and it bugs on jquery.
i googled on it and cant find anything.
what to do?
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
});
return postsjson;
}
You shouldn't be attempting to return anything from a callback function because the returned value doesn't go anywhere meaningful. Instead you simply use the response from the AJAX request inside that callback function.
Let's say you have this code:
function bar() {
var myObject = foo();
// do something with myObject
}
function foo() {
var bar; // 1
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 2
xhr.done(function(yourObject) {
bar = yourObject; // 5
}); // 3
return bar; // 4
}
bar();
The comments inside the foo function indicate the order in which those statements execute. So you declare a variable bar, declare a variable xhr that has a Deferred object, attach a done handler to it with a callback function, return the value of bar, then the value of bar is set (too late - you've already tried to return it).
Inside of your execution of the bar function myObject is going to be undefined, because the value of bar inside the foo function wasn't set before the return statement. What you need to do is simply move the // do something with myObject code to the callback function, and use bar there:
function foo() {
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 1
xhr.done(function(yourObject) {
var bar = yourObject; // 4
// do something with bar
}); // 2
// 3 - function execution has finished
}
You might want to move the return line inside the done section
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
return postsjson;
});
but keep in mind that, being an asynchonous call, so will be your return. My advise would be to pass in a callback.
function select_aragement(arragament, callback){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
test.done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
callback && callback(postjson);
});
}
And modify your code to use the callback instead of the returned value.
before
var postjson=select_aragement(arragament);
...stuff with postjson...
after
select_aragement(arragament, function(postjson) {
...stuff with postjson...
});
You are trying to make the ajax call fire synchronously, for that you need to make the async property false.
async: false,
The problem :
Look at the following code :
function getValue(){
var value = 0;
setTimeout(function(){
value = 42;
}, 1000);
return value;
}
What is the returned value ?
fiddle
This is your exact same problem with
function select_aragement(arragament){
var postjson;
$.ajax(...).done(function(vis){
postjson = vis;
});
return postjson;
}
A solution :
I imagine you use your function in the following way :
var data = select_aragement(arragament);
// do something with data :
$.each(data, function(){
....
});
You can change select_aragement's code like this :
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var test = $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
// return the promise which wraps the ajax call
return test;
}
and the calling code like this :
// "p" stands for "promise"
var p = function select_aragement(arragament);
p.done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
or without the local variable :
select_aragement(arragament).done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
In this case you can use async/await mixed to .done from jQuery like this:
async function myasyncfunction(myArgs){
var response = [];
var req = $.ajax({
method: "GET",
url: resquestURL,
dataType: "json",
})
await req.done( res => {
//DO some stuff with your data
for (let index = 0; index < res.length; index++) {
const element = res[index];
response .push( "some stuff" + element );
}
})
return response;
}

Issue with code inner variable

I have a code like the one stated below, please how do I get the value for (getData), using a code like:
var instanceArray = myGraph.getInstances(component)
I was thinking myGraph.getInstances(component).getData will do it, but it failed
this.getInstances = function(component) {
var getData = {};
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: true,
success: function(data) {
getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
}
});
};`
You can't, the get is asynchronous. getInstances returns before the GET completes, so it's impossible for getInstances to return the data. (See further note below.)
You have (at least) three options:
Use a callback
Return a blank object that will get populated later, and have the code that needs it poll it periodically
Use a synchronous get (not a good idea)
1. Use a callback
What you can do instead is accept a callback, and then call it when the data arrives:
this.getInstances = function(component, callback) {
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: true,
success: function(data) {
var getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
callback(getData);
}
});
};
And call it like this:
myGraph.getInstances(component, function(data) {
// Use the data here
});
2. Return a blank object that will get populated later
Alternately, you can return an object which will be blank to start with, but which you'll add the data to as a property later. This may be closest to what you were looking for, from your comments below. Basically, there's no way to access a function's local variables from outside the function, but you can return an object and then add a property to it later.
this.getInstances = function(component) {
var obj = {};
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: false, // <==== Note the change
success: function(data) {
var getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
// Make the data available on the object
obj.getData = getData;
}
});
return obj; // Will be empty when we return it
};
And call it like this:
var obj = myGraph.getInstances(component);
// ...later...
if (obj.getData) {
// We have the data, use it
}
else {
// We still don't have the data
}
3. Use a synchronous get
I do not recommend this, but you could make the call synchronous. Note that synchronous ajax requests will go away in a future version of jQuery. But just for completeness:
this.getInstances = function(component) {
var getData;
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: false, // <==== Note the change
success: function(data) {
var getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
}
});
return getData;
};
And call it like this:
var getData = myGraph.getInstances(component);
But again, I don't advocate that. Synchronous ajax calls lock up the UI of the browser, leading to a bad user experience.

jQuery ajax return value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
How can I return the value "pinNumber" from jquery ajax so I can append it outside of the ajax. Here is my code
var x = pinLast + 1;
for(i=x;i<=pinMany;i++) {
var i = x++;
var cardNumber = i.toPrecision(8).split('.').reverse().join('');
var pinNumber = '';
jQuery.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false,
success: function(msg){
var pinNumber = msg;
return pinNumber;
//pin number should return
}
});
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+'');
// the variable pinNumber should be able to go here
}
Please ask me if you don't understand.. ^^ thanks
AJAX is asynchronous by default, you cannot return a value from the callback without making a synchronous call, which you almost certainly don't want to do.
You should supply a real callback function to the success: handler, and put your program logic there.
var pinNumber = $.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false
}).responseText;
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+' ');
It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.
Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.
var _successEvent = function(response){
$('.pin_generated_table').append(cardNumber + ' = ' + response);
};
$.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator"
}).done(_successEvent);
You can use this example:
window.variable = 'some data';
This make you variable global and you can access to this from anywhere
Here is the simple solution.
//---------------------------Ajax class ------------------------------//
function AjaxUtil()
{
this.postAjax = function(Data,url,callback)
{
$.ajax({
url: url,
async: true, //must be syncronous request! or not return ajax results
type: 'POST',
data: Data,
dataType: 'json',
success: function(json)
{
callback(json);
}
});
}//--end postAjax
}
//--------------------------------End class--------------------//
var ajaxutil = new AjaxUtil();
function callback(response)
{
alert(response); //response data from ajax call
}
var data={};
data.yourdata = 'anydata';
var url = 'data.php';
ajaxutil.postAJax(data,url,callback);

Categories

Resources