Reputation: 51
I want to post the value of a selected radio button but the $_POST variable in PHP is getting assigned 'undefined', what do I need to change so the $_POST gets the correct value? I was thinking it might be because I havent used URIencode but when I do use this my JavaScript doesn't even get the element.
JAVASCRIPT
function rappoll(){
var xmlHTTPreq;
var url = "poll.php";
var params="name="+name;
var elements = document.getElementsByName("elements");
var checkedButton = getName(elements);
if (checkedButton) {
var name = checkedButton.value;
}
if (window.XMLHttpRequest) {
try {
xmlHTTPreq = new XMLHttpRequest();
} catch(e) {
xmlHTTPreq = false;
}
} else {
try{
xmlHTTPreq = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHTTPreq = false;
}
}
xmlHTTPreq.open("POST", url, true);
xmlHTTPreq.onreadystatechange = function()
{
if(xmlHTTPreq.readyState == 4 && xmlHTTPreq.status == 200){
document.getElementById('poll').innerHTML = xmlHTTPreq.responseText;
}
}
xmlHTTPreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHTTPreq.send(params);
}
function getName(group){
for (var i = 0; i < group.length; i++) {
var button = group[i];
if (button.checked) {
return button;
}
}
return undefined;
}
PHP
$name = $_POST['name'];
Upvotes: 0
Views: 61
Reputation: 57709
You declare and assign params
here:
var params="name="+name;
Since name
is not defined params
is now "name=undefined"
. Note that name
is declared because of variable hoisting, so you wont see undefined variable 'name'
.
Once you assign name
you must reassign params
too, or change this line:
xmlHTTPreq.send(params);
to
xmlHTTPreq.send("name=" + name);
Upvotes: 3