user3636516
user3636516

Reputation: 325

Error in receiving JavaScript value in php

I am writing a simple code to select a radio button and pass the value of the selected radio to php code, through AJAX!

Heres my code for AJAX:

function sendid(attack)
{
    var att;
    var xmlhttp;
    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("result").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","battlephp.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("att="+attack+"");
}
</script>
</head>
<body>

<input type="radio" value="10" name="attack" onclick="sendid('this.value')"/> Attack 1
<input type="radio" value="20" name="attack" onclick="sendid('this.value')"/> Attack 2

And my php code:

$attack = intval($_POST['att']);
echo "Working ".$attack;

The Output I am getting is:

Working 0

Which should be either "Working 10" or "Working 20"

Surely its not identifying the att which is passed through the AJAX..! But how should I handle it now??

Upvotes: 2

Views: 40

Answers (1)

shatheesh
shatheesh

Reputation: 633

This should be

<input type="radio" value="10" name="attack" onclick="sendid(this.value)"/> Attack 1
<input type="radio" value="20" name="attack" onclick="sendid(this.value)"/> Attack 2

You should not enclose this.value with ' single quotes since it will consider it as string if you enclose with single quotes rather than object property

Upvotes: 2

Related Questions