Javascript, create a global variable with window[] - javascript

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

Related

Calling Nested Function In Javascript - Is Not Defined Error When Called Within jQuery.ajax.success

I am making an ajax form submission inside an object.
When I try call the other object methods within the jQuery.ajax.success callback, this line throws an error...
Is this a scoping issue?
this.DisplayError(data.error);
this.DisplayError is not a function
Code:
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: function(data) {
if(data.success === false) {
this.DisplayError(data.error);
}
console.log(data); // show response from the php script.
}
});
}
}
Use arrow function:
success: () => {
}
This happens because you are loosing context, Ajax assigns different context when calling success function. You can also save context in New variable:
var self = this;
And use it inside success function instead of this.
Or you can define function context:
success: (function() {
}).bind(this)
this inside the success function is not equal to this outside. The simplest way to handle this is using arrow function.
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: data => {
if(data.success === false) {
this.DisplayError(data.error); // now `this` should be equal to the one outside
}
console.log(data); // show response from the php script.
}
});
}
}
The magic is, arrow function does not has its own this. When you call this, it will refer to the outside one. But normal function has its own this, therefore when you call this, it will refer to its own this instead of the outside one.
For details, you may take a look on the MDN web docs

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

Assigning JSON value to a Variable that Resides Outside JavaScript Function

I have a question regarding JSON Web Services and AJAX Function. I have declared a JavaScript Function below.
function setJsonSer(){
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
alert("This is Set JSON In "+JSON.stringify(data));
}
});
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
data: formData,
complete: function(data) {
alert("This is Get JSON Out "+JSON.stringify(data));
}
});
}
As you can see I have alert the JSON.stingify(data) statement and it gave me the result as I expected.
Now I want to get that JSON response out of that particular function SetJsonSer() to assign to avariable that resides out side the SetJsonSer() function.
I already tried return JSON.stringify(data)) and JSON.stringify(data) statements but they did not put the result out from the SetJsonSer() function.
The output must grab from a variable like the below.
function Load(){
//-----------------------------------------------
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
This variable will be used as the query to draw a chart using HighCharts. So could you someone give me a clue how to get the result of the SetJsonSer() function?
Thanks and regards,
Chiranthaka
You're getting a bit mixed up with asynchronous nature of AJAX.
The AJAX event is being fired, but it won't be causing any pause in the execution of your code, as such, you need to implement a callback.
This code isn't particularly nice, but it should give you an idea of how the data needs to be handled.
function setJSONSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
console.log("Successfullly set JSON!");
getJSONSer();
}
});
}
function getJSONSer()
{
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
complete: function(data) {
//alert("This is Get JSON Out "+JSON.stringify(data));#
Load(data);
}
});
}
function BeginLoad()
{
setJSONSer();
}
function Load(data)
{
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
}
BeginLoad();

Accessing JSONP data outside of ajax call in jQuery

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.

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