Hi. Trying to use a returnvalue from a function, but for some reason, it doesn't seem to return anything, and I'm a little confused as to why. Function: function getTableLength() { $.post('get_post.php',{ tablelength:'yes'},function(data) { data = $.parseJSON(data); return data.content; }) } Code (markup): and trying to use it here: $("#showallusers_table,#meetings_table").dataTable( { 'iDisplayLength' : getTableLength() }); Code (markup): But it doesn't return anything - if I console.log the returnvalue is, as it's supposed to be, 20. Just wondering if the return doesn't work because of the ajax-call... Any one have insight in how this could be achieved?
The problem is because it's asynchronous. You need to create a call back function from that response. Example: function handleResponse(response) { // do what you want with the response here... } function getTableLength() { $.post('get_post.php',{ tablelength:'yes'},function(data) { data = $.parseJSON(data); handleResponse(data.content); }); } Code (markup):
Ah, yes, of course. Completely forgot about that However, making a simple return value function to provide the callback doesn't seem to work - I'm guessing that might be because I'm trying to use the return value as a value for a setting in another function... Any tips as to how to get this working? Alert works, console.log works, but assigning a simple "return response" in the callback function does not work, and I'm wondering how I'm gonna get the value. Current code (not working): function displayTableLength(content) { return content; } function getTableLength() { $.post('get_post.php',{ tablelength:'yes'},function(data) { data = $.parseJSON(data); displayTableLength(data.content); }) } Code (markup):
Because you are doing an ajax request, you CANNOT retrieve data with it in that manner. When you call .post as mentioned it's aSync, but what that really means is the request is sent, then execution continues... since execution continues there is NO WAY for your wrapping function getTableLength() to EVER, EVER be able to return the value it's requesting. This is made even worse by that scripting handlers, even event ones, WILL NOT execute while another script is running; meaning that you can't simply make your 'getTableLength' function loop until the request is complete either. By the very nature of how javascript works your getTableLength function MUST end before the handler you are passing to $.post is ever even allowed to run! Whatever you want to do with the length HAS to be done in the handler function, NOT by what's calling $.post (and by extension getTableLength) -- JS, even with the idiocy known as jQuery on it, just doesn't work that way. Though if all you're getting is a length (integer) I wonder why you'd waste JSON around it -- at the same time if all I was passing for parms was one field with a shortval, not certain I'd use post either...