JSON from PHP, travel with JQUERY

1

I have generated a JSON in a PHP with MySQL data with the following code:

header("Content-Type: application/json");

while($spot = mysqli_fetch_assoc($dbspots)) {
    $jsonspots[] = $spot;
}

print_r($jsonspots);

This generates this output:

Array
(
    [0] => Array
        (
            [freq] => 14017
            [spotcall] => RN9N/M
            [time] => 1503318960
            [comment] => RDA SV-09
            [spotter] => RN9N
        )

    [1] => Array
        (
            [freq] => 14140
            [spotcall] => RA70MG
            [time] => 1503318900
            [comment] => 
            [spotter] => UB8CIF
        )

)

I have several doubts ...

1.- Is the JSON generation okay?

2.- How can I go through it with JQUERY to get the data? freq = nnn etc.

    
asked by FabianTRS 21.08.2017 в 14:40
source

1 answer

1

Is the JSON generation okay?

To generate a JSON from PHP you must use the function json_encode :

header("Content-Type: application/json");

while($spot = mysqli_fetch_assoc($dbspots)) {
    $jsonspots[] = $spot;
}

echo(json_encode($jsonspots));

How can I go through it with JQUERY to get the data? freq = nnn etc.

You do not need jQuery to iterate the contents of a variable.

To iterate the content of the response from javascript you can use any type of loop, for example a loop for ... in .

Below is a freelance PHP script with which you can test the operation:

<?php
/* Comprobamos si es la petición POST lanzada */
if (isset($_POST['datos'])) {
    $datos = Array (
        0 => Array (
            'freq' => 14017,
            'spotcall' => 'RN9N/M',
            'time' => 1503318960,
            'comment' => 'RDA SV-09',
            'spotter' => 'RN9N',
        ),
        1 => Array (
            'freq' => 14140,
            'spotcall' => 'RA70MG',
            'time' => 1503318900,
            'comment' => '',
            'spotter' => 'UB8CIF',
        ),
    );
    /* Devolvemos la cabecera adecuada para los datos generados */
    header('Content-Type: application/json');
    die(json_encode($datos));
}
?><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
/* Preparamos la consulta XHR */
$.ajax({
    method: 'post',
    /* La lanzamos a la misma URL */
    url: '<?= $_SERVER['PHP_SELF'] ?>',
    /* Datos de envío de prueba */
    data: {
        'datos': true,
    },
    /* Solicitamos un JSON de retorno */
    dataType: 'json',
}).done(function(datos) {
    /* Iteramos por cada elemento devuelto en la variable "datos" */
    for (dato in datos) {
        /* Agregamos un párrafo al <div> con el contenido */
        $( '#resultado' ).append( "<p>Valor de 'frec' (" + dato + "): " + datos[dato].freq + "</p>" );
    }
});
</script>
<div id="resultado"></div>
    
answered by 21.08.2017 в 15:02