Problems with radio buttons and Javascript querying PHP/MySQL
Hi,
I've been working a lot in PHP but am fairly new to javascript, so sorry if this is fairly basic. I've spent a day trawling forum posts etc. but can't find a solution. I need JS to send variables from a radio button list to PHP, so that it can serve up content from javascript to a text box in the same form. The text box is meant to be giving the user extra info on their choice, so if they clicked on the 'dog' radio button the text box might say 'Barks a lot, good as a pet' (dummy text obv!) I've tried using the getElementById() function, below and giving each radio button the same id. But this seems to require only one id per page because when I try it only declares the value of the first radio button with this id. I've also tried document.getElementsByName() but this produces a string that is inadmissible as a value apparently (for what ever reason it doesn't work). To be clear - I need to get the vars to PHP so it can query a database. Can anyone help?
Code:
if(radioObject.checked==true){
var pet = document.getElementById('pet').value;
var queryString = "?pet=" + pet
ajaxRequest.open("GET", "extraInfo.php" + queryString, true);
ajaxRequest.send(null);
}
Problems with radio buttons and Javascript querying PHP/MySQL
Hi,
I've been working a lot in PHP but am fairly new to javascript, so sorry if this is fairly basic. I've spent a day trawling forum posts etc. but can't find a solution. I need JS to send variables from a radio button list to PHP, so that it can serve up content from javascript to a text box in the same form. The text box is meant to be giving the user extra info on their choice, so if they clicked on the 'dog' radio button the text box might say 'Barks a lot, good as a pet' (dummy text obv!) I've tried using the getElementById() function, below and giving each radio button the same id. But this seems to require only one id per page because when I try it only declares the value of the first radio button with this id. I've also tried document.getElementsByName() but this produces a string that is inadmissible as a value apparently (for what ever reason it doesn't work). To be clear - I need to get the vars to PHP so it can query a database. Can anyone help?
Code:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?pet=" + pet
ajaxRequest.open("GET", "extraInfo.php" + queryString, true);
ajaxRequest.send(null);
}
document.getElementsByName()
//-->
</script>
}
alert() queryString and I think you'll find pet is empty or undefined. How are you passing the value of the selected radio button to the ajax function?
Also, you are not allowed to nultiple elements on tha page with the same id.
The first thing you need to do is confirm your ajax function is receiving the value of the selected radio button.
Last edited by webdev1958; 03-05-2012 at 12:12 PM..
alert() queryString and I think you'll find pet is empty or undefined. How are you passing the value of the selected radio button to the ajax function?
Also, you are not allowed to nultiple elements on tha page with the same id.
The first thing you need to do is confirm your ajax function is receiving the value of the selected radio button.
Hi you're totally right. Sorry I missed out the key line somehow when I was copying in.
<
Code:
script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//missing line***********************
var pet = document.getElementById('pet').value;
//************************************
var queryString = "?pet=" + pet
ajaxRequest.open("GET", "extraInfo.php" + queryString, true);
ajaxRequest.send(null);
}
document.getElementsByName()
//-->
</script>
}
I do realise now, as you say, that the ID can't be on more than one element. I thought I could change it to .getElementsByName() but this doesn't return a value. I am trying to work out how I could call the value of any radio button in a group to send to PHP.
Thanks.
David
P.S. the var queryString gets added to a PHP page GET request.
I am trying to work out how I could call the value of any radio button in a group to send to PHP.
A set of radio buttons need to have the same name as you have. To get the value of the selected radio button you need to loop through them to look for the checked radio button.
Below is a demo of looping through radio buttons to get the selected value.
Insert the code in the demo function (change variable names to suit your code) into your ajax function to get the value for your pet value.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
<style type="text/css"></style>
<script type="text/javascript">
function ajaxFunction(){
var radBtnsO = document.getElementsByName('pet');
for(i=0; i<radBtnsO.length; i++){
if(radBtnsO[i].checked){
var selectedPet = radBtnsO[i].value;
i = radBtnsO.length; //jump out of for loop
}
}
alert('selected pet: '+selectedPet); //for debugging
}
</script>
</head>
<body>
<div>
Pet: Dog<input type='radio' name= 'pet' value='dog'/> <br />
Cat<input type='radio' name= 'pet' value='cat'/> <br />
Mouse<input type='radio' name= 'pet' value='mouse'/> <br />
<br />
<input type='button' onclick='ajaxFunction();' value='Query MySQL' />
</div>
</body>
</html>
Thank you so much webdev1958. I've finally got a solution to the problem that works thanks to your code. Just so I understand what you added. You told it keep checking - for - until the value of radiobuttons (i) was greater than 0. If it was greater than 0 then it reports the value of that button to variable selectedPet. Everytime it checks it sets i to zero so that any new change will also be detected.
Either way, thanks for your help. Here's the final solution that sends the variable to PHP/MySQL:
Code:
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//object ready to respond to changes reported from server - added
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var radBtnsO = document.getElementsByName('pet');
for(i=0; i<radBtnsO.length; i++){
if(radBtnsO[i].checked){
var selectedPet = radBtnsO[i].value;
i = radBtnsO.length; //jump out of for loop
//takes value selectedPet and adds it to a get request on a PHP page, e.g. "ajax-example.php?pet=dog" - added
var queryString = "?pet=" + selectedPet;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
}
// alert('selected pet: '+selectedPet); //for debugging
}
</script>
</head>
<body>
Pet: Dog<input type='radio' name= 'pet' value='dog' onclick='ajaxFunction();'/> <br />
Cat<input type='radio' name= 'pet' value='cat' onclick='ajaxFunction();'/> <br />
Mouse<input type='radio' name= 'pet' value='mouse' onclick='ajaxFunction();'/> <br />
<br />
<div id='ajaxDiv'>More info about your choice...</div>
<br>
<input type='button' onclick='ajaxFunction();' value='Query MySQL' />
</body>
</html>
Also the script that I used to query the database from this:
Code:
<?php
$con = mysql_connect("localhost","yourDatabaseName","yourPassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dysfunc_game01", $con);
$pet = $_GET['pet'];
$pet = mysql_real_escape_string($pet);
$query = "SELECT * FROM ajax_example WHERE pet = '$pet'";
$qry_result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($qry_result)){
$petdesc = $row['description'];
}
echo $petdesc;
?>
I need help - it seems the PHP does not respond or gets called
Guys,
I am trying to fill my select dropbox with mySQL value but it seems the PHP does not operate or gets called.
Where is my problem?
Quote:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<title>Buy Running Shoes</title>
</head>
<!--
==================================================================================================== ==
This template is available for free download from the Quackit website. http://www.quackit.com/html/tutorial/html_frames.cfm
-->
<html>
<head>
<script type="text/javascript">
function updateChoice1(sel)
{
var Brand = sel.form.choice1;
var ch2 = sel.form.choice2;
var Type = sel.form.Type;
var str = "1";
alert (Brand.value + Type.value);
ch2.options.length = 0;
ch2.options[0] = new Option("--choose--","");
sel.form.myBrand.value = 1;
var xmlhttp;
if (str=="")
{
alert ("wrong exit");
document.getElementById("choice2").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("choice2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getModel.php?b="+Brand.value,true);
xmlhttp.send();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Model</title>
</head>
<body>
<?php
echo '<input type="submit" />';
$b=$_GET["b"];
$t=$_GET["t"];
$con=mysql_connect("localhost","rs1-sl9","070871") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$con=mysql_select_db("runningshoes");
$query="SELECT * FROM `models` WHERE `Gender`='" . $t . "' AND `BrandID` =" . $b ;
$result = mysql_query($query);
echo 'Hello<br>';
echo '<select name="choice2">';
while($nt=mysql_fetch_array($result)){ //Array or records stored in $nt
echo '<option value="' . $nt[$ModelID] . '">' . $nt[$ModelName] . '</option>';
/* Option values are added by looping through the array */
}
echo '</select>'; // Closing of list box
?>