JQuery / PHP Help

Soldato
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
Hi,

I've come across a small problem in a project I'm working on. The project requires me allow the user to add a com pany details via a form and add unlimited clients for that company.

I came across useful article - http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/ - that allows the user to generate a new form value dynamically.

In this tutorial he uses an array for fields field names to make it possible to grab these submitted values. In opne one his comments he says:

The idea of naming this way (name=”txt[ ]”) is to simplify processing in the server-side code (e.g. insert to DB).
So in the server-side code, say PHP, u need to write something to count the elements of $_POST[’txt’] array. Then, using the value u need to construct a while or for loop to process the array, which will be accessible through $_POST[’txt’][0], $_POST[’txt’][1], $_POST[’txt’][2]…

Can some please give me an example in PHP how I loop through these posted values?

Thanks
 
Associate
Joined
5 Oct 2008
Posts
1,486
Can you explain a bit clearer what you are doing, i think ajax would work fine if i have the right picture.
 

Pho

Pho

Soldato
Joined
18 Oct 2002
Posts
9,324
Location
Derbyshire
If you just want to read the array..

PHP:
foreach ( $_POST['txt'] as $key=>$value )
{
	echo $key . " = " . $value;
	echo "<br />";
}
 
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
If you just want to read the array..

PHP:
foreach ( $_POST['txt'] as $key=>$value )
{
    echo $key . " = " . $value;
    echo "<br />";
}

I think that's it, will have a go tomorrow.

But have just had a thought. I could submit the form, have its action to the page name and have a link at the bottom saying something like "I'm done adding items".
 
Soldato
Joined
26 Dec 2003
Posts
16,522
Location
London
Can some please give me an example in PHP how I loop through these posted values?

Thanks

<input type="text" name="foo[]" />
<input type="text" name="foo[]" />
<input type="text" name="foo[]" />
<input type="text" name="foo[]" />

PHP:
<?php

// print the value of the second text input above
echo $_POST['foo'][1] . "\n";

// print the value of the fourth text input above
echo $_POST['foo'][3] . "\n";

// loop through and print the values of all of them.
foreach ( $_POST['foo'] as $foo ) {
    echo $foo . "\n";
}

?>
 
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
Thanks for the replies. Rob's code works for lops through a single hidden field.

How would I loop through pairs of values - so say I added pairs of hidden fields? I've amened the code slightly to add two hidden fields. How would I loop through these to display the values (is this the equivalent of a multidimensional array?).

I think I'm half way there as I named both hidden fields as 'txt[]' - however I obv. get two arrays returned :( Doing a print_r gives (say i enetered text1 into box 1 and text2 into box 2):

PHP:
Array
( 
    [0] => text1     [1] => text2 
) 
Array 
(     
[0] => text1     [1] => text2 
)

Thanks
 
Last edited:
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
From my above post I probably didn't explain myself too well :) What I have is as follows, so when I check the 'Make A File Input' link a new pair of fields are added:

32397002.jpg
 

Pho

Pho

Soldato
Joined
18 Oct 2002
Posts
9,324
Location
Derbyshire
PHP:
<?php
	// Form has been posted
	if ( $_POST['name'] ) {
		// Loop through all inputted names (we could use urls too)
		for ( $i=0; $i<count($_POST['name']); $i++) {
			// Get the name and url parameters based on array index
			$name = $_POST['name'][$i];
			$url = $_POST['url'][$i];
			
			// Build submitted info
			$data .= sprintf("<li>Name: %s, Url: %s</li>", $name, $url);
		}
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<meta http-equiv="Content-Language" content="en-us" />

		<title>Suarve</title>
		
		<style media="all" type="text/css">
		body {
			font-family: verdana;
			font-size: 10px;
		}
		fieldset {
			border: 0;
			margin: 5px;
		}
		fieldset legend {
			font-weight: bold;
			margin-bottom: 1px;
		}
		fieldset fieldset {
			border: 1px solid #ccc;
			width: 430px;
			padding: 10px;
		}
		fieldset fieldset input {
			
		}
		</style>
	</head>

	<body>
		<form method="post" action="">
		<?php if (isset($data)) : ?>
		<h1>Submitted:</h1>
		<ol>
			<?=$data?>
		</ol>
		<?php endif ?>
		
		<fieldset>
		<legend>Websites</legend>
			<?php for ($i=1; $i<=4; $i++) :?>
			<fieldset>
				<legend>Website <?=$i?></legend>
					<label>Site Name: <input class="name" name="name[]" /></label>
					<label>Site Url: <input class="url" name="url[]" /></label>
			</fieldset>
			<?php endfor; ?>
			<fieldset>
				<legend>Finish</legend>	
				<input type="submit" value="Go" />
			</fieldset>			
		</fieldset>
		</form>
	</body>
</html>

Done ;).
 
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
PHP:
<?php
    // Form has been posted
    if ( $_POST['name'] ) {
        // Loop through all inputted names (we could use urls too)
        for ( $i=0; $i<count($_POST['name']); $i++) {
            // Get the name and url parameters based on array index
            $name = $_POST['name'][$i];
            $url = $_POST['url'][$i];
            
            // Build submitted info
            $data .= sprintf("<li>Name: %s, Url: %s</li>", $name, $url);
        }
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="en-us" />

        <title>Suarve</title>
        
        <style media="all" type="text/css">
        body {
            font-family: verdana;
            font-size: 10px;
        }
        fieldset {
            border: 0;
            margin: 5px;
        }
        fieldset legend {
            font-weight: bold;
            margin-bottom: 1px;
        }
        fieldset fieldset {
            border: 1px solid #ccc;
            width: 430px;
            padding: 10px;
        }
        fieldset fieldset input {
            
        }
        </style>
    </head>

    <body>
        <form method="post" action="">
        <?php if (isset($data)) : ?>
        <h1>Submitted:</h1>
        <ol>
            <?=$data?>
        </ol>
        <?php endif ?>
        
        <fieldset>
        <legend>Websites</legend>
            <?php for ($i=1; $i<=4; $i++) :?>
            <fieldset>
                <legend>Website <?=$i?></legend>
                    <label>Site Name: <input class="name" name="name[]" /></label>
                    <label>Site Url: <input class="url" name="url[]" /></label>
            </fieldset>
            <?php endfor; ?>
            <fieldset>
                <legend>Finish</legend>    
                <input type="submit" value="Go" />
            </fieldset>            
        </fieldset>
        </form>
    </body>
</html>
Done ;).

Excellent! Can adapt that easily to add as many extra fields as possible.
 

Pho

Pho

Soldato
Joined
18 Oct 2002
Posts
9,324
Location
Derbyshire
As long as you can keep outputting the bits between:

<?php for ($i=1; $i<=4; $i++) :?>
and
<?php endif ?>

You should be able to add as many as you want (unless you need hundreds of thousands :o).
 
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
Just in case anyone cares I just found a much better way of adding elements dynamically. Instead of typing all the html you want to append you could use clone() - a lot neater. E.g. for adding a new table row.

Code:
    var inputcount = 0; 
    $('#add-order-item-link').click(function(){
            inputcount += 1;
            $('#orders').append($('#orders tr:last').clone());
    });
 
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
Have run into a slight problem :( I'm trying to get pho's code to work with checkbox values. I have a simple checkbox with a value of 1 E.g.

Code:
<input type="checkbox" name="VAT[]" value="1" />

TO get this value I'd use the following within the foreach lop:

PHP:
$orderItemVATYorN = $_POST['orderItemVATYorN'][$i];

However, I'm not getting the expected value back each time. Am I missing something?
 
Associate
Joined
30 Dec 2005
Posts
415
With checkboxes you'll basically get an array returned of any checkboxes that have been ticked. If a checkbox hasn't been ticked it won't appear in the array. To distinguish between the checkboxes give each one a unique id.


E.g.
Code:
<input type="checkbox" name="VAT[]" id="check_1" value="1" />
<input type="checkbox" name="VAT[]" id="check_2" value="1" />

Would return
$_POST['VAT'] = array {
	['check_1'] = 1
	['check_2'] = 2
}

So simply do a foreach loop through the array to access each of the elements..

Hth!
 
Soldato
OP
Joined
8 Oct 2005
Posts
4,185
Location
Midlands, UK
With checkboxes you'll basically get an array returned of any checkboxes that have been ticked. If a checkbox hasn't been ticked it won't appear in the array. To distinguish between the checkboxes give each one a unique id.


E.g.
Code:
<input type="checkbox" name="VAT[]" id="check_1" value="1" />
<input type="checkbox" name="VAT[]" id="check_2" value="1" />

Would return
$_POST['VAT'] = array {
    ['check_1'] = 1
    ['check_2'] = 2
}
So simply do a foreach loop through the array to access each of the elements..

Hth!

This is a single checkbox though. I'm looping through posted values using phos code:

PHP:
for ( $i=0; $i<count($_POST['name']); $i++) {
            // Get the name and url parameters based on array index
            $name = $_POST['name'][$i];
            $url = $_POST['url'][$i];
            
            // Build submitted info
            $data .= sprintf("<li>Name: %s, Url: %s</li>", $name, $url);
        }

and the checkbox is part of the post E.g $_POST [chkBox'][$i].
 
Back
Top Bottom