views:

181

answers:

6

The form that will be submitting the data will have somewhere between 10 and 100 values being sent to the PHP file. The number of inputs is stored in a variable called count within my javascript function but I don't know how to transfer its value to my PHP file.

Another idea I had was to have a while loop that detected a null value and to have a counter within the while loop to keep count.

How should I handle this?

+1  A: 

No need to submit the count. You can just submit your dynamic number of values as an array. You can use the PHP array notation in your name attributes:

Input 1: <input type="text" name="myvar[]" />
Input 2: <input type="text" name="myvar[]" />
...
Input n: <input type="text" name="myvar[]" />

On the PHP side, $_REQUEST['myvar'] will be an array.

Asaph
+1  A: 

I think there might be a more "correct" way to do this, but what I would do (without knowledge of a better way) is have a hidden form element something like

<input id="hidden_count" type="hidden" name="count" value="" />

And then have a function called onsubmit that sets this value and returns true to tell the form to continue

(with jQuery)

function onSubmitFunc(){
  $('#hidden_count').val(count);
  return true;
}

I'm sure there's a more elegant solution, but that should work for what you need.

Chris Thompson
A: 

If you have access to Javascript, the easiest by far would be to turn your data into JSON on the client side, send it to the server as a single string variable, and use json_decode on the server to get the properly formatted value back. You can react to the submit event on your form to have the Javascript compute the JSON before the data is sent.

Otherwise, you can have the Javascript output the number of fields to a specific hidden variable within your form. The server can then read that value, and look for the data by key in its input.

Victor Nicollet
A: 

Without knowing more about your implementation, I would suggest the latter of your two options: use PHP to loop through your $_POST array and count the valid values you have. This is the best option as it is more secure and reliable.

Lucas Oman
A: 

I guess you use javascript for creating the additional input element, if you just name ascending, you could use count to loop through the $_POST data. Or else use a hidden element form for counting the new input elements and post it, that way you have the correct number, and know how long you should be count.

zpon
A: 

Maybe I am not getting this, but if count in your JS file corresponds to the number of input elements in the form which is send to your PHP file, why not count() them on the serverside. The data will be in the $_POST array.

Gordon