0

Hi guys, I have an array of data, and I want to print it in HTML form (type checkbox) and collect checked values and add it to the database. Here is my code so far, PHP code

//data sample
<?php $testData = ['8966558555e55', '2655sd889s55', '555522d859dkd'] ?>
<form action="<?php $_SERVER['self']?>" id="register_form">

  <?php 
    foreach ($testData as $key => $id) {
        # print IDs
        echo '<input class="formVal" type="checkbox" name"test_delete[]" value="'.$id.'" >';
    }
  ?>
  <input type="submit" value="submit_now" onclick="addSubmitData(); return false;">
</form>

<script>
   function addSubmitData()
    {
        var elements = document.getElementsByClassName("formVal");
        var formData = new FormData(); 
        for(var i=0; i<elements.length; i++)
        {
            // Get checked value
            if (elements[i].checked) {
                formData.append(elements[i].value, elements[i].value);
            }
            
        }
        var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function()
            {
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                {
                    alert(xmlHttp.responseText);
                }
                
            }
            xmlHttp.open("post", "server.php"); 
            xmlHttp.send(formData); 
    }
</script>

PHP file

//php file, expet to get an array of data containg only checked values
<?php
if(isset($_POST["test_delete"])){
 $_IDs = $_POST["test_delete"];

//Expet array of inputs values
 print_r($_IDs);
 }
?>
//Result is Undefined index: test_delete

How can I solve these issues?

1 Answer 1

1

Change

formData.append(elements[i].value, elements[i].value);

To

formData.append("test_delete[]", elements[i].value);

You've set the name of the form data parameter as the value of the checkbox by accident.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.