[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 933
  • Last Modified:

Php - Get value checkbox when checked In php

<!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
0
Soumaya Hachem
Asked:
Soumaya Hachem
  • 5
  • 3
  • 3
  • +2
2 Solutions
 
Jim RiddlesPrepress/OMS SpecialistCommented:
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.
1
 
Peos JohnPHPCommented:
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

0
 
Soumaya HachemAuthor 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

0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
Ray PaseurCommented:
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
1
 
Jim RiddlesPrepress/OMS SpecialistCommented:
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.
0
 
Ray PaseurCommented:
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

1
 
Soumaya HachemAuthor Commented:

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

0
 
Ray PaseurCommented:
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! :-)
0
 
Julian HansenCommented:
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?
2
 
Soumaya HachemAuthor 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>';
     }
}

?>
0
 
Julian HansenCommented:
still not clear on what you want to do.

You have a page with checkboxes.

A checkbox is clicked - what happens next?
1
 
Ray PaseurCommented:
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?
0
 
Ray PaseurCommented:
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
1
 
Jim RiddlesPrepress/OMS SpecialistCommented:
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.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 5
  • 3
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now