Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-05-2012, 09:45 AM   PM User | #1
dysfunc
New to the CF scene

 
Join Date: Mar 2012
Posts: 4
Thanks: 1
Thanked 0 Times in 0 Posts
dysfunc is an unknown quantity at this point
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); 

}
HTML code:

Code:
<form name='myForm'>
Pet: Dog<input type='radio' name= 'pet' id= 'pet' value='dog'/> <br />
Cat<input type='radio' name= 'pet' id= 'pet' value='cat'/> <br />
Mouse<input type='radio' name= 'pet' id= 'pet' value='cat'/> <br />
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
PHP section works - sends back a variable based on GET instructions. I've tested with static data.

Thanks,

David
dysfunc is offline   Reply With Quote
Old 03-05-2012, 09:48 AM   PM User | #2
dysfunc
New to the CF scene

 
Join Date: Mar 2012
Posts: 4
Thanks: 1
Thanked 0 Times in 0 Posts
dysfunc is an unknown quantity at this point
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>

}
HTML code:

Code:
<form name='myForm'>
Pet: Dog<input type='radio' name= 'pet' id= 'pet' value='dog'/> <br />
Cat<input type='radio' name= 'pet' id= 'pet' value='cat'/> <br />
Mouse<input type='radio' name= 'pet' id= 'pet' value='cat'/> <br />
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
PHP section works - sends back a variable based on GET instructions. I've tested with static data.

Thanks,

David
dysfunc is offline   Reply With Quote
Old 03-05-2012, 10:05 AM   PM User | #3
webdev1958
Banned

 
Join Date: Apr 2011
Posts: 656
Thanks: 14
Thanked 69 Times in 69 Posts
webdev1958 can only hope to improve
Code:
document.getElementsByName()
why have you got this line?

Code:
var queryString = "?pet=" + pet
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..
webdev1958 is offline   Reply With Quote
Old 03-05-2012, 12:52 PM   PM User | #4
dysfunc
New to the CF scene

 
Join Date: Mar 2012
Posts: 4
Thanks: 1
Thanked 0 Times in 0 Posts
dysfunc is an unknown quantity at this point
Quote:
Originally Posted by webdev1958 View Post
Code:
document.getElementsByName()
why have you got this line?

Code:
var queryString = "?pet=" + pet
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.

Last edited by dysfunc; 03-05-2012 at 12:54 PM..
dysfunc is offline   Reply With Quote
Old 03-05-2012, 09:44 PM   PM User | #5
webdev1958
Banned

 
Join Date: Apr 2011
Posts: 656
Thanks: 14
Thanked 69 Times in 69 Posts
webdev1958 can only hope to improve
Quote:
Originally Posted by dysfunc View Post
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>
webdev1958 is offline   Reply With Quote
Users who have thanked webdev1958 for this post:
dysfunc (03-06-2012)
Old 03-06-2012, 11:47 AM   PM User | #6
dysfunc
New to the CF scene

 
Join Date: Mar 2012
Posts: 4
Thanks: 1
Thanked 0 Times in 0 Posts
dysfunc is an unknown quantity at this point
Thank you! (Final solution)

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

Best,

David

Last edited by dysfunc; 03-06-2012 at 11:51 AM..
dysfunc is offline   Reply With Quote
Old 07-18-2012, 01:33 PM   PM User | #7
Dankid
New to the CF scene

 
Join Date: May 2012
Posts: 8
Thanks: 1
Thanked 0 Times in 0 Posts
Dankid is an unknown quantity at this point
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();




sel.form.myBrand.value = sel.options[sel.selectedIndex].value;
sel.form.myModel.value = "";
sel.form.myType.value = "getModel.php?b="+Brand.value+"&t="+Type.value;

}

function updateChoice2(sel)
{
sel.form.myModel.value = sel.options[sel.selectedIndex].value;
}
</script>
</head>
<body>
<form>
Brand: <select name="choice1" onchange="updateChoice1(this);">
<option value="">-- choose --</option>
<option value="1"> Mizuno</option>
<option value="2"> Brooks</option>
<option value="3"> Zoot</option>
</select>
Type: <select name="Type" onchange="updateChoice1(this);">
<option value="Men"> Men's Running Shoes</option>
<option value="Women"> Women's Running Shoes</option>
<option value="Kids"> Kids' Running Shoes</option>
</select>
Model:
<select name="choice2" onchange="updateChoice2(this);">
<option value="">-- choose other first--</option>
</select>


<br/><br/>
Brand: <input type="text" name="myBrand" readonly /><br/>
Type: <input type="text" name="myType" readonly /><br/>
Model: <input type="text" name="myModel" readonly /><br/>
</form>
<div style=" margin-left:33px; margin-top:29px; margin-right:15px; line-height:14px " >Copyright 2012 &copy; Value-Focused Investments Ltd. All rights reserved. <span class="blue"><a href="#" >Terms of use</a>&nbsp; |&nbsp; <a href="index-5.html" >Privacy Policy</a></span></div>

</html>

PHP Code:
<!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 
?>

</body>
</html>
Dankid is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:26 AM.


Advertisement
Log in to turn off these ads.