LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Arrays, checkboxes in javascript & PHP (https://www.linuxquestions.org/questions/programming-9/arrays-checkboxes-in-javascript-and-php-252232/)

Elijah 11-07-2004 07:55 PM

Arrays, checkboxes in javascript & PHP
 
This function here is supposed to fill up $mchecked with values from checkboxes that are marked as checked .... problem is that $mchecked gets all values from the checkboxes, including the unchecked ones...

Code:

function poll_mlist(){
<?
                $query="SELECT maillist from maillisthead";
                $data=pg_exec($connect,$query);
                $rows=pg_numrows($data);
                if($rows>0){
                        for($i=0; $i < $rows; $i++){
                                $result=pg_result($data, $i, "maillist");
                                //The name of each checkbox is fetched from the database
?>
                                if(document.frm_asti_email.<?=$result?>.checked=
=true){
                                        <?
                                        $mchecked[] = $result; //add the value to array if 'true'
                                        ?>
                                        alert("<?=$result?> is checked"); //just for testing
                                }
<?
                        }
                }
                foreach($mchecked as $key => $value){
                        echo "$value\n"; //just for testing
                }
?>
}

Help? :study: :scratch:

CroMagnon 11-07-2004 08:52 PM

You are mixing up javascript and PHP, and what they each do. Here is the process:

1. Browser asks server for PHP page
2. Server executes PHP and sends all output to the browser
3. Browser parses HTML and executes javascript

So, look at this piece of code, with my additions:
Code:

(PHP)<?
(PHP)    for($i=0; $i < $rows; $i++){
(PHP)        $result=pg_result($data, $i, "maillist");
(PHP)?>
(JS)          if(document.frm_asti_email.<?=$result?>.checked==true){
(PHP)        <?
(PHP)            $mchecked[] = $result; //add the value to array if 'true'
(PHP)        ?>
(JS)          alert("<?=$result?> is checked"); //just for testing

Can you see what will happen? When the PHP runs, it knows nothing about javascript's "if" statement - it just adds that JS code to the output, and the "$mchecked[] = $result" line will be run every time throughout the for loop. PHP runs through the loop and:
1. sets $result
2. outputs the if() line (with the value of $result)
3. adds $result to the $mchecked array
4. outputs the alert command.

Is there a reason you're trying to do so much with Javascript? Processing form input is what PHP does, not to mention how unreliable Javascript is from browser to browser. Just submit the form and have your PHP code check the $_POST variable. Sort of like this:

Code:

for ($i=0; $i < $rows; $i++) {
    $result = pg_result( $data, $i, "maillist" );
    if ( $_POST[$result] == "on" ) {
        $mchecked[] = $result;
    }
}

<religion>
Just say no to Javascript. It is the single biggest reason so many web pages suck.
</religion>

Elijah 11-07-2004 09:08 PM

Hmmm... ah I get it now. PHP isn't aware of that if statement so the variable now fetches all of it. thanks for clearing that up.

The code I'm debugging right now is littered with both php & javascript, it's isn't really my code and I'm not that familiar with both languages. So I guess somehow I'm forced to use javascript 'cause there are some variables here that are javascript ... I can't really convert it to php cause I just learned that both are different (client/server side).

I'll try $_POST, maybe read up on it a bit...

Elijah 11-08-2004 12:33 AM

Ok, just tried it:

Code:

function poll_mlist(){
<?
                $query="SELECT maillist from maillisthead";
                $data=pg_exec($connect,$query);
                $rows=pg_numrows($data);
                if($rows>0){
                        for($i=0; $i < $rows; $i++){
                                $result=pg_result($data, $i, "maillist");
                                if( $_POST[$result] == "on"){
                                        $mchecked[] = $result;
                                }
                        }
                }
?>
                alert("<?=$mchecked?>");
}

but $mchecked's empty, how could that be? :scratch:

CroMagnon 11-08-2004 03:28 AM

Are the checkboxes part of a form, and the form submitted to this script?

Elijah 11-08-2004 08:25 PM

The form calls a different script that generates an array of those checkboxes.
<?
disp_mlist();
?>

disp_mlist.php:
Code:

for loop --- {
?>
<input type=checkbox name="<?=$result?>" value="<?=$result?>">.....
<?
}


CroMagnon 11-08-2004 09:16 PM

When you submit a checkbox, the PHP var is either set to nothing (checkbox turned off) or the 'value' you set in the HTML - so instead of testing against "on" (the default), you should maybe test against $result:
Code:

if( $_POST[$result] == $result ){
    $mchecked[] = $result;
}


Elijah 11-08-2004 09:36 PM

Hmm... I've tried that but still no result, but after trying out:

Code:

if( $_POST[$result] == false){
                $mchecked[] = $result;
          }

after seeing all the unchecked values again I suspected something, I checked the source from my browser and I got this:

Code:

<html>

<head>

<script language="javascript">

function poll_mlist(){
                alert("mchecked: Array");
}

getting warm, I have a feeling the reason I didn't get any results using 'on' is because php fetched the results too soon before the user could click on submit() and check the checkboxes.

I should transfer the function somewhere ... I'm beginning to hate javascript :scratch:

CroMagnon 11-08-2004 10:13 PM

Quote:

php fetched the results too soon before the user could click on submit() and check the checkboxes.
PHP doesn't fetch anything. What happens is like this:

Imagine I have a form with two text inputs
Code:

<form action="test.php" method="post">
<input name="username">
<input name="password">
<input type="submit">
</form>

When I fill in those fields ('bob' and 'password') and click the submit button, my browser sends a request a bit like this:
Code:

http://server/test.php?username=bob&password=password
(this is not 100% accurate, but it is the basic concept - the important point is that the browser sends the data to PHP when you say so, PHP does not come and get the data from your computer)

When the webserver starts up PHP to process the page, it passes those two variables through in the $_POST variable (i.e $_POST["username"] and $_POST["password"]). There is another variable called $_GET, if you use method="get" on your form instead of method="post", so this is one thing you could check.

For more debugging, when you use PHP to print an array as if it were a string, it just prints "Array", which is why your alert statement is probably not showing you what you want to see. Try
Code:

print "Mchecked is: "
print_r( $mchecked );
print "POST array is: "
print_r( $_POST );
print "GET array is: "
print_r( $_GET );

These will probably help you to see what is going wrong, and where your checkbox values are.

Elijah 11-09-2004 02:33 AM

Thanks for explaining to me ... and those print_r's were very useful.

Re: empty $mchecked:

Still nothing, if( $_POST[$result] = "on/off/$result") doesn't give me any results. The only time it gave the right values correctly is when I used the if(document.frm_asti_email.<?=$result?>.checked==true) condition ... but It'll be tricky going back there again cause I need to pass the javascript array results to a php one and as I'm told, that's just not possible.

CroMagnon 11-09-2004 04:14 AM

Did $_POST or $_GET contain the stuff you wanted? Did you remove the quotes when you tested the values against $result? I assure you, PHP is built to do this, as long as everything is built correctly (i.e the checkboxes are contained within the form that is being submitted). Javascript is actually counter productive if you want the server to know which boxes are selected.

Elijah 11-09-2004 09:07 PM

strangely no, $_POST & $_GET didn't contain any values, and yes I did remove the quotes.

Here's how I analyzed how the entire page works:

<php> includes
<js> contains functions, checks for blanks
<js> if all is ok, document.form.submit()
<php> if save == 1? get all values & insert
<php> call script for checking checkboxes
<html> form, action="test.php?save=1" , post
<php> generate checkboxes
<html> submit button, go to functions

The start of the script has the includes, then javascript functions for checking the forms for human error. Php will then check if $save==1, if not continue with the script ... Checkboxes are generated using a different script and then finally the submit button.

If the submit button is checked, the form will let save=1. The page refreshes with a save=1 in the address, then it'll check if save==1 again, if it is then the script will now insert the details on the database. This is also where the checkboxes come in, all checked ones will have their values saved.

CroMagnon 11-09-2004 09:52 PM

Sounds like you are either using register_globals, or an older version of PHP (or both). register_globals is a security issue, and the $_POST and $_GET variables were introduced to counteract this.

Try changing the if section again, but this time to:
Code:

if( isset( ${$result} ) ){
    $mchecked[] = $result;
}

and see if you are more successful.

The thing is, if register_globals is being used, form-posted parameters are stored directly in variables, not in the $_POST array. That is, if you have a textbox called "chuck", your script will receive the contents in a variable called $chuck.

I would like to recommend turning off register_globals, but it's very likely the whole site has been written to take advantage of this old behaviour.

Elijah 11-10-2004 12:23 AM

Ok, I've tried to print_r each ${$result}

Code:

for($i=0; $i < $rows; $i++){
                                $result=pg_result($data, $i, "maillist");
                                print_r("this is result: ${$result} :");
                                if( isset(${$result}) ){
                                        $mchecked[] = $result;
                                }
                        }

I hate to say it but it's still empty :o , I'm running out of options :scratch: Hmmm... :study:

CroMagnon 11-10-2004 04:35 AM

OK, time to try creating a new file. Set up a file called test.php that looks like this, and test it out:
Code:

<html>
<body>
<?php
echo "POST is";
print_r( $_POST );
echo "testbox is ".$testbox;
?>
<form action="test.php" method="post">
<input type="checkbox" name="testbox">
<input type="submit">
</form>
</body>
</html>

Load it up in the browser, tick the box and hit submit and see what comes back.


All times are GMT -5. The time now is 11:39 AM.