Getting all POST from clone form elements - php

Here's my little problem:
I've this code http://jsfiddle.net/marcelo066/d7ehQ/light/ which I changed from BrianGlaz's original http://jsfiddle.net/B7bgN/10/ .It clones some part from a form. My question is: how can I get this cloned values using php to store it in a mysql database? Just for enlightenment, the code from my fiddle is a part from a bigger form, which is working. So i add this clone part, and I don't know how to get the cloned values from $_POST. Any ideas?

Name your form fields as array elements:
<select name="dormitorios_name[0]"... >
And for the clones make it respectively
<select name="dormitorios_name[1]"... >
...
<select name="dormitorios_name[2]"... >
Thus in you php code you can check for
$i = 0;
do {
// save values
$i++;
} while (isset( $_POST['dormitorios_name'][$i])

Use arrays on elements attributes names.
Alter the names of the elements so that instead of name="myname" and name="myname2", name="mayname3" you have name="myname[0]" and name="myname[1]", name="myname[2]".
So that in the $_POST array you will have $_POST['myname'] as an array will al original and cloned values and not $_POST['myname'],$_POST['myname2'],$_POST['myname3'].
Depending on the way you want to hanlde that you could also have original elements with names like name="form[0][myname]" and the others like name="form[1][myname]", etc. At the end the original elements values are on $_POST['form'][0] and the others in $_POST['form'][1], $_POST['form'][2], etc.
I've made a fiddle here http://jsfiddle.net/regilero/6kd2L/1/
http://jsfiddle.net/regilero/6kd2L/1/
Where basically, appart from altering the way names are handled in the HTML part I 've altered
$(elem).attr('id', $(elem).attr('id') + newNum).attr('name', $(elem).attr('name')+ newNum);
To:
var $elem = $(elem);
$elem.attr('id', $elem.attr('id') + newNum);
var ename = $elem.attr('name');
if (ename) {
$elem.attr('name',ename.replace('form[0]','form['+newNum+']'));
}

Related

Javascript Function to populate a select menu from MySQL

I have this PHP Code which populates a select menu from a MySQL Database...
<select name="input" id="input">
<?php
$sql="SELECT * from table ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<option value="'.$result["db_field"].'">'.$result["db_field"].'</option>';
}
?>
</select>
which works perfectly fine but i need to somehow get it into a javascript function.
I have the javascript code that when you click a button it adds more text boxes and another select menu but it does not populate the data from the database in any new (added on) select menus
You can probably convert the options into JSON using json_encode (I am not a PHP programmer and dont know exact semantics of using it)
In PHP do something like:
echo '<script>var optionsJSON = '.json_encode(mysql_fetch_array($rs)).'</script>'
In javascriptn do something like (I am using jquery):
var select = $('select.classOfThisSelect');
var options = JSON.parse(optionsJSON);
for(var i = 0; i < options.length; i++)
$('option').attr({value: options[i]}).append(options[i]).appendTo(select);
optionsJSON will be the JSON string which will be globally available
You can freely use it in your Javascript function
Note: You may need to surround the json_encode with quotes
Start by converting the string of values into an array, so you have something like:
var values = ['value0','value1','value2'];
Then you can convert them to options and add them to a select element like:
function addOptions(select, values) {
for (var i=0, iLen=values.length; i<iLen; i++) {
select.appendChild(new Option(values[i],values[i]));
}
}
And call it like:
addOptions(document.getElementById('input'), values);
after the select is added to the page.
Incidentally, you don't need to add both an id and name to form controls. You must have a name for them to be submitted, the ID is unnecessary. If you get a reference to the form you can access controls as named properties of the form, so you might reference the select using:
document.forms[0]['input'];
or
document.forms[0].input;
and so on. Note that "input" isn't a good choice of control name.

How to bring a dynamically generated HTML table into a JS array?

I'm generating a 2-column HTML table from a php array as follows:
<table>
<?php
$i=0
foreach ($fullNameArray as $namePair){
echo
"<tr>
<td id='first ".$i."'>".$namePair[0]."</td>
<td id='last".$i."'>".$namePair[1]."</td>
</tr>";
$i++;
}
?>
</table>
What is the best way to explore this table in Javascript, for example to build an array that would replicate the PHP array, i.e., an array of [first name, last name] pairs.
If you want to go the old-fashioned pure-JavaScript way, you could do some simple DOM traversal.
If you add an id to the table, your life will be much easier, especially if you have (or may later add) other tables in the page.
<table id="nameTable">
...
</table>
Now you can access the table in JavaScript and store a reference to it in a variable. You will also want to initialize an empty array/list variable to hold the names later.
var nameTable = document.getElementById("nameTable");
var nameArray = [];
Next, you begin looping through the child elements of the table, each of which will be a tr (table row) element.
for (var i=0; i<nameTable.childNodes.length; i++) {
...
}
Inside that for loop you will build your list of [first name, last name] pairs. You will do this by grabbing the value of each of the two td (table data cell) children of the current row.
var dataCells = nameTable.childNodes[i].childNodes;
var namePair = [dataCells[0].innerHTML, dataCells[1].innerHTML];
That should give you a JSON array something like this (my values added):
[
["Andy", "Jackson"],
["Barry", "Obama"],
["Benny", "Franklin"],
["Georgey", "Washington"],
["Billy", "Clinton"]
]
To review, the full code would look something like this:
var nameTable = document.getElementById("nameTable");
var nameArray = [];
for (var i=0; i<nameTable.childNodes.length; i++) {
var dataCells = nameTable.childNodes[i].childNodes;
var namePair = [dataCells[0].innerHTML, dataCells[1].innerHTML];
}
NOTE: This is fun, but it is likely that the better solution, if you don't mind a hard-coded JSON array in your source code (if you've got the table there anyway it really doesn't matter), is probably to print a json_encoded array in a <script> tag straight from the PHP, like #JayBhatt suggested. It is likely the faster method, and it puts much less stress on the user's browser.
Encode your array to Json using PHP's json_encode, assign this string to a javascript variable and decode json to array using javascript...
Another way could be assign the json to a hidden input instead a javascript and later get the input value in your javascript Code.

array not working for dynamic form field

I've found most of the pieces i've needed for this form (making the fields dynamic, etc.) however now the array part of this doesn't seem to work to be able to submit correctly.
what i'm trying to accomplish:
a form with a select field that can be duplicated dynamically and then be submitted as a part of the form to it's own table. so if we add and choose three people in the one form, it submits to it's own attending table with a foreign key back to the event the form is for. had to make it dynamic because we'll never know for sure how many people will be attending said event, but it has to happen all in one form. just because it does. my boss says so.
here's my javascript for the add another field button:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the id value of the input inside the new element
newElem.children(':first').attr('id', 'attendee' + newNum).attr('name', 'attendee[' + newNum + ']');
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 6)
$('#btnAdd').attr('disabled','disabled');
});
here's what the field starts out as in the form:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<select name="attendee[1]" id="attendee1" style='float:right;margin-right:4.5%;'>
<option value=''>Please choose one...</option>
<?php
while($row_attendees = mysql_fetch_assoc($res_attendees)){
$attendee_id = $row_attendees['attendee_id'];
$attendee_name = $row_attendees['name'];
echo "<option value='".$attendee_id."'>".$attendee_name." </option>";
}
?>
</select><label style='width:100px;display:inline-block;line-height:28px;' for="attendee">Attendee</label>
</div>
I'm getting all the things to change correctly. all of the select inputs are being id'd and name'd correctly. the div is being updated the same. all of that works correctly. what doesn't is when i go to submit. here's my php:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."','".$attendee."')";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
all the tutorials i used to pull this together show this as correct. however it doesn't work. i'm only getting whatever the first dropdown is, and nothing else is populating into the array. at least that's all it shows/submits if i run the form or echo the attendee variable in the foreach statement. PLEASE HELP! :)
thanks a ton in advance.
UPDATE
I have tried a few ways discussed with another user to display the array for $_POST['attendee'], however it still just shows 1 id in the array, and not however many fields i've actually added. I've also tried removing the number from the array in the select's name attribute. so it would just be name='attendee[]' instead of name='attendee[1]' and so on. this also doesn't help any. can someone please help with why my dynamically added fields aren't being added to the array?
I put your code into a JSfiddle, here: http://jsfiddle.net/rv8Mv/1/
It looks like the selects are being added correctly. You can check by clicking the "Submit" button, which shows a data string of what will be submitted to the server.
One thing you might want to check, is to make sure you are enclosing all the select elements inside a <form> element, which you didn't include in your question.
I think your problem is in the PHP code on the server.
On the server, make sure you are receiving all the variables by using this code:
<?php
foreach($_POST as $key => $value){
error_log($key.' -> '.$value;
}
?>
Then check your error log to see the names and values for all the POST variables.
You are probably not referencing the POST variables correctly in your current PHP code.
You should change your sql to look like this:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."',".$attendee.")";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
Your attendee_id is an int column. You were wrapping the column content with single quotes, which denotes a string. This would result in your attendee_id being null if your column is defined as nullable.

php comparing value from database with one in a textbox

i have a multiple amount of text fields, the amount of text fields is due to how much data is in a database. The input for both are integers, all i want is when the values are inputted into the text fields it throws an error if the inputted data is larger than the value in the data base
for example
in a markscheme
the data inputted into the textbox is the mark given to the student and the data in the database is the maxmark for that particular question, so therefore it cannot exceed that value
so in effect i want to compare the values and if the text input value is larger than that of the one in the database it throws and error :)
If it's OK for you to rely on your users having javascript enabled, I would say the easiest is to verify the data on the client side.
You could do something like this:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="text" value="5" name="grade[123]" data-max="10" />
<script type="text/javascript">
$(function() {
$('input[type="text"]').blur(function(e) {
var $this = $(this);
var max = parseInt($this.data('max'), 10);
if (parseInt($this.val(), 10) > max) {
var name = $this.attr('name');
console.error('Value ' + $this.val() + ' in field "' + name + '" exceed its maximum value of ' + max);
$this.focus();
}
})
});
</script>
</body>
</html>
Or you could replace all this logic with simple HTML5 number fields:
<input type="number" value="5" name="grade[123]" min="0" max="10" />
Obviously, one should never trust their users. You should always double-check the data on the server side and notify users about the possible errors.
This is something you could do:
<?php
if (!empty($_POST)) {
// ...
// fetch max values from the database in the form of
// array(
// id => [max],
// );
$maxValues = array( /* ... */ );
// prepare some error array if you want to show errors next to individual fields
$errors = array();
// ...and then loop through the posted array
foreach ($_POST['grades'] as $id => $value) {
// make sure the submitted value is an integer
if (!ctype_digit($value) && !is_int($value)) {
$errors[$id] = 'Invalid value';
continue;
}
if ((int) $value > (int) $maxValues[$id]) {
$errors[$id] = 'Value cannot be more than ' . $maxValues[$id];
}
}
// assign errors to the view or do whatever is required in your script
// ...
}
It shouldn't be difficult to understand what I was doing there. Basically, have one reference array and the data array to verify against (note: your HMTL field names must have the square brackets in them to act as arrays). And then just loop through the submitted data and verify against the reference array.
Just like Ryan Kempt said, there are lots of ways you could do it and without a specific example of your data structure or how you want the errors/exceptions to be presented to the user, it's quite difficult to write you an exact code.
Nevertheless, have a look at our suggestions and start from there. And best of luck!
Lots of ways to tackle this but pretty much with everything you can use a javascript solution for client-side checking and PHP for server-side... for front-end you could query the DB and output the information in hidden inputs and then compare the value of the textbox to the value of the matching hidden div using a javascript solution.
When the textbox loses focus you could use AJAX and query what's in the textbox against your database.
When the user submits the form finally you should also then verify the numbers again against the daabase using PHP.
So... would need more information but the above steps are what you're going to want to do - how you do them is up to you and if you need specific help after trying the above methods and running into issues, we'd love to help you more.
Happy coding and best of luck!

Dynamically set input values in HTML with non-specific names

Long time lurker, first time poster.
I have a page that can dynamically (with Javascript / jQuery) add key => value pair inputs to a form. These fields need to be returned to PHP as an array for processing, so the keys are all named "complete_fields[]" and the values are all named "complete_values[]". Now here is my problem. If I fill in some inputs then want to add another key => value pair, I can click on a button and the Javascript will work its magic. However, because the HTML "value=" part is not filled out, the inputs I have already filled out are erased by the Javascript. So my question is this: How can I dynamically set the HTML value of the input with JS, even though all the inputs are named the same? If this is not possible, how can I add to the end of a div without erasing all the rest of the HTML?
Here is the Javascript add input code:
function addCompleteField() {
var oldhtml = $("#complete_fields").html();
var newrow = '<tr><td><input type="text" name="complete_fields[]" > => <input type="text" name="complete_values[]" ></td></tr>';
$("#complete_fields").html(oldhtml+newrow);
}
Rather than mucking around with HTML, just clone the elements using jQuery's clone method:
function addCompleteField() {
var table = $('#complete_fields'),
lastRow = table.find('tr').last(),
newRow = lastRow.clone(true);
newRow.find('input').val(''); // blank the new row's input elements
newRow.appendTo(table);
}

Categories