1

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?

11
  • 1
    Is data in JSON format? Commented Aug 20, 2015 at 9:07
  • Yes I get an array from mysql and encode it with json_encode Commented Aug 20, 2015 at 9:08
  • @Tushar I would say it is. Commented Aug 20, 2015 at 9:08
  • 1
    I see no issues in your jQuery code. working fiddle Commented Aug 20, 2015 at 9:08
  • 6
    dataType:'json', Commented Aug 20, 2015 at 9:09

2 Answers 2

7

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

2 Comments

Actually I solved it by specifying the data type in the ajax request. I thought that jQuery could be able to detect it but it didn't
@LelioFaieta Yes, there are a lot of ways. Glad that something worked for you.
2

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.

Comments

Your Answer

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