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);
?>