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!
Related
I have the following code in JS:
if (Subs.Lsr!==null) {
Subs.Measure.Do("markLSRPosts",function() {
Subs.Lsr.Dom($ce);
});
}
Because this kind of code is inside my file multiple times I wanted to create a function for that:
function SingleMeasure(measureTitle, functionName) {
if (setting!==null) {
Subs.Measure.Do(measureTitle,function() {
functionName();
});
}
}
SingleMeasure(Subs.Lsr, "markLSRPosts", Subs.Lsr.Dom($ce));
Now my problem is that the function Subs.Lsr.Dom($ce) is called BEFORE my SingleMeasure()-Function is called (and so always, no matter what the condition of setting is).
I have to admit: This makes sense to me from coding logic. Nonetheless I wonder if there is another way to achieve what I want. (the method ...Dom() only being called when the setting-condition is met)
Now my problem is that the function Subs.Lsr.Dom($ce) is called BEFORE my SingleMeasure()
That's because you are calling it right here: Subs.Lsr.Dom($ce)
SingleMeasure(Subs.Lsr, "markLSRPosts", Subs.Lsr.Dom($ce));
You might pass it as an anonymous function:
SingleMeasure(Subs.Lsr, "markLSRPosts", function() {
Subs.Lsr.Dom($ce);
});
The callback will be invoked by your SingleMeasure function at a later stage.
I'm a javascript noob, and I don't understand why this works:
$().load('/my/url/', {my:data, more:data}, jsFunc());
function jsFunc()
{
$("#myid").val("yep");
}
But not this:
$().load('/my/url/', {my:data, more:data}, function() {jsFunc()});
function jsFunc()
{
$("#myid").val("yep");
}
I tried an $.ajax instead of $.load with the same result. I will be passing the response data to jsFunc() and that is why I need jsFunc() inside the function. I'm sure it is something simple I'm just not very experienced with javascript. Thanks.
Thanks again for all the help. I decided to use $.post because it works best for the situation but now I'm having trouble with the response data. My code looks like this:
$.post('/my/url/', {my:data, more:data}, function(data) {
var strung = JSON.stringify(data)
var parse = jQuery.parseJSON(strung)
console.log(parse.some);}, 'json');
I'm logging to the console to see what is coming back for now and I will add the callback when I see the correct value logged. The process I got from the jQuery api page, but it will only log undefined. When I change parse.some to parse the console log will display the objects and I can select an element and see the correct key:value pair. Any help would be sweet.
Neither works. The first one appears to work, because you call the function jsFunc immediately, it doesn't wait for any response.
If you create an empty jQuery object using $() and use the load method on that, it won't call the server because there is no element where it can put the result.
To specify the callback function you either use the name of a function:
$('#someElement').load('/my/url/', {my:data, more:data}, jsFunc);
or a function expression:
$('#someElement').load('/my/url/', {my:data, more:data}, function() { jsFunc(); });
The first code block will simply call jsFunc() and return the results as the parameter to the load(..) method, which is odd because that parameter is supposed to be a callback function to fire when the load completes, but that works? The callback syntax is more in keeping with the second example (the one I believe you stated doesn't work).
Answer to my second part:
My returned JSON data consisted of many objects, so I had to specify the index and the key to get the value to return.
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.
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);
});
}
I have no idea what's going on here and was hoping someone could help, I'm sure it's something easy going on that I'm just missing.
I have a function in javascript that has a JQuery post inside of it. I would like to return the results of the post which is just text and put it in a variable. The number is coming back correctly from the Post but when I put it in the variable, the variable says "undefined". Any ideas?
var total = GetTotalSize();
alert(total);
function GetTotalSize(){
var i = "";
$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data){
i = data.toString();
return i;
});
}
You can't do it like that. Remember, the "A" in AJAX means "Asynchronous". The callback function you provide to $.post() will execute well after GetTotalSize() executes and returns.
You'll need to restructure your code to accommodate this. I can't be specific in my recommendation because I don't know what the rest of your code looks like, but here's a possibility.
$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data)
{
doSomethingWithTotalSize( data.toString() );
});
function doSomethingWithTotalSize( totalSize )
{
// whatever
}
Peter is absolutely right, but you can force the $.ajax method to work synchronously by passing async: false.
The problem is that you are returning i outside of the callback function. Basically when you return i, its contents don't exist yet, and won't exist until the server returns the data to your callback function.
Try this
function GetTotalSize(callback) {
$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(outputData) {
callback(outputData);
});
}
function DoSomething(data)
{
//....
}
GetTotalSize(DoSomething);
I realize this is an older post, but a solution for me was to use complete:[delegate] rather than success. This ensures that the callback is complete.