0
votes

Hi iv got this error on my ajax function using json on retrieving data. It wont return any data. Here's my code below

$.ajax({
  url: "php/getCategory.php?action=getyear",
  cache: false,
  dataType: "json",
  success: function(data){
    $.each(data.items, function(i,item){
        $("#catYear").append('<option value="'+item.id+'">'+item.name+'</option>');
    });
  }
});

When i try to remove dataType: "json" it will pass into success: function. I think the problem is on my json. I also echo the output of my getCategory.php and i think their is no problem on it. Below is the output of my php json_encode.

{items:[{"id":"1","name":"2010"},{"id":"2","name":"2011"}]}

Thanks!

1
Is the PHP outputting with a JSON header? - dotty
@dotty...what do you mean by that, sorry im new on this..can you give me example. thanks! - drexsien
@dotty...i im using json_encode. I think there is no need to put that on my header. Am i correct? - drexsien
You should check your JSON with jsonlint.com - it isn't valid. - Quentin
json_encode will give you a lump of JSON. You still need the to say header('content-type: application/json'); otherwise PHP will claim it is sending an HTML document. - Quentin

1 Answers

1
votes

from jquery documentation :

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

so jour json string has element items which is not double quoted try something like that :

{"items":[{"id":"1","name":"2010"},{"id":"2","name":"2011"}]}