MultiformeIngegno
MultiformeIngegno

Reputation: 7059

Issue getting first item from JSON array

$('#data').change(function () {
    $.ajax({
        url:        'richiesta.php',
        type:       'POST',
        dataType:   'json',
        data: {
            value: this.value
        },
    }).done(function (data) {
        $('#textfield').val(JSON.stringify(data));
        $('#results').val('Descrizione codice: ' + data[0].descrizione_codice);
    });
});

richiesta.php is just a file that triggers some functions to get the JSON. #textfield is correctly populated with the raw JSON, so everything is working properly.

I can't figure out how to output the first item of the JSON identified by the name descrizione_codice in #results.

The JSON is valid, here's an example selecting one option (truncated):

{
   "data":[
      {
         "codice_comparto":"PRO",
         "descrizione_codice":"Competenze fisse per il personale a tempo indeterminato",
         "codice_siope":"1101",
         "descrizione_ente":"",
         "ricerca":false,
         "idtable":"000717409-1101",
         "cod_ente":"000717409",
         "anno":"2014",
         "periodo":"12",
         "codice_gestionale":"1101",
         "imp_uscite_att":"756",
         "importo_2013":"37718576",
         "importo_2014":"32810124",
         "importo_2015":null
      }
   ],
   "cosa":false
}

I'm doing something wrong is that data(0).descrizione_codice as Firebug tells me "data is not a function"..

I'm not using $.parseJSON because jQuery already parses data correctly thanks to the datatype.

I put up a test page here. You can request the JSON response selecting an option from the dropdown menu.

Upvotes: 2

Views: 5148

Answers (2)

Leo Nomdedeu
Leo Nomdedeu

Reputation: 338

    $('#results').val('Descrizione codice: ' + data.data[0].descrizione_codice);
  1. First data is your actual js variable
  2. Second data is your array inside JSON named "data" where we access first element's property named "descrizione_codice"

Hope it clarifies

Upvotes: 1

dfsq
dfsq

Reputation: 193261

According to your JSON structure you should be able to access array as data.data

.done(function (data) {
    console.log(data.data[0].descrizione_codice);
});

Upvotes: 4

Related Questions