Execute dynamic function with param in javascript - javascript

If the following possible?
I wish to move the alert(result) into a function and to dynamically call it.
Current
$.ajax(this.href, {
success: function (result)
{
alert(result);
AjaxComplete();
}
});
My Attempt - not working
$.ajax(this.href, {
success: function (result)
{
window["MyAlert(result)"]();
AjaxComplete();
}
});
function MyAlert(result)
{
alert(result);
}
Is this possible?

Why can't you just do this?
MyAlert(result);
If MyAlert is a part of the window object, it's already a global.
Unless you want to call an arbitrary function by name (which isn't really good practice, IMO), which you can do like this:
window[function_name_string](argument);

window["MyAlert(result)");
is invalid syntax (missmatching [ and ), wrong function name, and not calling it at all, just getting it..). Should be
window["MyAlert"](result);
if you want to call it like that, but I see no reason why you couldn't just call it normally, as Blender mentioned.

Related

Calling function by string not working

I'm trying to write a js function that triggers another, variable, function when complete. I figured I could do this by passing the second function's name as a string, but I can't get it to work. Here's my code:
logMeIn('likeThisPost');
function logMeIn(callBack) {
//First function content
$.post("/ajaxurl/",
{
login_id: login_id,
intent: 'login'
},
function(){
console.log('Logged in, refreshing header');
$.post("/secondajaxurl/",{},
function(data){
//success
if(typeof callBack!=='undefined') {
window[callBack]();
}
}
);
}
);
});
}
This should, according to my thinking, run likeThisPost after successfully completing both ajax calls in logMeIn, but instead I get this error:
window[callBack] is not a function
The function I'm calling on success definitley exists, and besides which, it doesn't look like it's even trying to call that function, but it's treating callBack as literal rather than a string.
I'm using jQuery and have everything wrapped in a $. Where am I going wrong?
With thanks to Jonas W and Rory McCrossan, the answer was to change the passed function to the function name, rather than a string, and then call the function directly rather than using window.
So logMeIn(likeThisPost) instead of logMeIn("likeThisPost") and callBack(); rather than window[callBack]();.
Thanks!

this.url is not a function

In Nightwatch, I'm trying to write a command for checking the url of the current page.
When I write this directly in the test file, it looks like this:
browser.url(function (result) {
browser.assert.equal(result.value,expectedPageUrl);
});
This works perfectly, returns expected results. However, when I try to move it into the pageObject file and modify it like this:
checkUrl: function (expectedUrl) {
var _this= this;
this.url(function (result) {
_this.assert.equal(result.value,expectedUrl);
});
}
this returns the error
TypeError: this.url is not a function
What am I missing here?
The error you get is most probably because the 'url' is not defined in your second function, within the this object.
One way to solve it would be to try passing in that browser object as a parameter in your checkUrl function. and then to call it:
checkUrl: function (browser, expectedUrl) {
browser.url(function (result) {
_this.assert.equal(result.value,expectedUrl);
});
}

Pass a function reference as callback to my service

I'm trying to refactor my code to avoid DRY and found that I'm doing the same stuff in two callback functions from my $resource. But I haven't managed to pass in a reference to a function instead of the function declaration itself.
I'm trying this:
emailService.getEmails(people, function(data) {
data.foo();
});
But i want something like this:
emailService.getEmails(people, $scope.callback);
$scope.callback = function(data) {
data.foo();
};
I don't seem to get it to work. Can I do this even?
It’s because $scope.callback isn’t defined (yet) when you run the emailService.getEmails function. You can change it to:
emailService.getEmails(people, callback);
function callback(data) {
data.foo();
};

Pass a javascript function through JQuery $.post

Basically what I am trying to do is pass a callback function through PHP using JQuery $.post. Something like:
function loadPage()
{
$.post('myurl.php', { 'callbackfunc' : function (info) { alert(info); } },
function(data) {
$("#divid").html(data);
} );
}
Where myurl.php creates a page with a table. The table rows have an onclick handler that calls the callback function.
The problem is, passing the function this way sends it as undefined via post, and if I enclose it in quotes, then when I try to call it I get the error that it is not a function.
Is there any way to do what I am describing?
there is a way but not normally recommended. You can pass the function as a string and then when you receive the function with javascript use the eval() function.
function loadPage()
{
$.post('myurl.php', { 'callbackfunc' : "function (info) { alert(info); }" },
function(data) {
$("#divid").html(eval(data));
} );
}
pass it as a string (function body in double quotes, probably using escape characters).
You could attach your function to your table rows after the table has been returned, rather than try to have the php code create it with the proper callback.
function loadPage(callbackfunc)
{
$.post('myurl.php', {},
function(data) {
$("#divid").html(data);
$("#divid").find("tr").each($(this).click(callbackfunc));
} );
}
there is no way to do what you are describing, but there is a probably way to do what you want. ( i dont know what you want )
you cant pass a JS function to the server. you can only pass strings.
edit:
based on your response, i can tell you that your way of doing this is not only not good, but dangerous, as it allows XSS.
it would be better to delegate the click function to the div where you are inserting the table like this:
function loadPage(){
$("#divid").delegate('tr', 'click', function(evt){
//this code is different per page, change color, alert, etc
});
//after the above event is delegated, you can reload the table as much as you want, without needing to rebind the above event
$.post('myurl.php', function(data) {
$("#divid").html(data);
});
}

Pass a function as parameter in jQuery?

I would like to pass to a jQuery function a regular function, instead of the usual anonymous function, but I'm not sure how such a thing could be done.
Instead of this:
function setVersion(feature) {
$.post("some.php", { abc:"abc" },
function(data){
// do something here
}, "json");
}
I would like to do this:
function foo(data){
// do something here
}
function setVersion(feature) {
$.post("some.php", { abc:"abc" }, foo, "json");
}
Thank you.
Yeah, already works. But you want it probably look like this:
function setVersion(feature, myFunction) {
$.post("some.php", { abc:"abc" }, myFunction, "json");
}
setVersion(blah, foo);
Should run just fine.
I believe jQuery is actually meant to use the regular function, called by name. Using the anonymous function is simply a replacement for a named function that would otherwise be passed.
Yes, that is exactly how you do it.

Categories

Resources