Unable to change global variable from local function - javascript

I'm trying to have a jQuery.getJSON() call change a global variable with the JSON array it returns:
var photo_info ;
//Advance to the next image
function changeImage(direction) {
jQuery('img#preview_image').fadeOut('fast');
jQuery('#photo_main').css('width','740px');
if (direction == 'next') {
jQuery.getJSON('/ajaxupdate?view&sort='+sort+'&a='+a+'&s=' + title_url_next, function(data) {
photo_info = data;
title_url = photo_info.title_url;
title_url_next = photo_info.preview_title_url_next;
title_url_previous = photo_info.preview_title_url_previous;
});
} else if (direction == 'prev') {
jQuery.getJSON('/ajaxupdate?view&sort='+sort+'&a='+a+'&s=' + title_url_previous, function(data) {
photo_info = data;
title_url = photo_info.title_url;
title_url_next = photo_info.preview_title_url_next;
title_url_previous = photo_info.preview_title_url_previous;
});
}
}
However, the variable photo_info is only accessible from within the getJSON() function and returns undefined from anywhere else in the script.
What am I doing wrong?

as Randal said Ajax call is asynchronous. Use the ajaxComplete function or replace the getJSON function with an .ajax call and use the photo_info var whithin the success function e.g.:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(photo_info);
}
});

If you're looking at photoinfo in the rest of the script right after changeImage has returned, then of course it won't have a value, because the Ajax call is asynchronous. You need to rethink your application to be more event driven.

JavaScript scoping isn't quite like standard scoping. It looks like you're actually losing your scope because of nested functions. Try giving this article a read:
http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/

Related

How to create global variable in query and usable with javascript

$(document).ready(function ()
{
$.ajax(
{
url: "Bibliotheek.xml",
dataType: "xml",
success: function (data)
{
var song = $(data).find('key').filter(function ()
{
return $(this).text().indexOf('Name') != -1;
}).each(function()
{
window['globalVar']= $(this).next('string').text();
console.log(globalVar);
});
}
});
});
I want to use globalVar outside that each loop. But once i put de console.log outside the function. It tells my globalVar is undefined.Is it also possible to use that variable later on in javascript code?
This probably happens, because you loop over an empty list (i.e. it never enters the .each callback). This thing is wrong: .find('key'). It searches for a key tag (which is not HTML, unless you actually are not dealing with HTML?). Perhaps you were looking for .find('.key')?
EDIT: It seems that you want to put console.log outside of ajax call. If you do, then you're out of luck, since you are trying to log a variable that does not exist yet. That's because a in ajax stands for asynchronous, i.e. the piece of code will run later.
EDIT 2: Welcome to asynchronous programming! It seems that you are trying to force ajax to be synchronous, which is wrong and pure eveil. Don't do it. You're code should be similar to this:
var my_fn = function(clb) { // <-- this is callback to be called later
var els = [];
$.ajax({
url: "Bibliotheek.xml",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var el = $(this).next('string').text();
els.push(el);
});
clb(els); // <-- call it now
}
});
};
$(document).ready(function() {
my_fn(function(els) {
console.log(els);
// do coding here
});
});
Define the globalVar outside of the functions...
var globalVar;
var song = {...
console.log(globalVar);//will work here
};
console.log(globalVar);//and, will work here

how to pass function in json as a function?

in arrayRec , onShow value should be a function.
Following is my reference code.
Any help?
This is my reference code:
if (rec.element_flag == '111'){
var arrayRec = [];
$.ajax({
type:'GET',
url: "/aps/one-url",
success: function(responseData){
for (var i = 0; i < responseData.length; i++){
var recJ;
var newFunction1 = function onshowdata(counter){
if(responseData[counter].fields.on_show_fn != null){
return function responseData[counter].fields.on_show_fn;
}
else
return;
}
recJ = {
element: responseData[i].fields.element_class,
placement: responseData[i].fields.placement,
title: responseData[i].fields.title,
content: responseData[i].fields.content,
onShow: newFunction1(i)
}
arrayRec.push(recJ);
console.log('-------arrayRec------');
console.log(arrayRec)
aps.walk.setupBootstrap(arrayRec);
}
},
error: function(){
alert('get failure');
}
});
}
Tried many ways but what I am missing?
in JSON, only text can be used, not objects. Functions are objects too. So, in JSON, name of the function can be passed, not the function object. An alternate way is to send the text of that entire function, which can be run using "eval", though this way is not recommended.
Use closure technique here. Define function above the ajax code, and use the name of the function inside it, which is a standard method of doing this.

How to invoke function call if it is defined as var?

I'm getting data from server using JQuery and JSON. I defined getBooksDoneFunc
as variable because I need to be able to call this function not only once (when getBooks is done) . Unfortunately, I cannot call getBooksDoneFunc from inside of signInOK as window["getBooksDoneFunc"]();. Why? What is the best way to call this function?
function getBooks(){ return $.getJSON( "bookstore.json" ); }
var getBooksDoneFunc = function(json) {
$.each(json.books, function(i, json){ .......... });
}
getBooks().done(getBooksDoneFunc);
function signInOK(){
window["getBooksDoneFunc"]();
}
PS. The idea for window["getBooksDoneFunc"](); was taken from SO answer
UPDATE:
var booksJSON = {};
window["getBooksDoneFunc"](booksJSON);
getBooksDoneFunc must be called with parameters nevertheless the call to getBooksDoneFunc fails. signInOK is defined outside of $(document).ready(function(){ }); but called inside of it.
Try:
function getBooks(){
return $.getJSON( "bookstore.json" );
}
window.getBooksDoneFunc = function(json) {
$.each(json.books, function(i, json){ .......... });
}
getBooks().done(getBooksDoneFunc);
$(document)ready(function() {
function signInOK(){
var booksJSON = {};
window.getBooksDoneFunc(booksJSON);
}
});
If window["getBooksDoneFunc"](); works, then does getBooksDoneFunc(), the idea of using window is when you want to access a global function but you don't know the function name which is stored in a variable.
In your case, put a hardcoding string is mean less, just do getBooksDoneFunc() is the same, because you already store the function self (not the string of function name) in the variable.
The thing that won't work is that if the variable is not global, please check the scope.
I would do this a bit differently, although I do not really understand the signInOK() function. How will it receive the "json" data. I would reconstruct the getBooks function and rethink the signInOk function. Here's a start:
function getBooks() {
$.getJSON("bookstore.json").done(function (json) {
getBooksDoneFunc(json);
});
}
var getBooksDoneFunc = function(json) {
$.each(json.books, function(i, json){ .......... });
};
...
getBooks();
function signInOK(){
getBooksDoneFunc("some json data");
}

Using variable in a ajax function

I just want to use a variable from outside of the function, but I am not sure what I have to do for that...
Is var myRequest = a; line enough to use this variable in the function?
Because I saw such an example: var myRequest = e.which;
I am asking this because I did not get a succesful result for my request.
I am think that it is not working as I expected because ajaxFunction(3) working diffirent than writing send.php?goto=3 into address bar of my browser.
You can see the following codes:
function ajaxFunction(a)
{
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.open("GET", "send.php?goto=" + a, true);
ajaxRequest.send();
}
If you want to use a variable outside a function you have to use a global scope variable, example (using jQuery ajax)
var globalA = null;
$(document).ready(function(){
var localA1 = null;
$.ajax({
"url":"http://someurl.com/",
"type":"POST",
"dataType":"json",
"success":function(incomingData){
var localA2 = incomingData //localA2 only useable inside this function
localA1 = incomingData; //localA1 being set here still can only be used here as code within the "ready" function has already been executed and will see it as null
globalA = incomingData; //Now any further code should use globalA as it now contains useable data
doSomethingWithData();
},
"error":function(xhr,msg) {
alert("Ajax Error:"+msg);
}
});
alert(localA1); //Will give alertbox with null in it as localA1 has not been set.
});
function doSometingWithData() {
alert(globalA); //You can now use the data in whatever function makes reference to globalA
}
Of course in this example you could have just passed the data straight to doSomethingWithData() and processed it there.
You could take a look at the jQuery $.globalEval for instantiating a variable globally inside of your AJAX success function.
$.ajax({
url: "send.php",
success: function (data) {
$.getScript("somescript.js", function(data) {
$.globalEval("var something = new Whatever;");
});
});
The $.getScript portion is a helpful little snippet if you find you need to load an external JS file in your ajax call, and make its assets globally available. You can then use $.globalEval to instantiate a variable inside of your AJAX function.
Documentation for $.globalEval
Documentation for jQuery AJAX
You don't a function wrapper for setting a value to a variable.
var myRequest = a;
That is good enough.
After thought revision
in a very basic way a variable can be created on its own like a place holder.
var myRequest;
when you get to the function (say you have a series of functions.
You could do something like this.
function(myRequest=a);
if the function has more than one argument it can look like this.
function(myRequest=a,myConcern=b); as you have it stated in the
var arg1 = 1;
var arg2 = 2;
var arg3 = 3;
ajaxRequest.open(arg1,arg2,arg3);
I hope this is helpful and yes, some more info would help (like the poster below stated).

How can I pass this specific variable I'm using jquery-ajax

I want to pass the "passedThisValue" to my "start_battle" function and use the "start_battle" function in my "Rematch". But the modal just hangs why is this happening? what could be wrong? Please help! :) Thank you.
CODE:
function start_battle(){
$.ajax({
data: {
receivePassedValue: passedThisValue
},
success: function(data){
}
});
}
$("#start_battle").click(function() {
$.ajax({
success: function(data){
var toAppend = '';
if(typeof data === "object"){
var passedThisValue = '';
for(var i=0;i<data.length;i++){
passedThisValue = data[i]['thisValue'];
}
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").dialog({
modal:true,
buttons: {
"Rematch": function(){
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").show(500);
});
When you call a function, you don't use function start_battle();, you just use start_battle();.
When you pass a value to a function, you need to use this syntax: start_battle(param1, param2);.
When you want to get a value from a function, you need to return it in the function, like so:
function start_battle(param1) {
// Do something
return param1;
}
When you want to store a returned value from a function, you do something like: var returned = start_battle(param1);
And the fact that you don't know why the modal just hangs, means that you didn't check the browser's error console, which can hold some pretty important information on what's wrong. Try checking that and posting here so we can see the current problem
Your function declaration seems a little off. I think you should leave off the $ from function. Just do this
function start_battle() {
Also, when you're calling a function, you don't say function before it. And if you want to pass a value to the function, you have to put it inside the parenthesis, both when defining the function and when calling it. Like this
function start_battle(someValue) {
// do some stuff with someValue
}
// inside your .click, call start_battle like this
start_battle(passedThisValue);
Pretty basic stuff. But either one of those problems could be causing the hang, which was likely a javascript error.

Categories

Resources