I am trying to get the value of a product from a database when the user makes the selection in a <select>
element and display said value obtained through AJAX in a element but its not working, if i go to the precio.php?q=PRODUCTO%201
it does give me the desired result 10
which makes me think the code inside the php file is correct, the issue must reside in the <script>
section or the <select>
element.
This is my AJAX function in the <head>
<script>
function precioProd(str) {
if (str=="") {
document.getElementById("precio").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("precio").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "precio.php?q="+str, true);
xmlhttp.send();
}
}
</script>
This is my <select>
element in the <body>
<div class="form-group row">
<label class="col-sm-4 col-form-label font-weight-bold">Elige un Producto</label><br>
<div class="col-sm-8">
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" onchange="precioProd(this.value)" required>
<option selected>Elegir...</option>
<?php require $_SERVER['DOCUMENT_ROOT'].'/php/fetch_lista_productos_compra.php'; ?>
</select>
</div>
</div>
<h3 id="precio" name="precio"></h3>
This is the content of precio.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/php/db_key.php';
$con = mysqli_connect($servername, $username, $password, $dbname);
$q = $_GET["q"];
$sql = "SELECT precio FROM productos WHERE titulo = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['precio'];
}
?>
As always any kind of help would be greatly appreciated and thank you for your time.
You have added an additional }
at the end of your script. The following is OK.
<script>
function precioProd(str) {
if (str=="") {
document.getElementById("precio").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("precio").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "precio.php?q="+str, true);
xmlhttp.send();
}
</script>