1

I am trying to append this JSON array to a select box

{
  "10":"Branche",
  "2":"Marketing & Comunicatie",
  "8":"Test Branche 1",
  "9":"Test Branche 2",
  "6":"Test Branche 3",
  "7":"Test Branche 4",
  "1":"Webdevelopment & design"
}

But it doesn't work I encoded it from a PHP array. This is how I am trying to loop through it.

this.addOption = function(name, table, value){
    $.ajax({
        type: "POST",
        data: {action:'add', table:table, value:value},
        url: "index.php",
    })
    .done(function( obj ) {
        $("#"+name+"-select").empty()
        console.log(name);
        $.each(obj, function( key, value ) {
            $("#"+name+"-select").append('<option value='+key+'>'+value+'</option>');
        });
    });
}

Where obj is the JSON array.

It is giving me this error:

enter image description here

9
  • How does your JSON come to obj? Maybe it needs to be parsed again. Commented Oct 16, 2014 at 12:27
  • 1
    Seems fine to me: jsfiddle.net/2nas43ae Commented Oct 16, 2014 at 12:27
  • 1
    @SinanSamet You should show a screenshot of the data being returned from PHP (via dev tools). More than likely it's invalid/not what you're expecting Commented Oct 16, 2014 at 12:32
  • 2
    Try explicitly setting dataType: 'json' in your $.ajax() options? Commented Oct 16, 2014 at 12:35
  • 1
    Thank you Anthony that worked! Sorry for my stupid mistake Commented Oct 16, 2014 at 12:36

2 Answers 2

3

It appears that your PHP is outputting the JSON with a content type of text/html and because you haven't told jQuery you're expecting JSON, it won't parse the response, and in the end you're trying to call $.each on a string.

Add a dataType to tell jQuery to explicitly parse the response as JSON:

$.ajax({
    type: "POST",
    data: {action:'add', table:table, value:value},
    url: "index.php",
    dataType: 'json'
})

Alternatively, set the correct content type in your PHP:

header('Content-type: application/json');
echo json_encode(...);
Sign up to request clarification or add additional context in comments.

Comments

0

Yes you can use following way:

 for(k in obj) {
    $("#branch-select").append('<option value='+k+'>'+obj[k]+'</option>');
 }

1 Comment

Indeed they can. But that's not the question :)

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.