Pass a javascript function through JQuery $.post - javascript

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

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!

Not able to send dynamic javascript parameters when changing onclick function through javascript call

Sample Code:
<img id="image" onclick="addDetails('1','2','3');" src="sample.png"/>
<script>
function addDetails(data1,data2,data3)
{
$.ajax(
{
.....
.....,
success: function()
{
document.getElementById("image").onclick=function onclick(event){deleteDetails('data1','data2','data3');};
}
});
}
</script>
In the above sample code i am making an ajax call on click of image and after successchanging the
onclick function to deleteDetails. Both the functions addDetails and deleteDetails have same value as their parameter. so in the onclick function am trying to set the deleteDetails with the same parameters as of the called method.
The problem here is when i debugged it the actual function which binded with the onclick function is
deleteDetails('data1','data2','data3') insted of deleteDetails('1','2','3') . I tried all the possible string operators to print the value but its not happening.
Your arguments are variables, not "Strings" (only strings are wrapped in quotes)
document.getElementById("image").onclick = deleteDetails(data1, data2, data3);

need to call onDataReturnInitializeTable in custom callback

I need to call onDataReturnInitializeTable yui datatable method from custom call back function.
Normally I would use on success of sendRequest method like this:
success: onDataReturnInitializeTable,
but now I need to do something else after that. I tried to do this
success: function(e) {
dataTable.onDataReturnInitializeTable;
//do my code here
},
but that won't work cause onDataReturnInitializeTable is a function and needs to be called in correct context
Please help.
success: function(e) {
dataTable.onDataReturnInitializeTable.apply(this, arguments);
//do my code here
},
This is a generic JavaScript trick, it is not limited to DataTable.

Call external function from ajax() success function

I have a function defined within $(document).ready() which arranges some JSON into HTML using DoT.js:
$(document).ready(function() {
function arrangeResults(jsonObject, templateFunc) {
$(jsonObject).each(function(i, item) {
$.each(item, function(i2, item2) {
$('#ajax-article-list .col-left').append( templateFunc(item2) );
});
});
};
I have an AJAX call on page load which executes this function to display the data:
$.post(ajaxRequestURL, function(data) {
arrangeResults(ajaxData.pages, projectTemplate);
}
and this works fine.
However I have a set of links which requests more/different JSON data using the click() handler, which should execute arrangeResults again with the returned data, but the function isn't executed:
$('nav.filters a').click(function(ev) {
ev.preventDefault();
$.post(ajaxRequestURL, function(data) {
ajaxData = parseJSON(data);
arrangeResults(ajaxData.pages, projectTemplate);
}
}
This doesn't work. The data is all valid, and everything works if I take the contents of arrangeResults and put them directly within the script, but I was hoping to follow DRY and have an external function that I could call upon both on pageload and when one of the filters is clicked.
I guess it's because the AJAX call is asynchronous but since the function call is within success I presumed this wouldn't cause a problem.
If I understand it right, you have first AJAX call inside $(document).ready() block.
So it could be because you have arrangeResults function inside your $(document).ready() block. Because of that you are unable to call the function from other part of JScript.
Define it like that:
function arrangeResults(jsonObject, templateFunc) {
...
}
$(document).ready(function() {
...
);
and so on.
Correct me if I wrong, please.

Execute dynamic function with param in 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.

Categories

Resources