0

I have created a javascript object and im trying to fetch som data from it. Im using jquery ajax to fetch send some values and then returing them from a php script. this works, but when i try to use an instanse of my javascript object to dispaly the value i get 'undefined'.

Object:

var getDBresults = (function () {   
    function getResult(url,TableName ,callback){
        $.ajax({
            url: url,
            type: 'POST',
            data: {
                'table':TableName,
            },
            success: function(data){
                callback(data);
            },
            error: function(event){
                alert(event.error);
            }

        });
    }   
    return {
        getAllVideoes: function(){
            getResult("getAllResults.php", "videoer", function(data){
                console.log(data); //Works
                return data;
            });
        },
    }

})();

in my other script:

var obj = getDBresults;
var data = obj.getAllVideoes(); //this runs, and produce the log showed above
console.log(data) //results in undefined
    console.log(obj.getAllVideoes()) //results in undefined
Rinrub
  • 137
  • 10
  • tried the async false, but no luck. but i think that is the root to the problem. the response is expected before the ajax call is finished. Just DK how to fix it :/ – Rinrub Mar 10 '14 at 13:55
  • You're using callbacks, but still not really getting it. You can't use `data` in the return statement, it's not available yet, and you can't return the content of `data` to `getDBresults` even if you wrap it in a IIFE, you have to write code that works with the data **when it's available** and not code that expects the data to be available when it's not, and `async : false` is never the solution. – adeneo Mar 10 '14 at 14:07
  • You are totaly right dude. Im not getting it, thats why i ask. I thought the callback would make sure the $.ajax returned "success" and was finished with the call to the server before the callback was invoked. I can see that im wrong about that, but i just dont get why :) thx for the reply anyways – Rinrub Mar 10 '14 at 14:15

1 Answers1

0

Maybe you can use callbacks it will solve your async problems: http://recurial.com/programming/understanding-callback-functions-in-javascript/

Aartsie
  • 143
  • 2