how to pass function in json as a function? - javascript

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.

Related

How am I getting the scope wrong? Unable to access this function from jQuery ".on"

Morning all,
I'm using the following code to somewhat imitate setInterval with AJAX:
// Poll for ALERTs
(function pollForAlerts() {
var params = { "send": 1, "poll": 1 };
// Set up the correct patch for sending AJAX data
ALERTS = {};
ALERTS.Auth = { site: data_site, uuid: data_uuid };
ALERTS.API = function(app,data) {
var url = "//myurl.com/alerts/"+ app +"/?";
var data = $.extend({}, ALERTS.Auth, data);
return url + jQuery.param(data || "") + '&timestamp='+$.now();
}
// Run the AJAX request
$.getJSON( ALERTS.API( 'touchscreen', params ) , function (response) {
if( typeof response === "object" ) {
for( var i = 0; i < response.length; i++ )
renderAlert(response[i]);
} else { setTimeout( pollForAlerts, 3000 ); }
});
}());
The function runs repeatedly until it finds a response.
I'd like to then set a jQuery ".on" to restart this loop if a certain element is clicked on:
// Respond to ALERT
$('#alerts').on('click', 'td.initials span', function(event) {
$(this).closest('tr').removeClass("active abs cri");
pollForAlerts();
});
However, when I do that, I get the following error in Firebug:
ReferenceError: pollForAlerts is not defined
http://myurl.com/alerts/static/js/touchscreen.js
Line 14
I can't work out why pollForAlerts() can't be accessed. Is it because of the self-executing function, or is it just because it's being used within jQuery's on function?
I'm not JavaScript expert, especially when it comes to self-executing functions and closures, so please be gentle with me!
Duncan
You wrote self invoking function, These functions are executing only once in lifetime. If you want to call a function multiple times then you can write it as normal function.

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

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.

Unable to change global variable from local function

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/

Categories

Resources