John Davidson

javascript - How to get values from checkboxes to php array on button click?

0 comments
Message:


I have a problem. I want to get checked values from checkboxes and add them to a php array but i have no clue on how to do it. I can do it in javascript but i want a php array and i don't know how to convert js array to php array. I am gonna use the array in next php file and search rows from database with those values. I would appreciate if anybody suggests something on how to do it as i have no clue.


while ($row = mysqli_fetch_array($search)) {
$category = $row["Category"];
echo<inputtype=\"checkbox\"name=\"category\"value=\"$category\"required/>$kategoria</input><br /><br />";
}

<a id='answer' href='questions.php'><button>Answer to questions!</button></a>

This is how i make the checkboxes and then on button click i move to the next file



My Answer:
To achieve this, you can use JavaScript to collect the checked values from the checkboxes and then pass them to the next PHP file using a form submission or AJAX request. Here's an example of how you can do it:

1. Modify your HTML to include a form element with a submit button:

html


Category 1

Category 2

Category 3






2. Add JavaScript to collect the checked values and submit the form:

javascript
document.getElementById('checkboxForm').addEventListener('submit', function(e) {
e.preventDefault();

var checkboxes = document.querySelectorAll('input[name="category[]"]:checked');
var values = Array.from(checkboxes).map(function(checkbox) {
return checkbox.value;
});

// Add the values to a hidden input field in the form
var hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = 'selectedCategories';
hiddenInput.value = JSON.stringify(values);
this.appendChild(hiddenInput);

// Submit the form
this.submit();
});


3. In your PHP file (process.php), you can retrieve the values from the hidden input field and convert them back to a PHP array:

php
$selectedCategories = json_decode($_POST['selectedCategories']);
print_r($selectedCategories);


Now, when the form is submitted, the selected checkbox values will be passed to the process.php file as a PHP array. You can then use this array to search for rows in your database.

Rate this post

3 of 5 based on 3221 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us