-4

I need to return a variable from a function

function getdatabasesize() {
    name = "t";
    var test
    $.post(
        'ajax/getlastfilenumber.php',
        { name: name }, 
        function(data) {    
            test = data;
        });
        return test;
    }

Then to call this I use something like

alert(getdatabasesize());

or

var test = getdatabasesize()

but all I get is undefined. I want to use this to get the last record number in my database you see.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Remember, the first A in AJAX stands for Asynchronous. `return test` is hit before `test` is set in the AJAX callback function. – Rory McCrossan Nov 23 '13 at 12:12

1 Answers1

0

You can return promise interface from function and then use specific methods on it:

function getdatabasesize() {
    name = "t";
    return $.post(
        'ajax/getlastfilenumber.php', {
        name: name
    });
}

getdatabasesize().done(function (data) {
    alert(data);
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • I don't know why this was downvoted? – Rory McCrossan Nov 23 '13 at 12:17
  • Just code, no explaination, maybe that's it – A. Wolff Nov 23 '13 at 12:19
  • Hi A. Wolff, What you posted works, however I cannot use data outside the scope of getdatabasesize. I am really new to jquery, so I am not 100percent certain how to get things to work. However I know programming and php, so I should be able to get my head around this. I tried creating a var outside the scope and using that, but it still didn't work. – user3024801 Nov 23 '13 at 12:30
  • Set an outer scoped (global?) variable e.g `var test;` and affect value in done() callback. Still in done() callback, call function(s) to use this new variable value. This is how you have to deal with async methods. – A. Wolff Nov 23 '13 at 12:38