jeudi 3 mars 2016

creating and passing a checkbox array to javascript function

I have an html form displaying a series of checkboxes. The checkboxes (an array called "checkbox" is ) are created using a loop in php. I want to use this array for some background processing. Trying to use AJAX as below, but I am not able to get it working.

Please help!

Here is test.php: containing html form:

<!DOCTYPE html>

<script language="javascript">
function activate(checkbox){

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        document.getElementById("ajaxState").innerHTML =xhttp.readyState;
        document.getElementById("ajaxStatus").innerHTML =xhttp.status;

        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("POST", "process.php", true);
    xhttp.setRequestHeader( "Content-Type", "application/json" );
    xhttp.send(JSON.stringify(checkbox));
}
</script>

<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
    echo "$i: ";
    echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>

<button  type="button" name="button" onclick="activate(checkbox)" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>

</body>
</html>

Output: Don't get any response.

process.php: decode json data and display the array

<?php 
$data = file_get_contents( "php://input" );
$checkbox = json_decode( $data, true ); 

echo "Hello!<br>";
var_dump($checkbox);
?>

NOTE: If, in the button element, I use this.checkbox, var_dump returns NULL.

<button  type="button" name="button" onclick="activate(this.checkbox)" >Test</button>

Response: ajaxState: 4

ajaxStatus: 200

ajaxResponse: Hello! NULL




Aucun commentaire:

Enregistrer un commentaire