Get JSON data

1

Greetings. I need to obtain the records of a specific row, through ajax I am sending the id to php and I get the row, but I am not able to manipulate the data and then assign them to html elements. Where will the error be?

$(function() {
    $('#id_project').on('change', function() 
    {
    var id_project = $('#id_project').val();
    $.ajax(
    {
        url: "ff.php",
        type: "POST",
        data:{id_project},
        dataType: "html",
        success: function(data)
        {
            var datos = data.nb_informacion_general_localizacion;
            alert(datos);
        },
    })
});
});

PHP

$id_project = $_POST['id_project'];
$sql = "bla bla bla";
while ($row = pg_fetch_assoc($result)) {
  echo $row['id_project'];
  echo $row['nb_informacion_general_localizacion'];
}
    
asked by Alex Hunter 20.11.2017 в 19:43
source

1 answer

2

Your problem is that you are returning each variable separately, therefore, when performing:

while ($row = pg_fetch_assoc($result)) {
  echo $row['id_project'];
  echo $row['nb_informacion_general_localizacion'];
}

You will be sending only the first answer ( id_project ) since the AJAX is waiting for the first response that comes.

To solve this, I recommend that you include the information inside an array and code it as JSON. In this way, you can access data much more easily from your AJAX call.

Your PHP code would look like this:

while ($row = pg_fetch_assoc($result)) {
   $fila['id_project'] = $row['id_project'];
   $fila['nb_informacion_general_localizacion'] = $row['nb_informacion_general_localizacion'];
}

echo json_encode($fila);

IMPORTANT:

  • You will have to change the dataType of your AJAX function to json .
  • You will have to add the header("Content-type: application/json"); header to the start of your PHP file.
answered by 20.11.2017 / 19:48
source