Access JSON data (PHP, AJAX)

0

I have the following code which makes the query correctly in the database:

<?php
$serverName = "SERVIDORSQL";
$connectionInfo = array(
    "Database" => "bd_test",
    "UID" => "supervisor",
    "PWD" => "supervisor",
    "CharacterSet" => "UTF-8"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
$modelo = $_POST['codigo_sel'];

if ($conn === false) {
    die(print_r(sqlsrv_errors() , true));
}
else {
    echo "Conexión establecida.<br />";
}

$sql_consulta_query = sqlsrv_query($conn, $sql_consulta);

if (($sql_consulta_query = sqlsrv_query($conn, "SELECT CNOMBREPRODUCTO
     FROM bd_test WHERE CCODIGOPRODUCTO = '$modelo' ")) !== false) {
    while ($row = sqlsrv_fetch_array($sql_consulta_query)) {
        $codigo_modelo[] = $row;
    }
}

echo json_encode($codigo_modelo);

I get the following JSON result

[{"0":"CJ688TGBL","CNOMBREPRODUCTO":"CJ688TGBL"}]

I want to access the data from this function, but still without success.

$('.autocompletarCodigo').focusout(function() {
    $.ajax({
        url: 'http://localhost/inv/php/auto-modelo-other.php',
        type: 'POST',
        dataType: 'json',
        data: {
            codigo_sel: $('.autocompletarCodigo').val()
        }
    }).done(function(data) {
        $('#modelo1.autocompletarModelo').val(data);
    });

});

I already tried several combinations in the .val (data) but without success I could not access the data.

I look forward to your comments.

    
asked by Julio Martinez 26.01.2017 в 21:44
source

2 answers

1

I recommend you save your data in an array, in my case I call it response, inside this array I save another more data, once the fixes are full, I use json_encode passing as parameter the response array, so when the server return answer, return the resulting json, in jquery you manipulate it within "success" by going through each one or simply print the json in console 'to see the results.

php:

//como devolver la respuesta a la peticion ajax
    header("Content-Type: application/json;charset=utf-8");
    http_response_code(200);
    echo json_encode($response);

jquery:

success: function(response) {
                $.each(response.datos, function(index, value) {

                //accion
               });
                console.log(response);

            },
    
answered by 22.11.2018 в 21:37
0

To obtain the values of the object data use:

console.log(data[0].CNOMBREPRODUCTO);
// Resultado: "CJ688TGBL"

console.log(data[0][0]);
// Resultado: "CJ688TGBL"

You can change the following line of code to place the value in the text field:

$('#modelo1.autocompletarModelo').val(data[0].CNOMBR‌​EPRODUCTO);

or with Javascript:

document.getElementById('modelo1').value = data[0].CNOMBR‌​EPRODUCTO;
    
answered by 26.01.2017 в 21:59