tags:

views:

56

answers:

3

Hi guys. Got some basic problem again.

I need to modify a function that previously returned a in code written object. Im now trying to get the object from json through $.getJSON

   function getEventData() {
       var result = '';

       $.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data){
           result = data; 
       });
       return result;
   }

Problem is that result isn't set in the callback function for obvious reasons.

Do you guys have a solution for this?

Edit: Ok i got an answer that was removed. I just had to change it abit..

This is the answer that works:

function getEventData() {
    var result = '';
    url = "ajax.php?cmd=getbydate&fromdate=&todate=";
       $.ajax({
          url: url,
          async: false,
          dataType: 'json',
          success: function(data){
                   result = data;
               }
        });
    return result;
}
A: 

Try:

   function getEventData() {
       var result = '';
       $.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data){
           return data;       
       });
   }

In your example, result was being returned by the function before $.getJSON's success callback fired, since execution flows straight past the ajax call without waiting for it to finish.

karim79
I have tried that but it doesnt seem to return it to the getEventData function call.
Yo-L
A: 

Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

kgiannakakis
Im sure its ok json.Inside the callback function I can check it out by console.log(data) and it is correct.
Yo-L
+1  A: 

You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:

   function getEventData() {
       var result = '';

        result = $.ajax({
          url: "ajax.php?cmd=getbydate&fromdate=&todate=",
          async: false,
          dataType: "json",
          data: data,
          success: function(data){
                   return data; 
               }
        });
       return result;
   }
Daff
I had to change it a bit to get it to work but it did it.Even though its not recommended its a hack in an existing function and i really need the function to return this correctly.
Yo-L