简体   繁体   中英

PHP AJAX MySql grabbing data - radio button

Is it possible to display data from the database by clicking a radio button. Currently I have it set to a drop down box but I would like it to connect to my radio button. Here is one of my current radio button codes:

<Input type = 'Radio' Name ='compcase' value= '1' />NZXT Phantom Enthusiast USB3.0 Full Tower Case - White <br />

The current code I have is:

index.php

<script>
  function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
} 
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
  document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getprice.php?q="+str,true);
xmlhttp.send();
}

</script>

<select name="case_price" onchange="showUser(this.value)">
<option value="">Select a processor:</option>
<option value="1">i5 2500k</option>
<option value="2">i5 4970k</option>
<option value="3">i7 4770k</option>
<option value="4">i7 4790k</option>
</select>
<div id="txtHint"><b>Processor listed here</b></div>

getprice.php

    <?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"compcase");
$sql="SELECT * FROM compcase WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['case_price'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

when you are going to get many data from a php file via ajax and you dont know how many are them
you have to change your data format to JSON
try this:

$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','test');
mysqli_select_db($con,"compcase");
$sql="SELECT * FROM compcase WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

$callBack = json_encode( mysqli_fetch_array($result) );
//then echo that
echo $callback;

mysqli_close($con);

and in your JavaScript file you can parse data by
JSON.parse(xmlhttp.responseText);
It give's you back an array containing your data
I recommend you to detect index names in array by :
console.log(JSON.parse(xmlhttp.responseText));
then you can detect how to access your data just by pressing F12 and clicking on console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM