Bring and display json data with ajax

0

I have a select in a form, and I want that when selecting an option, it shows me the ones related to it in some input text in the form (to send and save it in BD later). Use an ajax to send the selected value and make the query to the corresponding DB, but when you bring the result, it does not show me anything and it throws me the "error" message of the function. I'm pretty newbie in all this .. Thanks in advance.

<script type="text/javascript">
    function objetoAjax(){
        var xmlhttp=false;
        try {
               xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
               try {
                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
               } catch (E) {
                       xmlhttp = false;
               }
        }
 
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
               xmlhttp = new XMLHttpRequest();

        }

        return xmlhttp;

}


function mifuncion(valor){
        $.ajax({
            url : 'buscard.php',
            type : 'GET',
            dataType : 'JSON',
            data : {valor:valor},
         
         success : function(json) {


        $("#precio").value = json.precio;
        $("#moneda").value = json.moneda;
            },
 
// código a ejecutar si la petición falla;
            error : function(xhr, status) {
                alert('Disculpe, existió un problema');
            }
});
    }
</script>
<div class="input-field col s6">
 
 <select id="propiedad" name="propiedad" class="browser-default" onchange="mifuncion(this.value)">
                            
                            <option value="nulo" selected="">Propiedad</option>
                            <?PHP
                            $sql= ("SELECT * FROM propiedades");
                            $res= mysql_query ($sql,$cnx);
                            while ($array= mysql_fetch_assoc($res)) {


                            echo "<option value=".$array['Id'].">".$array['Titulo']."</option>";

                            }
echo '
</select>
</div>
</br>';

?>


Precio: <input id="precio" type="text" name="precio" class="validate" aria-required="true" required> </br>

Moneda: <input id="moneda" type="text" name="moneda" class="validate" aria-required="true" required> </br>

buscard.php

<?PHP
require_once ("inc/html.head.php");
?>
<?php
if ( !function_exists('json_decode') ){
    function json_decode($content, $assoc=false){
                require_once 'Services/JSON.php';
                if ( $assoc ){
                    $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        } else {
                    $json = new Services_JSON;
                }
        return $json->decode($content);
    }
}

if ( !function_exists('json_encode') ){
    function json_encode($content){
                require_once 'Services/JSON.php';
                $json = new Services_JSON;
               
        return $json->encode($content);
    }
}
?>
<?php

//el dato que enviamos a traves de ajax
$valor=$_GET['valor'];
 
//la consulta que necesites para trer el codigo y el nombre del cliente
$query=("SELECT * FROM propiedades WHERE Id =".$valor);
 
$r=mysql_query($query,$cnx);
while($resultados= mysql_fetch_array($r)){

 
$precio=$resultados['Precio'];
$moneda=$resultados['Moneda'];

//esta variable es para retornar los datos
$jsondata = array();
 
//agregamos nuestros datos al array para retornarlos
$jsondata['precio'] = $precio;
$jsondata['moneda'] = $moneda;

}
//este header es para el retorno correcto de datos con json
//header('Content-type: application/json; charset=utf-8');
 echo json_encode($jsondata);
?>
    
asked by jorge laquis 27.09.2018 в 16:26
source

1 answer

0

The truth is that what you upload is quite tangled and it took me a bit to understand what you upload, I'll write you an example on how you can make a call with ajax and then send by post to save the selected I hope it was clearer (I will obviate the use of librearias as jquery for the use of ajax)

Html

<div>
 <select id="propiedad" name="propiedad" class="browser-default">
  <option>tus dato de la consulta</option>
 </select>

 Precio: <input id="precio" type="text" name="precio" class="validate" aria-required="true" required> </br>

 Moneda: <input id="moneda" type="text" name="moneda" class="validate" aria-required="true" required> </br>
</div>

js for ajax use

$('#propiedad').change(function () {

var propiedad = $('#propiedad').val();

var consulta = $.ajax({
    type: 'post',
    url: ('buscar.php'),
    data: {valor: valor},
    dataType: 'JSON'
});

consulta.done(function (data) {
    if (data.error !== undefined) {
        $('#estado').html('Ha ocurrido un error: ' + data.error);
        return false;
    } else {
        if (data.NombreApellido !== undefined) {
            $('#Datoscilindro #txtNombreApell').val(data.NombreApellido);
            $('#txtNombreApell').attr('readonly', 'true');
        }
        return true;
    }
});
consulta.fail(function () {
    $('#estado').html('Ha habido un error contactando el servido de clientesr.');
    return false;
});

})

searched.php

 $conexion = new \mysqli(tus datos de conexion);
if($conexion->connect_error){echo "Fallo al conectar:".$conexion->connect_error() or die();} if( !empty($_POST['valor'])){
    $id = $_POST['valor'];
    $sql = "SELECT* FROM tabla  WHERE id = '$id'";
    $result = $conexion->query($sql);
    die(json_encode($result->fetch_array()));
}
$conexion->close();

This is a simple way to do it, there are more ways and best practices to do it by refactoring the code but as you are just starting out it is a good starting point

I hope it serves you

    
answered by 27.09.2018 в 16:53