Parameter as function name - javascript

I am not sure if this is possible. I would like to pass in a function name as parameter like this
loadContent("http://test.com/", specialFunction);
specialFucntion is just a string :
function loadContent(href, functionIWant){
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
functionIWant + "()"; //So this would be treated as function
//and it actually calls specialFunction()
//is it possible for this?
}
});
}
How do I achieve this?
ADD-ON
Let's say, I would pass in an array of function names, how do I call it?
for(var i = 0; i < functionIWant.length; i++){
functionIWant[i]; // how? appeciate a lot :)
}

You can just do it with functionIWant()
Example using your provided snippet:
function loadContent(href, functionIWant)
{
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
functionIWant();
}
});
}
For your addendum
Assuming the following three functions you want to call
function foo() {alert("Foo")}
function bar() {alert("bar")}
function baz() {alert("baz")}
The best I can recommend if you're passed an array of function names as strings is to follow the advice here. Basically, you could just do it like this:
// Assuming FunctionIWant is an array of strings that represent function names
FunctionIWant = ["foo","bar","baz"];
...
for(var i=0;i<FunctionIWant.length;i++)
window[FunctionIWant[i]]();
If, however, FunctionIWant is an array of actual functions, for example, you can simply iterate over them and call them individually like so:
FunctionIWant = [foo,bar,baz] // note, these are not strings
for(var i=0;i<FunctionIWant.length;i++)
FunctionIWant[i]();
In most cases, you'll be better off assigning the function rather than as a string

If you want to try to call the function represented by a parameter, simply call it as if that were the name of the function:
function loadContent(href, callback)
{
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
callback();
}
});
}

I am guessing that functionIWant is a string, not a reference to a function [You should make that clear when asking the question]
If that is the case, you want
window[functionIWant]();
That will work if the function is in the global scope. It would be better that you pass in the reference to the function or if you namespaced your functions.
var myFuncs = {
foo : function(){ alert("asdf"); },
bar : function(){ alert("qwerty"); }
};
var functionIWant = "foo";
myFuncs[functionIWant]();

for example you have two functions,
var function1 = function( value ) {
console.log( "foo: " + value );
};
var function2 = function( value ){
console.log( "bar: " + value );
};
and in functionIWant array you have name of function,
function loadContent(href, functionIWant)
{
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
var callbacks = $.Callbacks();
for(var i = 0; i < functionIWant.length; i++){
callbacks.add( functionIWant[i] ); //on i=0 add function1
callbacks.fire( "hello" ); // will fire function1
}
}
});
}

Related

why am I getting undefined at the moment when I click my button?

I want to try to display my notification json through ajax, but however when I try first show me undefined, and then show me my json what am I doing wrong?
$(function (doc, win, $) {
var notification = win.Notification || win.mozNotification || win.webkitNotification;
var $badge = $("#notifications-badge");
var $list = $("#notifications-list");
var $button = $("#notifications-button");
URL_GET_NOTIFICATION = BASE_URL + 'notifications/getNotification';
function check_notifications() {
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
}
});
}
$button.click(function (e) {
alert(check_notifications());
});
}(document, window, jQuery));
All functions return undefined by default when called, unless something else is specified.
You'd get the same with just
function go() {};
alert( go() ); // undefined
And that's basically what you're doing, alerting a function that doesn't return anything.
If you return something from the function, it works
function go() { return 'Hello Kitty' };
alert( go() ); // Hello Kitty
But, as you're using ajax inside the function, you can't really return the result from that, as it's asynchronous and executes some time after the result is returned.
You'd have to use a callback or promise to make it work.
function check_notifications() {
return $.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json'
});
}
$button.click(function (e) {
check_notifications().done(function(data) {
alert(data);
});
});
As a sidenote, use the console when debugging, not alerts.

adding JSON length

I have a function that is called multiple times which uses jquery to fetch different JSON from an API.
I have been trying to get a cumulative count of part of that JSON. Here is sort of what I have:
getTheData(aBlah,bBlah,cBlah);
getTheData(aStuff,bStuff,cStuff);
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
console.log(data.subdata.length);
'the rest of the code'
});
}
I am trying to get a cumulative total of data.subdata.length but I'm not sure how to go about getting it.
This is a classic use case for closures:
var closure = function(){
var counter = 0;
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
counter += data.subdata.length;
'the rest of the code'
});
}
function getcount(){
return counter;
}
return {
getTheData:getTheData,
getcount:getcount
}
};
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
This helps control the scope of the counter variable. So you can do things like:
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
//counter in the new closure is zero
var newClosure = closure();
newClosure.getTheData(aBlah,bBlah,cBlah);
newClosure.getTheData(aStuff,bStuff,cStuff);
var totallyNewCount = myClosure.getcount();

Javascript global variables used as flags

I am trying to use global variables as flags and cant get it to work. I have two functions:
This function sets a flag to be false when it is done.
function buildYearsTable(btn) {
//console.log ("At build years table")
var fundCode = document.getElementById("fundCode").value
buildYearsFlag = true;
$.ajax({url: "/scholarship/scholarshipMaintenance/buildYearsTable", method: "POST",
cache: false, data: {fundCode: fundCode},
complete: function(xhr, statusCode){
console.log("inside build years table")
data = $.parseJSON(xhr.responseText)
$('#myTable tbody').html('');
data = data.sort()
data = data.reverse()
for(var i = data.length - 1; i >= 0; i--) {
moveYearOption(data[i])
addYearRow(data[i])
}
buildYearsFlag = false;
//$('#yearsTable').html(xhr.responseText)
console.log("done in build years table")
}})
}
This function is called when the first one is called, but i need it to perform its ajax call ONLY once the flag is set to false by the first function. I am not sure how to accomplish this. I was thinking a while loop (polling kind of idea) but not sure how to go about it.
function rebuildYearSelects(btn) {
//console.log ("At rebuild selects")
var fundCode = document.getElementById("fundCode").value
while (buildYearsFlag == false) {
$.ajax({url: "/scholarship/scholarshipMaintenance/rebuildYearSelects", method: "POST",
cache: false, data: {fundCode: fundCode},
complete: function(xhr, statusCode){
console.log("got inside rebuild years select")
data = $.parseJSON(xhr.responseText)
selectedYears = data.sortedSelectedYears
unselectedYears = data.sortedUnselectedYears
$('#yearsModal').replaceWith(data.html)
fixModals();
buildYearsFlag = true;
console.log("done in rebuildYearSelects")
}})
}
}
The best way to accomplish this is by using callbacks.
You just need to call the second function after the response from the first.
You should use 'done' instead of 'complete'.
function buildYearsTable(btn) {
var fundCode = document.getElementById("fundCode").value
$.ajax({url: "/scholarship/scholarshipMaintenance/buildYearsTable", method: "POST",
cache: false, data: {fundCode: fundCode},
done: function( data ){
// Your code goes here
// Call the function only after the response
rebuildYearSelects();
}})
}
Html:
onclick="buildYearsTable();"
Remove the flags and the while loop, everything should work.

jquery function access local javascript variable

New to jQuery and having simple yet confusing problem. ha2.
I am writing this normal javascript function with jQuery function reading xml file. How do I assigned value to the prodPrice variable declared on the top? the script keep returning 0 value, but if I alert the value within the jQuery function, I managed to get the value that I wanted.
Thank you guys.
function getPrice(valprodID)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
return false;
}
});
}
})
return prodPrice;
}
That's because $.ajax is performed asynchronously.
And it is a great chance for you to learn how to work with $.Deferred
function getPrice(valprodID)
{
var prodPrice=0;
return jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml"
}).pipe(function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
return jQuery(this).find('prodPrice').text();
}
});
});
}
Now you call your getPrice() function in this way:
getPrice(someid).done(function(prodPrice) {
// do what you need with prodPrice
});
Here is an example on jsfiddle: http://jsfiddle.net/zerkms/9MgsX/1/
you can do asynchronous as reported by #xdazz, as #zerkms indicated with Deferred, or anonymous functions:
function getPrice(valprodID, fn)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
fn(prodPrice);
}
});
}
})
}
getPrice(1, function(prodPrice) {
/* your code */
})
You need to set the async option to false, or you should do your work in the callback function.

How to create jquery ajax as separate function?

I want to create a separate function to get specific data from Facebook graph JSON.
For example, I have the load() and called getNextFeed() function.
The getNextFeed works correctly. Except that returning value of aString is not successful.
When I pop alert(thisUrl). It said undefined.
Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
var thisUrl = getNextFeed(url);
alert(thisUrl); // return undefined
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
return aString;
}
});
}
The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.
You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.
Example:
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
getNextFeed(url);
alert('Please wait, loading...');
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
do_something_with(aString);
}
});
}

Categories