Referencing an object loaded from a JSON

1

I try to make a plugin that loads a JSON from google book. In principle it is very simple and I use a single file.

The jquery function receives the JSON and with

console.log(data)

Shows it correctly. The problem comes when I try to print partial data of the type

data.items[0].volumeInfo.title

Well, it catalogs undefined .

The code I use is:

<?php
/*
 * The JavaScript for our AJAX call
 */
function rellenar_datos_con_json() {
  ?>
  <script type="text/javascript" >
  jQuery(document).ready(function($) {
    $( '#buscarlibro' ).click( function() {
      var id = $( '#valor' ).val();
      $.ajax({
        method: "POST",
        url: ajaxurl,
        data: { 'action': 'cargar_json_action', 'id': id }
      })
      .done(function( data ) {
        console.log(data);
        $( '#librotable' ).append('<tr><td>' + data.items[0].volumeInfo.title + </td><td> + data.items[0].volumeInfo.authors + '</td><td>' + data.items[0].volumeInfo.publishedDate + '</td><td>' + data.items[0].selfLink + '</td></tr>');
      })
      .fail(function( data ) {
        console.log('Failed AJAX Call :( /// Return Data: ' + data);
      });
    });
  });
  </script>
  <?php
}
add_action( 'admin_footer', 'rellenar_datos_con_json' );
/*
 * The AJAX handler function
 */
function cargar_libros() {
  $data = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=' . $id);
  echo $data;
  wp_die(); // just to be safe
}
add_action( 'wp_ajax_cargar_json_action', 'cargar_libros' );
?>

The JSON that I receive in the console is:

{
 "kind": "books#volumes",
 "totalItems": 8,
 "items": [
  {
   "kind": "books#volume",
   "id": "iFxlngEACAAJ",
   "etag": "US1yzgaTJ/k",
   "selfLink": "",
   "volumeInfo": {
    "title": "Enciclopedia de Microsoft Visual C#",
    "authors": [
     "Francisco Javier Ceballos Sierra"
    ],
    "publishedDate": "2013",
    "industryIdentifiers": [
     {
      "type": "ISBN_10",
      "identifier": "8499642640"
     },
     {
      "type": "ISBN_13",
      "identifier": "9788499642642"
     }
    ],
    "readingModes": {
     "text": false,
     "image": false
    },
    "pageCount": 1118,
    "printType": "BOOK",
    "categories": [
     "Computers"
    ],
    "maturityRating": "NOT_MATURE",
    "allowAnonLogging": false,
    "contentVersion": "preview-1.0.0",
    "imageLinks": {
     "smallThumbnail": "",
     "thumbnail": ""
    },
    "language": "en",
    "previewLink": "",
    "infoLink": "",
    "": "."
   },
   "saleInfo": {
    "country": "ES",
    "saleability": "NOT_FOR_SALE",
    "isEbook": false
   },
   "accessInfo": {
    "country": "ES",
    "viewability": "NO_PAGES",
    "embeddable": false,
    "publicDomain": false,
    "textToSpeechPermission": "ALLOWED",
    "epub": {
     "isAvailable": false
    },
    "pdf": {
     "isAvailable": false
    },
    "webReaderLink": "",
    "accessViewStatus": "NONE",
    "quoteSharingAllowed": false
   }
  },
    
asked by Pedro Lorca 22.12.2016 в 13:23
source

3 answers

1

You should indicate that the response of ajax is json .

$ .ajax provides the dataType option.  When dataType: "json" is set, the response is evaluated as JSON and returns a JavaScript object.

Example:

$.ajax({
  method: "POST",
  url: ajaxurl,
  dataType: 'json', // <-- Indicamos que la respuesta es JSON
  data: { 'action': 'cargar_json_action', 'id': id }
})
    
answered by 22.12.2016 в 15:53
0

That's because your json is not an arrangement

var array = JSON.parse(data);
array.items;

var array = JSON.parse('{"kind": "books#volumes","totalItems": 8,"items": [{"kind": "books#volume","id": "iFxlngEACAAJ","etag": "US1yzgaTJ/k","selfLink": "","volumeInfo": {"title": "Enciclopedia de Microsoft Visual C#","authors": ["Francisco Javier Ceballos Sierra"],"publishedDate": "2013","industryIdentifiers": [{"type": "ISBN_10","identifier": "8499642640"}, {"type": "ISBN_13","identifier": "9788499642642"}],"readingModes": {"text": false,"image": false},"pageCount": 1118,"printType": "BOOK","categories": ["Computers"],"maturityRating": "NOT_MATURE","allowAnonLogging": false,"contentVersion": "preview-1.0.0","imageLinks": {"smallThumbnail": "","thumbnail": ""},"language": "en","previewLink": "","infoLink": "", "": "."},"saleInfo": {"country": "ES","saleability": "NOT_FOR_SALE","isEbook": false},"accessInfo": {"country": "ES","viewability": "NO_PAGES","embeddable": false,"publicDomain": false,"textToSpeechPermission": "ALLOWED","epub": {"isAvailable": false},"pdf": {"isAvailable": false},"webReaderLink": "","accessViewStatus": "NONE","quoteSharingAllowed": false}}]}');
console.log(array.items[0].volumeInfo.title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 22.12.2016 в 14:11
0

The answer the $ .ajax () function is giving you is not an object, so you have than to make it an object using JSON.parse () :

.done(function( data ) {
   console.log(data);
   data = JSON.parse(data);
  
   // Resto del código
})

You can tell $.ajax() that the answer is a json as described Marcos Gallardo .

    
answered by 24.12.2016 в 20:16