Forum Moderators: open

Message Too Old, No Replies

AJAX Request not working

         

PartisanEntity

2:51 pm on Aug 4, 2009 (gmt 0)

10+ Year Member



Hello all,

I have tried to put together the following AJAX request but it is not working. I keep getting an internal server error 500.

The aim of all this is to do nothing more than send the value of a button to the php script which spits back the value of the button that was clicked.

Here is the javascript portion:

<script type="text/javascript">

function GetValue(v) {
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.onreadystatechange = handleValue;
xmlHttpReq.open("GET", "updateSite.php?button="+v,true);
xmlHttpReq.send(null);
}

function handleValue() {
if(xmlHttpReq.readyState == REQUEST_COMPLETED) {
if(xmlHttpReq.status == HTTP_OK) {
alert(xmlHttpReq.responseText);
} else {
alert("Network error!");
}
}
}

</script>

Here the html:

<button type="button" onClick="GetValue(this.value)" class="button eins" value="1">
Button 1
</button>
<button type="button" onClick="GetValue(this.value)" class="button zwei" value="2">
Button 2
</button>
<button type="button" onClick="GetValue(this.value)" class="button drei" value="3">
Button 3
</button>

Oh and here is the part in the php:
<?php
Result = $_GET["button"];
echo "You clicked on Button ".Result;
?>

Demaestro

4:10 pm on Aug 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Can you look in the error log and report any details on the error.

What ever the error is, it is most likely coming from "updateSite.php" not the javascript.

Fotiman

4:37 pm on Aug 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You PHP is invalid. Try changing it to this:


<?php
$Result = $_GET["button"];
echo "You clicked on Button ".$Result;
?>

PartisanEntity

4:48 pm on Aug 4, 2009 (gmt 0)

10+ Year Member



Damn I have been looking at the code for the past day and completely missed that. Thanks very much Fotiman, that was it.

Now I can't seem to get the responseText to be shown in the alert in the Javascript, any ideas?

i.e. when I click on a button nothing happens on the html page (using the Firebug console I can see that there is a response from the php page)

whoisgregg

5:11 pm on Aug 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think this code will work better for checking that the ajax request is ready. You currently have:

if(xmlHttpReq.readyState == REQUEST_COMPLETED) { 
if(xmlHttpReq.status == HTTP_OK) {

Try:

 if(xmlHttpReq.readyState==4){
if(xmlHttpReq.status==200){

PartisanEntity

5:23 pm on Aug 4, 2009 (gmt 0)

10+ Year Member



Bingo, it's working, thank you!

I actually wanted to use constants, so I set REQUEST_COMPLETED and HTTP_OK but didnt actually create vales for them.