0

I'm trying to get the value of the checkbox using an Ajax/Javascript response which passes the value to PHP so i can perform a query based on the value ("Checked","Not checked")

<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">

The Javascript/Ajax code for the function "updateStatus" is as followed

function updateStatus(id,value) {
if (window.XMLHttpRequest) {
    http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
    http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
    alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
     if (http.readyState == 4) {
        alert(http.responseText);
     }
 }
 http.send(null)

The PHP function inside functions/ajax.php

if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
    $id = mysql_real_escape_string($_GET['id']);
    $checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
    echo "Checked";
} elseif($checked == false) {
    echo "Not checked";
} else {
    echo "Invalid response";
}

when using this code it always returned "Checked" any idea why ?

3 Answers3

5

In the JS. value will be true or false. When you stringify either of those, you will get a string ('true' or 'false').

Thus $_GET['checked'] will be either "true" or "false" both of which == true.

To fix this on the PHP side, compare to the string "true" and the string "false"; not the boolean.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

You are getting $_GET['checked'] as a String. Change to something like:

if($checked == "true") {
    echo "Checked";
} elseif($checked == "false") {
    echo "Not checked";
} else {
    echo "Invalid response";
}
blo0p3r
  • 6,790
  • 8
  • 49
  • 68
nimlhug
  • 121
  • 4
0

This might help you in your answer https://stackoverflow.com/a/4228827/90648

You can try replacing the code

"&checked="+value

with

(value ? "&checked=true" : '')

This way you will only send the value true when it is checked, and not send anything (which you can check in PHP with isset)

or you can go with

(value ? "&checked=true" : '&checked=')

which will again, not send anything, thus empty string will be interpreted as false.

Community
  • 1
  • 1
Azder
  • 4,698
  • 7
  • 37
  • 57