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>