Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Php - Get value checkbox when checked In php

Posted on 2017-03-24
14
Medium Priority
?
640 Views
Last Modified: 2017-04-14
<!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
Comment
Question by:Soumaya Hachem
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +2
14 Comments
 
LVL 9

Expert Comment

by:Jim Riddles
ID: 42062984
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
 
LVL 4

Expert Comment

by:Peos John
ID: 42062990
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
 

Author Comment

by:Soumaya Hachem
ID: 42063009
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
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 42063020
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
 
LVL 9

Expert Comment

by:Jim Riddles
ID: 42063024
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 42063042
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
 

Author Comment

by:Soumaya Hachem
ID: 42063209

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

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 42063299
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
 
LVL 59

Assisted Solution

by:Julian Hansen
Julian Hansen earned 1000 total points (awarded by participants)
ID: 42063367
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
 

Author Comment

by:Soumaya Hachem
ID: 42063403
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
 
LVL 59

Expert Comment

by:Julian Hansen
ID: 42063602
still not clear on what you want to do.

You have a page with checkboxes.

A checkbox is clicked - what happens next?
1
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 42063614
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
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1000 total points (awarded by participants)
ID: 42065474
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
 
LVL 9

Expert Comment

by:Jim Riddles
ID: 42092887
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question