I am working on a system that allows the user to preview the result as an HTML table. I put a checkbox in the leftmost cell that is checked by default. Should the user uncheck any row, that row will not appear in the final product.
Submitting this form, which as of now is only these checkboxes, with just HTML yields a 404 error. Removing or significantly reducing the number of the checkboxes fixes this problem.
I implemented name = "checkbox[]" instead of name = "checkbox1", name = "checkbox2", ... to see if that would solve the problem; it didn't.
I also tried serializing and submitting the form data with jQuery post and PHP, which still gives me the 404. I tried submitting the form using AJAX and jQuery to the same effect.
I'm not sure if submitting the data through $_SESSION will help. I don't know how I would implement this in my use case.
How can I submit many inputs without causing an error?
EDIT: A hopefully minimal, complete and verifiable example (using only HTML, since none of the scripting methods produced a better result):
<?
print "<form action = 'target.php' method='get'>";
for( $i = 0 ; $i < 200 ; $i++ ){
print '<input type="checkbox" name="chk[]" checked /> Checkbox ' . $i . '<br />';
}
print '<input type="submit" value="Submit">';
?>
This produces the same error for me: 404.
Replace <form action = 'target.php' method='get'> with <form action = 'target.php' method='post'>
You use the GET method, which means that the input names and values will be sent in the URL. If you send data to the server, always use POST.
If you have 100+ inputs, then the URL gets too long
Related
Basically, it's a form that needs specific information, "Tamanho"/"Tamanhos" means "size"/"sizes", which I have a list of acceptable sizes that goes from 8 to 30 that are registered in a database (to make it easier to add more acceptable sizes if needed), the user should be able to chose many "sizes" and put a quantity of "how many products of that size?" in an input right after it.
I was able to create an JavaScript function AddTam() called by a button that generates one more block to fill, with a select, and all the block's select inputs are named Tam[], so their values pass as an array, and their respective inputs named as "TamQnt8", the number 8 at the end refers to the size chosen, it changes every time the user chooses other size for the same block using other function DefTam(), that way, I could verify the sizes array in the Back-End, and use it to get their respective quantities and organize it all in an array, to finally send it to the database.
But for some reason, when I test if the information is passing through correctly, it doesn't send any data in the key "Tam" saying it's undefined when I tested it, in PHP I'm testing: if(!empty($_POST['Tam'])) but i also tried isset().
I just don't know what's wrong, so I was asking if isn't it the method I'm using insertAdjacentHTML() to generate the blocks, and if it works as well as createElement() in forms.
Also, when I created the blocks manually and instead of many selects I used checkboxes, it was working, just decided to change to the generated method because the checkboxes took way too much space in the screen, even worse for mobile.
Here's a simplification of the code in HTML:
<form method="post">
<section>
<div class="littlebutton" id="addTamanho" onclick="AddTam()">Add Tamanho</div>
</section>
<script>
var contador = 0;
function AddTam(){
let tamTitulo = document.querySelector('#addTamanho');
tamTitulo.insertAdjacentHTML("afterend",
'<div class="cellTam cell">'+
'<select name="Tam[]" class="'+contador+'tam8 '+contador+'" onchange="DefTam(this)">'+
'<?php foreach ($_SESSION["tamanhos"] as $key => $value) { ?>'+
'<option value="<?php echo $value["tamanho"];?>"><?php echo $value["tamanho"];?></option>'+
'<?php }?>'+
'</select>'+
'Tem => <input class="qnt" id="'+contador+'tam8" name="TamQnt8" type="number" min=1>'+
'</div>');
contador++
}
function DefTam(ElementTam){
let infoTam = ElementTam.value;
let refTam = ElementTam.getAttribute("class");
refTam = refTam.split(" ");
let relInput = document.getElementById(refTam[0]);
ElementTam.setAttribute("class", refTam[refTam.length-1]+"tam"+infoTam+" "+refTam[refTam.length-1]);
relInput.setAttribute("name", "TamQnt"+infoTam);
relInput.setAttribute("id", refTam[refTam.length-1]+"tam"+infoTam);
}
</script>
<button class="post" name="Inserir" type="submit">Postar</button>
</form>
Output: The Add Tamanho button, 3 generated blocks of the form and the Elements tab of browser's Developer tools
Sorry if I wrote something wrong or weirdly, still learning English, or if it's just a silly mistake in my code, also, any help is welcome.
I don't know how to solve the variable $cat by following script.
"text" variable from Form to javascript and pass to php function to be $Categories_name and to be $cat.
I already test the $cat variable, it is not "String", it is "object", I don't understand.
But I need $cat to be "String".
when Test = "This is Cat" (3 words),
I test $cat by php str_word_count and the output is 1 (I need to correct answer 3);
I test $cat by php var_dump and no output (I need to correct answer "String").
<p id="CaTable"></p>
<script>
function CaFunction()
{
var text = document.getElementById("CategorySelect").value;
document.getElementById("CaTable").innerHTML = "<?php php_catable('" + text + "'); ?>";
}
</script>
<!-- Generate Table by php and MySQL-->
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
?>
You are confusing server side code and client side code. Your php code live on the server and can only be executed on the server. And your javascript is on your client's browser and does not know about the server (remember, php generate a text file, and only that text file is sent to the browser). if you want to use the php_catable() function from your client, you will need to do an AJAX call or to redesign your page to do a form submit (just like what Steve is proposing).
Your First Page:
Assuming CategorySelect is a dropdown select box, create a script for its onChange event and create a method="post"post form with a hidden input that goes to "generate_table.php".
<input type="hidden" name="ca_table" id="ca_table" />
You make ca_table a hidden input so php will pick up the value from it when this page gets submitted to a second page where you can generate your table using the php function.
<script language="javascript" type=text/javascript>
function CaFunction(){
documentGetElementById('ca_table').value = documentGetElementById('CategorySelect').value;
submit();
}
</script>
add this to your select dropdown:
onChange="CaFunction();"
Your Receiving Page:
So your receiving page "generate_table.php" would have
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
$category_name = $_POST['ca_table']; // cleaned up at least with suitable preg_replace etc
// and call your catable function
php_catable($category_name);
?>
So that way your result will have been posted back to the server as per comments about client side/server side by #Fluinc and answer by #litelite. To get it to do something which performs looking like innerHTML which changes a part of the page without submitting the whole page you will need AJAX, again as per #litelite's answer.
Might get marked down for being dependant on JavaScript but intended mostly to help clarify client v server.
If you want to avoid the JavaScript dependency of this script you could leave out the onChange altogether and add a submit button, then collect $_POST['CategorySelect']; assuming that is its name - ensure it has name="CategorySelect" for php as well as its Id for your css/javascript. Php gets its variable from the item's name.
To get something a bit like the effect of AJAX visually (though the page is still submitted) you could submit the page to itself using action="<?php echo $_SERVER['PHP_SELF']; ?>" on the form and have all the code on the one page. You can put the table generating code in the div where you want the table to appear - it would need a default state set, of course.
#litelite's comment regarding not using posted data directly in an sql query is also vital to prevent attack - make sure you clean it up before you use it!
Example is here.
I'm moving countries from one select box to another, when I submit the form I want the values in the right text box to be used by php. When I give the right box a name for a php array, like ToLB[] the Javascript fails. How can I handle this so that the submitted values will be used by php processes?
in forms it's a typical process to use an action and a method. This is declared within the form tag. For example
<form name='phpSend' method='post' action='myActions.php'>
Now when your form is submitted it is instantly 'posted' to the url myActions.php and is automatically declared as a $_POST array.
The names of the inputs become the array keys and the value becomes the value.
A basic method is to do a procedural action. Meaning if you leave the action attribute blank, the action will submit the form to the page you're already on and use if statements to check if the form has been submitted.
if(isset($_POST)&&isset($_POST['someName'])){
//form submitted!
}
Now, I've never used a multiple select before so you may want to var_dumb() or print_r() your output to double check but my guess is it'll be an Array within the $_POST array.
Submitting with javascript
if(document.getElementByName('phpSend').submit){//or however your checking
var selected=[];
for(var e=0;e<document.getElementByTagName('select').options.length;e++){
if(document.getElementByTagName('select').options[e].selected==true)selected[e]=document.getElementByTagName('select').options[e].value;
}
//then add the selected array to your preferred method of sending your data to your php document
}
I often encounter a situation like this and I usually submit the select options as a string.
Add an hidden field to your form:
<input type="hidden" name="valuesToSubmit">
<script type="text/javascript">
var selectobject=document.getElementById("myselect");
var myValues = "";
for (var i=0; i<selectobject.length; i++){
myValues = myValues + selectobject.options[i].value + ",";
}
document.form.valuesToSubmit.value=myValues;
</script>
In the PHP scripts that receive the posting data you can use the explode function to turn your sting into an array and then iterate on it ... depends what you need to do. Remember to remove the last unwanted ","
I have taken a look at your code.
There are some missing parts and amendments to do to make it works.
I didn't test the amendments but I think they should work.
1)you have to add the hidden field inside the form.
<form name="combo_box" action="test.php">
<input type="hidden" name="valuesToSubmit" value="">
2)Then you have to give the id to the select box because you use the id to reference the object like this var selectobject=document.getElementById("ToLB");
<select multiple size="10" name="ToLB" id="ToLB" style="width:150">
3)Change th submit button with a normal button so you can force the submit only when the loop is ended and the values have been passed into the hidden field.
<input type="button" name="submit" id="submit" value="Submit" onClick="updateValues()">
4)Force the submit at the end of the javascript
function updateValues(){
var selectobject=document.getElementById("ToLB");
var myValues = "";
for (var i=0; i<selectobject.length; i++){
myValues = myValues + selectobject.options[i].value + ",";
}
document.form.valuesToSubmit.value=myValues;
document.combo_box.submit();
}
I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];
So I'm trying to create a webpage where the user puts in there course information. There is an add button on the page, that adds another text field for them if they need more fields.
Once the Add button is pressed, the page is reset and all of the information that has been previously entered is gone. I could save the information in an array, and when or if the the add button is pressed save the information into an array, and re populate the fields using what was stored in the array.
My question is: Is there a way to refresh a page, and keep the information in the text fields, without taking the long process mention above, is there some attribute that I can use that will not delete information that has been previously entered into ?
If you code HTML5, you can use localStorage with a fallback to cookies. Also, if the information should be removed after session end, then you may use sessionStorage instead.
You can use ajax i think...it runs in background no page reload is done.
Assuming this HTML:
<form id="course-info-form" action="submit-course-info.php" method="post">
Professor name: <input type="text" name="professor"><br>
Additional info:<br>
<input type="text" name="additional0"><br>
<input type="submit" value="Submit">
</form>
<br>
<button id="add-button">Add Field</button>
<!-- Use jQuery for DOM manipulation -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
With JavaScript / jQuery:
var courseInfoForm = $('#course-info-form');
var addButton = $('#add-button');
// Keep track of how many fields there are, so each can have a unique "name" attribute
var additionalFieldsAdded = 1;
// Whenever "Add Field" is clicked, create another input field
addButton.on('click', function() {
var newInput = $("<input>", {
type: "text"
name: "additional" + additionalFieldsAdded
});
courseInfoForm.append(newInput, "<br>");
additionalFieldsAdded += 1;
});
I'm not very good at PHP. In your PHP script, make a while loop that checks to see if isset($_POST['additional0']), and additional1, additional2, etc, until you are sure that there were no more additional fields passed. Then store all those additional details into an array, and handle it how you see fit.
As for your original question, I recommend using my solution instead. It's better to avoid unnecessarily reloading the page, if all you're doing is simply adding a new form each time.
I suppose you could capture the information that was "tentatively-submitted" when the "Add Field" button is clicked, and then in your PHP script loop through all the additional fields and create 1 more input element each time another field is added, and set the value attribute of each "old" input element to whatever was "tentatively-submitted."
So, to answer your question, you can set the default value of an input field (server-side) with:
// add-course-information.php
<?php
$addingField = false;
// Check for the optional "?do=addfield" parameter
if (isset($_POST['do']) && $_POST['do'] == 'addfield') {
$addingField = true;
$fields = array();
$nextField = 'additional' . count($fields);
// Get each piece of POSTed field data
while (isset($_POST[$nextField]) && $_POST[$nextField] != '') {
array_push($fields, $_POST[$nextField]);
$nextField = 'additional' . count($fields);
}
}
?>
<!-- Silly HTML! -->
<?php
// If adding a field, recreate and repopulate all previous fields
if ($addingField) {
for ($i = 0; i < count($fields); i++) { ?>
<input type="text" name="additional<?= $i ?>" value="<?= $fields[$i] ?>">
<?php } ?>
<input type="text" name="additional<?php echo count($fields) + 1 ?>">
<?php }
// Otherwise, show the default additional field
else { ?>
<input type="text" name="additional0">
<?php } ?>
<!-- More awesome HTML! -->
That might work... (Currently untested.)
What that page is supposed to do (if it works) is:
On default, give the user his initial setup, with just 1 additional input field, "additional0".
When the user clicks "Add Field," ?do=addfield should be POSTed to add-course-information.php (you can write that part), and when this page receives the do=addfield parameter, then it knows to loop through all the submitted additional fields, and store them each into an array, and then afterwards output all the submitted data back into another loop's-worth of dynamically generated <input> elements.
But I think that that would be much more complicated, and unnecessarily increase the processing your server has to do. It could even be abused if someone was to hammer the "Add Field" button hundreds of thousands of times a minute, eventually making your for-loops iterate millions of times... (Unless you imposed a limit on the maximum number of fields, which would be easy.)
However, you might as well leverage the client's processing power if it's available.