1

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; } 
1
  • I undeleted my answer, but be aware, that this procedure is not recommended at all so try to avoid it whenever possible. Commented May 28, 2010 at 14:52

2 Answers 2

1

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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.

1 Comment

Im sure its ok json. Inside the callback function I can check it out by console.log(data) and it is correct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.