Read a JSON object from Javascript

3

I have found many forums and texts where they explain it in detail, the problem is that nothing works for me and I have tried it in many ways. I leave you the JSON and how I try to read it without having different results from:

  

application.js: 29 Uncaught ReferenceError: content is not defined       at HTMLButtonElement. (application.js: 29)       at HTMLButtonElement.dispatch (jquery-3.1.1.min.js: 3)       at HTMLButtonElement.q.handle (jquery-3.1.1.min.js: 3)

Thanks in advance for your response.

    [ { 0: "14460243",
         1: "", 
         2: "RICARDO RAFAEL ", 
         3: "VILLAGRANA LARIOS",  
         4: "VILLAGRANA", 
         5: "LARIOS", 
     ncont: "14460243", 
  mtricula: "", 
    nombre: "RICARDO RAFAEL ", 
  apellido: "VILLAGRANA LARIOS", 
        AP: "VILLAGRANA", 
        AM: "LARIOS" } ]

and this is my code with which I intend to read:

$('#load-more').click(function(){
    $.get('api/fields.php?code=show',function(data){
            var content = JSON.parse(data);
            console.log(content)
        })
        alert(content[0].nombre)
});

This is executed when I press a button

<button id="load-more" style="margin: 150px;" class="btn btn-color-2"> <i class="fa fa-refresh"></i> Cargar más </button>
    
asked by Ricardo Villagrana Larios 30.12.2016 в 21:06
source

2 answers

2

The problem is that the Ajax call is asynchronous, when you make the Ajax javascript request it continues to the next execution line where you show the 'alert', the answer will come later after the 'alert' has been displayed, theoretically the response can arrive before the 'alert' is invoked and shows you the information but the latency of an Ajax call is huge compared to the execution of the script since the first is subject to network latency while the second is subject to the processor cycles.

the line console.log (content) should show you the result but not the 'alert'.

To control the execution flow and be serial you can use promises, however everything is serial within the context of the promises, any code outside the promise will not follow the same serial execution flow.

$.get('api/fields.php?code=show')
  .done(function( data ) {
     var content = JSON.parse(data);
     console.log(content)
     alert(content[0].nombre)
  });
    
answered by 30.12.2016 / 21:39
source
1

The exact error is giving you, because outside of the function of $.get of jQuery you have not defined content , and you are doing an alert, it would be best to do it inside, as follows:

$('#load-more').click(function(){
    $.get('api/fields.php?code=show', function(data) {
        var content = JSON.parse(data);
        console.log(content);
        alert(content[0].nombre)
    })
});

It would also be good if you verify first if data is a string, then pass it by JSON.parse

    
answered by 30.12.2016 в 21:37