Reputation: 157
I am having trouble in submitting radio input values using PHP and AJAX. I've constructed the code below, but I can't seem to get it to work. Any ideas? The values of the radio fields need to pass only when the button is pressed
<script>
function showUser(str) {
if (str == "myvalue") {
document.getElementById("txtHint").innerHTML = "";
/// location of new code -start
document.querySelector('input[name="users"]:checked').value;
/// location of new code -end
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
<form>
<input type="radio" name="users" value="1">
<input type="radio" name="users" value="2">
<!-------unable to pass value----------->
<input type="button" value="myvalue" onclick="showUser(this.value)">
<!-------unable to pass value----------->
</form>
<div id="txtHint">echo results here</div>
ajax-php.php
<?php
$q = intval($_GET['q']);
echo $q;
?>
Thank you.
Upvotes: 0
Views: 449
Reputation: 1018
What you are doing is fine.
<input type="button" onclick="showUser(this.value)">
The function showUser
is called by the button
type input field. And the field has no value.
If you want to send any value then use value attribute
. For example:
<input type="button" value="mayValue" onclick="showUser(this.value)">
To access the radio button value you can use this code.
document.querySelector('input[name="users"]:checked').value;
To send the radio button value follow the code bellow
//xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.open("GET", "ajax-php.php?q=" + document.querySelector('input[name="users"]:checked').value, true);
Upvotes: 0
Reputation: 2016
Your 'this.value' parameter being passed to your showUser function is scoped to the element with the onclick function. So it is trying to send the value of the button element which has no value.
Upvotes: 1