0

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!

5
  • Is the PHP outputting with a JSON header? Commented Apr 19, 2011 at 7:57
  • @dotty...what do you mean by that, sorry im new on this..can you give me example. thanks! Commented Apr 19, 2011 at 7:58
  • @dotty...i im using json_encode. I think there is no need to put that on my header. Am i correct? Commented Apr 19, 2011 at 8:02
  • 1
    You should check your JSON with jsonlint.com - it isn't valid. Commented Apr 19, 2011 at 8:10
  • 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. Commented Apr 19, 2011 at 8:11

1 Answer 1

1

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

1 Comment

thats why this is the first time i encountered this problem. My previous version of my jquery is 1.3+. This is the first time i change into 1.4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.