Php - Get value checkbox when checked In php

Soumaya Hachem
Soumaya Hachem used Ask the Experts™
on
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<form action="page.php" method="post"><input type="checkbox" name="courses[]" value="photoshop"/>
<input type="checkbox" name="courses[]" value="php"/>

<input type="checkbox" name="courses[]" value="html"/>

<input type="checkbox" name="courses[]" value="javascript"/>

</form>

<?php

foreach($_POST['courses'] as $values)
{
echo $values;
}
?>

</body>
</html>

Open in new window




Notice: Undefined index: courses in C:\xampp\htdocs\testCheckbox\checkbox.php on line 18

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\testCheckbox\checkbox.php on line 18
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jim RiddlesPrepress/OMS Specialist

Commented:
You are referencing values that do not exist when that page loads.  PHP is server side, not client side.  Only page.php, the target of your form will contain a value for the courses array.  Even then, you should wrap the code that references the courses array in an isset check, like so:

<?php

if (isset($_POST['courses'])
{
  foreach($_POST['courses'] as $values)
  {
    echo $values;
  }
}
?>

Open in new window


By doing that, you will prevent PHP from throwing an error in case the variable has not been set.
use isset fuction to check if the POST has values, Pleas check the below code

<?php

if (isset($_POST['courses'])) 
{ 
	foreach($_POST['courses'] as $values)
	{
		echo $values;
	}
}
?>

Open in new window

Author

Commented:
It shows me nothing, try it


<!DOCTYPE html>
<html>
<head>
      <title></title>
</head>
<body>
<form action="#" method="post"><input type="checkbox" name="courses[]" value="photoshop"/>
<input type="checkbox" name="courses[]" value="php"/>

<input type="checkbox" name="courses[]" value="html"/>

<input type="checkbox" name="courses[]" value="javascript"/>

</form>

<?php

if (isset($_POST['courses'])) 
{ 
	foreach($_POST['courses'] as $values)
	{
		echo $values;
	}
}
?>

</body>
</html>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Of course it shows you nothing!  It's working exactly the right way.  I think we have a fundamental misunderstanding of the timeline of HTTP request and response.  It's too much to write in an answer to this and your other question, but we have an article here that explains it.
https://www.experts-exchange.com/articles/11271/Understanding-Client-Server-Protocols-and-Web-Applications.html

If you're new to PHP and want to learn the language and associated technologies, this article can help you find well-vetted learning resources, and perhaps more importantly, it can help you avoid all of the bad, incompetent, outdated and insecure examples that litter the internet!
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
Jim RiddlesPrepress/OMS Specialist

Commented:
Refer to my original answer.  The PHP code that is trying to access the courses array is in checkbox.php, however your form is set to send the data to page.php.  If you want to see the data, change the form target to checkbox.php, and when you submit it you will see the data.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Try it like this.  There is a "submit" button in the form, because that is how we get the information from the client browser to the server.  I removed the "page.php" from the form tag, so that the script will submit the request to itself.

You can test this on my server, here: https://iconoun.com/demo/temp_hachem.php
 
<?php // demo/temp_hachem.php
/**
 * https://www.experts-exchange.com/questions/29011455/Php-Get-value-checkbox-when-checked-In-php.html
 * https://www.experts-exchange.com/questions/29011219/Equivalence-of-serialize-in-PHP.html
 */

// IF THERE IS A POST-METHOD REQUEST
if (!empty($_POST))
{
    foreach($_POST['courses'] as $values)
    {
        echo PHP_EOL . $values;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
      <title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="courses[]" value="photoshop"/>
<input type="checkbox" name="courses[]" value="php"/>
<input type="checkbox" name="courses[]" value="html"/>
<input type="checkbox" name="courses[]" value="javascript"/>

<input type="submit" />

</form>

</body>
</html>

Open in new window

Author

Commented:

Is there a way to get the value of a checkbox without the submit button

Most Valuable Expert 2011
Top Expert 2016

Commented:
Is there a way to get the value of a checkbox without the submit button
Not in PHP, at least not in any practical sense, no.  Your client (probably a browser) must make an HTTP request to the server before PHP can even start running.

Please read the articles I linked before.  You need some more foundation information to understand this issue, and it will be easier to discuss when you have that information.

Now having said that, here is a sequence that is programmable, but terribly impractical and culturally inappropriate.  You can trigger an AJAX request to the server when the checkbox is clicked.  For that matter you could even trigger an AJAX request on a mouseover event.

What's wrong with this idea?

1. Human beings know that checkboxes on the WWW don't work this way.  Checkboxes can be checked and unchecked before submitting them.

2. You will need to have a PHP listener script on your server to listen for the AJAX request.

3. The listener script will have to be stateful, recording (at least) the IP address and user-agent that clicked the checkbox.

4. If the client unchecks the checkbox, the stateful information will have to be erased.

5. If the client visits the site, checks a checkbox, then closes the browser, what are you going to do with the stateful information?

6. How will you communicate with the client again?  How will you know that they once came to the site and clicked a checkbox?

7. A web site that makes an AJAX request on a checkbox click feels like "spooky action at a distance," and it will probably make people feel like you are trying to trick them into something.  They will go away and never come back, or report your site to Google as a potential attack site.

It's points of confusion like these that make me say you really want a submit button.  It's always easier to ride the horse in the direction he is going! :-)
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
if (!empty($_POST))
{
    foreach($_POST['courses'] as $values)
    {
        echo PHP_EOL . $values;
    }
}

Open in new window

Assumes $_POST['courses'] exists
I prefer
$courses = isset($_POST['courses']) ? $_POST['courses'] : false;
if (is_array($courses)) {
  foreach($courses as $course) {
  }
}

Open in new window


Is there a way to get the value of a checkbox without the submit button
Yes - can you explain why you would want to do this - what is your thinking around the problem?

Author

Commented:
i want that when i check a checkbox , the value of checkbox stock in a value ,  So I can change the URL.


<?php


$query = Input::get('query', '');
for($i=1; $i<=$nbPages; $i++) //On fait notre boucle
{
     //On va faire notre condition
     if($i==$pageActuelle) //Si il s'agit de la page actuelle...
     {
         echo '<span><a>  '.$i.'  </a></span>';
     }  
     else //Sinon...
     {
    echo '<span><a href="/pricefilter?query=' . $query.'&priceFilter[]='.$sq.'&page='.$i.'">'.$i.'</a></span>';
     }
}

?>
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
still not clear on what you want to do.

You have a page with checkboxes.

A checkbox is clicked - what happens next?
Most Valuable Expert 2011
Top Expert 2016

Commented:
Input::get() seems like an out-of-date version of Laravel.  The current way is described here:
https://laracasts.com/discuss/channels/laravel/how-to-use-use-inputget-globally-in-larvel-52

Are you using Laravel or another framework for your application?
Most Valuable Expert 2011
Top Expert 2016
Commented:
These sample scripts may come close enough to show you how to do this, but I sincerely hope you will not design your application to work this way.

First, the server side script.  It simply looks for a POST method request and a request variable "q" and bounces back the time of the request and the contents of the request.  Obviously it could do many more interesting things like save the request variables in a database, etc.
<?php // demo/temp_hachem_server.php
/**
 * https://www.experts-exchange.com/questions/29011455/Php-Get-value-checkbox-when-checked-In-php.html
 * https://www.experts-exchange.com/questions/29011219/Equivalence-of-serialize-in-PHP.html
 */
error_reporting(E_ALL);

// IF THERE IS A POST-METHOD REQUEST
if (!empty($_POST['q']))
{
    echo "REQUEST RECEIVED AT " . date('H:i:s');
    echo " WITH: ";
    echo implode(',', $_POST['q']);
    echo PHP_EOL;
}

Open in new window

Next, the client side script.  This uses JavaScript (jQuery) to select all of the checkboxes on the page and trap the click event.  With each click, the script collects the values of all the checkboxes that have been clicked and makes a POST-method request to the server-side script.  The response from the server is put into the "output" div.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>

<!-- demo/temp_hachem_client.php -->

<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
    $(":checkbox").click(function(){
        var values = $("input:checkbox:checked").map(function(){
            return $(this).val();
        }).get();

        $.post("temp_hachem_server.php", {q:values}, function(response){
            $("#output").html(response);
        });
    });
});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<input type="checkbox" value="a" />
<input type="checkbox" value="b" />
<input type="checkbox" value="c" />

<div id="output" />

</body>
</html>

Open in new window


You can try it here on my server:
https://iconoun.com/demo/temp_hachem_client.php
Jim RiddlesPrepress/OMS Specialist

Commented:
Although the author never clarified what his actual intent was, I believe that Ray found the meat of the issue and displayed the best solution, although Julian's comment was also helpful.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial