Yo-L
Yo-L

Reputation: 487

jquery trouble with getJSON call

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;
}

Upvotes: 1

Views: 233

Answers (2)

Daff
Daff

Reputation: 44205

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;
}

Upvotes: 1

kgiannakakis
kgiannakakis

Reputation: 104168

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.

Upvotes: 0

Related Questions