With php, I dynamically create a form with a variable number of "select" in it.
When user has done his selections, he hits a button that launches another php.
I now want to browse through all form elements, but have no idea on how to get the array of form elements with their respective name.
I know how to retrieve the value for a given select when I have its name, but as the select elements in the form are different each time, I cant use the name directly, but would need the array of form elements.
So, as I understand the question: form is created dynamically (with dynamic names) so you don't know what's being POST'd and what the other options were in your handler. I suggest using javascript to solve this - in the form, add an onSubmit="saveForm();" and then, in that function saveForm, you'll have to grab all the form elements and put them into some format your PHP can interpret. Pseudocode:
function saveForm(){
var outputString="[";
var theInputs=document.querySelectorAll("input, select");
for (var x=0; x<theInputs.length; x++){
outputString+="\""+theInputs.name+"\", ";
}
outputString=outputString.substring(0,outputString.length-2)+"]";
var hiddenInput=document.createElement("input");
hiddenInput.name="formNames";
hiddenInput.value=outputString;
document.body.appendChild(hiddenInput);
}
That way, a variable will be set in $_POST['formNames'] that will be equivalent to a string representation of an array containing all the names of the form elements. You can loop through that array to get the $_POST data from each one of them.
I found the solution. I can do:
foreach($_POST as $eid){
and $eid will then be every element I have in my form
Related
I'm working on a project that involves returning the id of the checkboxes chosen as well as the text in the corresponding textarea fields for those chosen checkboxes. The data is dynamically displayed and so far my jquery pull of both the checkboxes and textareas work:
var noteList = $("textarea[name='revokeNotes']").map(function(){
return this.value;
}).get().join();
var revokeList = $("input[name='revoke']:checked").map(function(){
return this.id;
}).get().join();
but I'm getting back all of the notes fields and I'm uncertain how to best iterate through them to find the proper notes as their ids aren't sequential but rather based on their id in the table they are being pulled from. The last version of the display code is below:
<td><textarea name=\"revokeNotes\" id=\"".$v["id"]."\" cols=\"30\"rows=\"3\">".$v["notes"]."</textarea></td>
<td><input type=\"checkbox\" id=\"".$v["id"]."\" name=\"revoke\" value=\"".$v["id"]."\" /></td>
Is there a way to reach my goal from this state or should I be using another jquery function, similar to .map()? I thought about using the id field from the checkboxes to iterate through the selected notes and pushing them into an array but I'm not sure 1) if that will work and 2) how to do that.
I need the data back in some form either an array or something I can explode on in php to create an array as I'm passing one value in ajax as there is no set maximum or minimum number of rows that will be displayed per user. Map was working until I threw some commas at it. Extra points for that.
var noteList = $.map(
$("textarea[name='revokeNotes']").filter(function() {
return $(this).closest('td')
.next('td')
.find('input[type="checkbox"]')
.is(':checked');
}), function(el) {
return el.value;
}).join();
adeneo's answer is great, I'd just propose the following improvements:
If possible use class selectors (like '.revoke-notes-area') since those are faster than DOM + attr selectors
Assuming this is a table and there is one textarea checkbox combo per row, you can traverse the tree to the closest <tr> a decouple the JS from depending that the checkbox comes after the text area in the DOM.
var filterMethod = function() {
$(this).closest('tr').find('.revoke-checkbox').is(':checked');
};
var mapMethod = function(el) {
return el.value;
};
var nodeList = $.map($('.revoke-notes-area').filter(filterMethod), mapMethod);
There's no reason you cannot or should not put the filter and map methods inline, I just split them out into variables so it's easier to read here.
You can check out my codepen here: http://codepen.io/aaron/pen/eIpby.
This question follows from my previous question counting the rows in html table using php.
Since I got no working solution, I want to try a new way but dont know how to implement it.
I assign unique ID to each dynamic row added using Javascript. So the count variable in Javascript stores the number of rows present in HTML table. When i submit the form, it is processed by savedata.php. Is it possible to automatically pass the Javascript variable count to savedata.php each time the form is submitted.
Following is a short version of my Javascript file that is used to create unique IDs for elements of dynamically created rows.
var count=2;
function addRow()
{
var table=document.getElementById("studenttable");
var row=table.insertRow(-1);
var cell15=row.insertCell(14);
var ipt8 = document.createElement('input');
ipt8.setAttribute("type", "hidden");
ipt8.id = "text" + count;
ipt8.name = "htmlrow[]";
ipt8.value = count;
cell15.appendChild(ipt8);
count++;
}
Each time a new row is added, count increments, so just passing it to the PHP file will allow to get the number of rows in HTML table. I want to do it automatically each time the form is submitted.
Add this inside your form..
<input name="NumRows" id="NumRows" type="hidden" value="0"/>
And then modify your JS to update the value...
document.getElementById("NumRows").value = count;
Then, in your PHP you can do...
$NumRows = $_REQUEST['NumRows'];
Note that if for some reason NumRows isn't passed with the form (unlikely here but possible elsewhere) then you should do this in PHP...
$NumRows = isset($_REQUEST['NumRows'])?$_REQUEST['NumRows']:0;
Which means "If $_REQUEST['NumRows'] is set, use it, otherwise set $NumRows to 0"
I would suggest never use $_REQUEST, use $_POST for post method forms. If you use $_REQUEST you have no guarantee that the data came from the post data, which leads to security holes in your script. So better use
$NumRows = $_POST['NumRows'];
to access the count value in PHP
Go for Ajax call. Each time when submit button is clicked make an ajax call and send the required data to the any php page.
here go through these links and they will definitely gonna help u
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/
Basically I am creating a number of rectangles using jQuery and adding these to the DOM e.g.
var divElement = jQuery('<div/>').attr({
'class': 'ui-widget-content resizable'
});
I am then allowing the user to fill out input fields for the selected rectangle e.g. name, width, height. This data is currently being added to each element via .data method.
Once the user has created all their elements along with their associated meta data, I would like them to submit the page so I can do some server side scripting in PHP.
Just wondering what the best way is to submit this data - as I understand it, I could dynamically create form elements or use the jQuery.post method.
Please can anyone advise on the best method (perhaps a different one altogether) and any tips on how to set this up e.g. using [] brackets in the name of each element to create arrays etc..
A good way will be to construct an object, or array, and fill it with all the data you wish to save. and then send it to your server using $.post() for storage.
var data = new Array;
data['height'] = 100;
data['width'] = 200;
$.post('save.php', data, function(result){
// test if successful and carry on
});
source: http://api.jquery.com/jQuery.post/
I am building a Web App.
At some point a user needs to input data to a form.
This form has several text fields and DropDownLists.
One of the DDLs is dependent on its previous DDL.
What happens is that when the user selects a value from the first DDL, the second DDL should load data from the database that are related to the selected value of the first DDL.
Up to this point I've implemented only PHP and JS, ( no AJAX, jQuery or anything else ) for handling most of my problems.
I'd like to know how to populate the 2nd DDL from the database after an item on the first DDL was selected.
Any help would be appreciated. Thank you!
Here's an example:
http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/
Google is your friend :)
Ajax is your best bet.
this will help
If the data in the second drop-down is dependent on the data in the first, then you will have to load the values of the second dropdown into a javascript object, like so:
// Given the options in the first dropdown are: "foo", "bar", and "baz"
var secondData = {
foo: ['lorem', 'ipsum'],
bar: [1,2,3],
baz: []
}
Add a 'change' event to the first dropdown, and given the value of that dropdown, load the contents of the second dropdown with the values contained in the secondData object.
If you're comfortable using jQuery (which I would highly recommend), something like this should do:
$("#dropdown").on("change", function() {//change [dropdown] to the actual ID of your dropdown
var selected=$(this).find("option:selected").val();//assuming your dropdown has a value to send, otherwise use text()
$.get("options.php?selected="+selected, function(data) {
var options=data.split("\n");
var newSelectHTML="<select name=\"whatever\">\n";
for (var i=0;i<options.length;i++) {
newSelectHTML+="<option>"+options[i]+"</option>";
}
newSelectHTML+="</select>";
$("#form").append(newSelectHTML);//again, change [form] to the correct ID.
}
}
This code simply gets the value of the currently selected option of the DDL with the ID "dropdown" (change as necessary) and sends it to PHP file options.php in $_GET["selected"];. Assuming that file then outputs a list of options separated by a new line (\n). The JavaScript then takes that, splits it by line, loops through the options, and creates the HTML for a new DDL and appends that to element ID form. No error handling is there, but that, as they say, is an exercise for the reader. Whatever is returned is in the variable data.
I've done some reading on AJAX, and would like to create a listbox, that controls what is displayed in a separate textbox located within the same form. The backend of the website is handled in php, and the possible values and whatnot is stored within the MySQL database via php. What's the best way of obtaining the listbox values as well as the textbox values, and if your answer is JS, how do I create multiple selects in JS?
Well this is really a wide theme question.
My approach would be to create a listbox with php and put an onchange event that will call an ajax with value parameter, that ajax call will fill textbox.
You should use jquery, read some documentation here http://docs.jquery.com/Main_Page
multiple select listbox
<select id="choices" multiple="multiple" .. >
If you were using jQuery you could do something like:
$("#choices").change(function() {
var choices = {};
$("#choices option:selected").each(function() {
choices[this.id] = $(this).val();
});
$.post("http://example.com/choice_handler.php", choices, function(content) {
$("#textarea").val(content);
});
});
choice___handler.php would look at $_POST to retrieve the id/value pairs and produce content that would be returned and then assgned as the value of a textarea.
Note: i haven't tested/debugged any of this - just some code sketching here