Lelio Faieta
Lelio Faieta

Reputation: 6684

issue while looping a json array

I retrieve some option for a select from an ajax call in json format. The code I have set up to display the new options in the select (replacing the existing ones) is the following:

success: function (data){
    var $select = $('#dettaglio');
    $select.html('');
    $.each(data, function(key, val){
        $select.append('<option id="' + val.id + '">' + val.text +'</option>');
    })
}

while the json is like this:

[
   {"id":"1","text":"J-Invest Spa"},
   {"id":"2","text":"J-A Holding S.r.l."},
   {"id":"3","text":"J-Invest Advisory & Servicing S.r.l."},
   {"id":"4","text":"J-Invest Immobiliare e Consulenza S.r.l."}
]

Running this code leads to an error that is not easy to understand:

TypeError: invalid 'in' operand e

...===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={}...

jQuery is throwing an error but this is not helpful to see where my code is wrong. Any hint?

Upvotes: 1

Views: 82

Answers (2)

Ismael Miguel
Ismael Miguel

Reputation: 4241

The easiest way would be to change a bit on your PHP, by adding this:

header('Content-type: application/json');

Just that. jQuery is automatically set to detect the encoding of the returned data. If later you decide to send something else, you just change the header.

Warning: This function must be one of the first ones to be executed, before ANY output. Otherwise, it will throw errors at you.

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Yes I get an array from mysql and encode it with json_encode. The data received from the server will always be of string type. You need to parse it to convert to JSON format. Can you try this?

success: function(data) {
  data = JSON.parse(data);

Or in case, if you are using some Old IE, you can also try:

success: function(data) {
  data = $.parseJSON(data);

Upvotes: 7

Related Questions