Post several duplicated forms, with different info to a new page - javascript

I need to create a system to print information about items in a database. By now I have an html form with several input fields (types = text and radio), so I can collect all the info of an item.
To make the process faster I introduce a javascript to duplicate the whole empty form 'n' times with a click, so one can print several items information at once. My script looks like this:
<body>
<button id="button" onclick="duplicate()">add form</button><!--this button duplicates the empty form-->
<form action="action.php" method="post" name="formulario">
<div id="duplicater">
<p>Código:<input type="text" name="codigo" /></p>
<p>Nombre del proyecto:<input type="text" name="proyecto" /></p>
<p>
<span>
<input type="radio" name="grupo1" value="SD" />SD
<input type="radio" name="grupo1" value="HD" />HD
</span>
<span>
<input type="radio" name="grupo2" value="4:3"/>4:3
<input type="radio" name="grupo2" value="16:9"/>16:9
</span>
</p>
<p>Fecha:<input type="text" name="fecha" /></p>
<p>Lugar:<input type="text" name="lugar" /></p>
<p>Dueño:<input type="text" name="dueno" /></p>
</div>
<p><input type="submit" name="submit" value="enviar" /></p>
</form>
<script>
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
At this point, this part of the project is working fine, but I have a problem with the action.php file that handle the functionality to send the information from all the forms to a new page to print it.
The action.php collects the information of the form using the name attribute of every input. As every form is just a duplicate of the original one, every new form have the same name attribute, so when I click the send button, the php just echo the information of the last form.
<div><span>Código: </span><?php echo htmlspecialchars($_POST['codigo']); ?></div>
<div><span>Proyecto: </span><?php echo htmlspecialchars($_POST['proyecto']); ?></div>
<div><span>Calidad: </span><?php echo htmlspecialchars($_POST['grupo1']); ?></div>
<div><span>Formato: </span><?php echo htmlspecialchars($_POST['grupo2']); ?></div>
<div><span>Fecha: </span><?php echo htmlspecialchars($_POST['fecha']); ?></div>
<div><span>Lugar: </span><?php echo htmlspecialchars($_POST['lugar']); ?></div>
<div><span>Dueño: </span><?php echo htmlspecialchars($_POST['dueno']); ?></div>
Questions:
I need to update (rename) the name attribute of the input tags in every duplicated form, how can I do that?
It is possible to refer the echo function in the action.php file to a div with an id assigned to post the whole information at once? otherwise, how can I send (post) the information of all the duplicated form to a new page at once?
This have to be a client side process, so there is nothing more behind it, the php is just for echoing the info to the new page. So if there are solutions that can be done with javascript or jQuery is ok as well.
I leave a link to the demo http://www.programaicat.una.ac.cr/ICATsite/demo/
Thanks to all in advance.

The way POST vars are sent to a script, they're named key, value pairs in an array. Any inputs with the same name will be overwritten.
I suggest appending or prepending a number to each additional input as they are created, so instead of a new input called "name", it would be called "name.1" or "1.name". Your first input would be "name.0" and the rest would increment upwards as they are added. When you process the information, you can iterate over the POST array keys using substr and re-shape your information as needed before saving it to the database.

Related

Use array to post html form with every aray value ony by one

I am wondering if the folowing is possible.
I fetch a list of names as an array from a SQL database. I need all those names to be posted with a html form one by one. This action should be activated with one button. When the button is clicked the names should be posted one by one untill all names are posted, then stop. So probebly jquery or javascript is needed but that is new for me. I have been searching but I can not find anything that can help me accomplisch this.
I am sorry for asking this question and my language (english is not my main language) but I don't know if this is even possible and I cant find any corresponding topics while researching..
PS: I can not use Ajax for the post !!
Example to get the names:
$stmt = $mysqli->prepare("SELECT username FROM example WHERE examplefield = 1");
$stmt->execute();
$result = $stmt->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result->fetch_assoc())
{
$arrayusername[] = $rowid['username'];
}
I need all the names from the $arrayusername[] to be posted with below form one by one by pressing the following button
<input type="button" value="Post all names one by one"
onClick="sendallvalues('???') "class="example_c" />
// The button should do the following post name 1, end. post name 2 end, post name 3 end. stop script when all names are posted.
<form method="post" target="_example" action="https://www.example.nl">
<input type="hidden" value="<?= $arrayusername[] ?>" name="postvalue" >
</form>
// should be hidden to the user and is only ment for the name atrribute to have a place ! All the stuff needs to happen by pressing that one button !
<script>
function sendallvalues(???) {
//I have no Idea where to begin to make this happen.. But it should post the form one by one with one value at the time untill all names are posted.
}
</script>
Maybe you can explain more detailed what you need.
The value attribute should have one name and you create different input fields.
<form method="post" target="_example" action="https://www.example.nl">
<input type="hidden" value="<?= $arrayusername[] ?>" name="postvalue" >
<input class="example_s" type="submit" value="Post name">
</form>
should be
<?php
$arrayusername = array('Name1','Name2');
echo '<form method="post" target="_example" action="https://www.example.nl">';
foreach ($arrayusername as $key => $value) {
echo '<input type="hidden" value="' . $value .'" name="name-' . $key . '" >';
}
echo'<input class="example_s" type="submit" value="Post name">';
echo '</form>'
?>

Targetting button outside of a form in action.php?

I currently have 2 forms, which adds data to my database. They both work, but they each have their own submit button - and I only want one submit button to collect the data from all the forms.
I found some javascript that should set the deal;
$("#submitbutton").click(function(){
$("#form1").submit();
$("#form2").submit();
});
The button I'm targetting is outside of both forms and looks like this:
<input id="submitbutton" type="button" value="add">
I'm pretty sure the reason why it doesn't work, is because of the way my php is written. I'm targetting the submit button in each form to excecute the php.
You can see the forms and php below.
One of the forms allows you to upload a picture;
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
The action file contains this php;
<?php
if(isset($_POST['sumit']))
{
if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
{
echo "Please select an image.";
}
else
{
$image= addslashes($_FILES['image']['tmp_name']);
$name= addslashes($_FILES['image']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($name,$image);
}
}
displayimage();
function saveimage($name,$image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="insert into pictures (name,image) values ('$name','$image')";
$result=mysql_query($qry,$con);
if($result)
{
//echo "<br/>Image uploaded.";
}
else
{
//echo "<br/>Image not uploaded.";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="select * from pictures";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
mysql_close($con);
}
?>
The other form lets you choose between multiple categories collected from my database;
<form id="form2" action="checkbox.php" method="post">
<label for="Category">Category</label>
<br />
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="checkbox" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
<input type="submit" name="Submit" value="Submit" class="btn btn-default"/>
</form>
And has the following php;
<?php
include("config.php");
$checkbox = $_POST['category'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox);$i++) {
$query = "INSERT INTO placecategory (category_id) VALUES ('".$checkbox[$i]."')";
mysql_query($query) or die(mysql_error());
}
echo "Category is inserted";
}
?>
I've tried targetting the new button I made that should excecute the javascript, but it doesn't seem to work because that button is out of the form.
Is there a way to target the button outside of the form so the php excecutes when that is clicked? Or how can I rewrite this?
Any help is appreciated!
Not sure I understand completely what you're trying to do but try this with HTML5 add form="form1" and form="form2" for your second one and let me know if this works.
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
<input type="submit" name="sumit" value="Upload" form="form1" />
Taking in account your complementary comment, then your proposed javascript sequence would work, assumed you have:
suppressed buttons such as <input type="submit"... /> from both forms
added the new button <button name="submitbutton">...</button> outside of the forms
modified the PHP parts accordingly, referencing $_POST['submitbutton'] instead of sumit and Submit respectively
You didn't report how it currently don't work, so the above steps target only the changes precisely related to the fact you replace two in-form buttons by a unique out-form one.
But something may turn wrong elsewhere. I notably noticed the non-usual way (at least for me) you get and process the image. Also you must ensure that your javascript part have really been executed.
Let me know if it doesn't work yet, than adding precise description of what turns wrong.
Edit, based on your provided comments and live preview.
Fully testing is not really possible because the server PHP part is out of reach, bue we can use Firebug to debug JS part.
So adding a breakpoint we can observe that, as soon as $("#form1").submit(); has been executed, the server returns a new page with the "Place has been added!" message.
In the other hand, without any breakpoint set, the server returns returns a new page with the "Categorie inserted!" message.
Though the OP didn't show the addingplace.php part of the current live preview, and comparing with the checkbox.php part, we can guess that:
In the reduced execution part, the first step addingplace.php did work as expected.
What we observe while whole execution merely means that all three parts have worked as expected, but each one having its returned message overwritten by the next one, but for the last one.
In other terms, when you comment "it only seems to submit the last form", this is a false impression based on what you only can see.
To ensure this is true or not you should control what is really updated or not in your database.
Let me know.
That said, it must be noted that this illustrates how the couple server-browser works in those circumstances: as already pointed by #David in a comment under the OP, to submit a form causes the browser to immediately receive a new page which overwrites the current one.
In the current example, it works because there are only few forms, and all three are submitted in a very reduced time, almost instantly: so the 3rd submit() can get executed before the 1st one's returned page comes.
So the recommended way to achieve the whole work in your example is merely to use only one form, with its unique submit button. BTW I wonder why you wanted to have this more complicated structure with three forms: what is the expected benefit?
Last point, outside of the precise issue you reported: you should pay attention to how you're coding. There is a lot of inconstencies in the HTML part, e.g.: a <html><body> part inside the already existing <body>; an exotic <br></br>; also you kept a supplemental button in the 1st form.

check box value display in results page

i have two php file one input page another results page . input page have checkbox. code looks like this
<form action="" id="frmCalculators" method="post" name="frmCalculator">
<input id="chkUFtoLoan-1" name="S" value="S" type="checkbox" checked />
<button id="Button4" type="submit" onclick="GetPage()" class="dont-compare shadow-inset ">
Calculate Scenarios</button>
I have passed check box value next page php
<?php
session_start();
$checkbox1 = $_POST["S"];
?>
i have tired checked using echo value passed in results php.
Now i have question i have value in results page looks like
About your Loan :
<label id="FinancedUpfrontMIP" class="pull-left">Financed Upfront MIP</label>
<label id="financedmip" class="pull-right">$<?php echo round($arrFirstBox["upfrontmipamt"],2);?></label>
Buyer close to section:
<label id="FinancedUpfrontMIP" class="pull-left">Financed Upfront MIP</label>
<label id="financedmip" class="pull-right">$<?php echo round($arrFirstBox["upfrontmipamt"],2);?></label>
my question user select check box value display about your loan if user not select checkbox value display buyer close to section.. Now display same value both place. if one value one show another value need to show Zero.. please any idea about it?

How to change div id name based on form value?

I have a couple forms on a page with a single button and a hidden input field with a value already pre-set:
<form action="product.html" method="get">
<fieldset>
<input style="display: none;" type="text" name="RSS" id="RSS" value="RSS" />
<input type="submit" value="Go"/>
</fieldset>
</form>
<form action="product.html" method="get">
<fieldset>
<input style="display: none;" type="text" name="RSS2" id="RSS2" value="RSS2" />
<input type="submit" value="Go"/>
</fieldset>
</form>
Once they hit the Go button on either form, it will redirect to the product.html page where a specific div loads based on the value above.
<div id="ID CHANGE TO OCCUR HERE to either be RSS or RSS2"></div>
My question is, how do I get that id to change on that div?
Thanks
PS: PHP is not enabled on the company servers...so yeah..yeah...
If I understand you correctly, when program control transfers over to product.html, you wish to discover which form value has come across (i.e. which form did the user click).
I cannot think how you would do this solely with HTML. This is a job for a server-side language like PHP or ASP .Net.
It's pretty simple in PHP. Note that you can take all your existing HTML files and simply rename them to .php (eg. product.php) and they will still work the same.
Just put this at the top of the file -- in fact, this is the complete file (just copy/paste to your server to test):
product.php
<?php
/* Below not required, but un-comment to see useful info:
echo '<pre>';
print_r($_REQUEST);
echo '<pre>';
*/
if (isset($_REQUEST['RSS'])) {
echo 'User clicked the RSS form';
} else if (isset($_REQUEST['RSS2'])) {
echo 'Sent here by the RSS2 form';
}
Since the name of the processing file has changed, remember to change the action= line in each of your forms before trying this:
<form action="product.php" method="get">
Explanation:
When a form is submitted, the form elements (input fields, radio buttons, checkboxes) are turned into variables and sent to the processing document (the target document specified in the action= attribute of the form tag).
For each element, the variable name is the name= attribute for that element, and the variable value is either the value= attribute, or, in the case of an input field for example, whatever the user typed into the field before pressing submit.
The is very little difference to the programming/functionality between sending the form as method="Get" or method="POST", but the post method is more secure and can transfer more information, so most of us use that.
Finally, on the other end, there are three ways to get the variable values (PHP Example):
$newvar = $_GET['varname']; //if method="GET" was used
$newvar = $_POST['varname']; //if method="post" was used
$newvar = $_REQUEST['varname']; //works for both
If you need more assistance with PHP, view some of the Alex Garret's free ten-minute videos on the New Boston or on his own site.
Re-reading your question, I put together the completed example. In your target page, you have two DIVs and you wish to display one or the other depending on what form the user clicked.
Here is a working example of the solution. Copy/Paste into two files called:
test.php -- this file can be renamed whatever you want
product.php -- if change this name, must also change name in both action= attributes of forms
test.php
<form action="product.php" method="get"> <!-- product.html -->
<fieldset>
<input type="hidden" name="RSS" id="RSS" value="RSS" />
<input type="submit" value="Go"/>
</fieldset>
</form>
<form action="product.php" method="get">
<fieldset>
<input type="hidden" name="RSS2" id="RSS2" value="RSS2" />
<input type="submit" value="Go"/>
</fieldset>
</form>
product.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var whichone = $('#xfer').val();
//alert( whichone );
$('#' + whichone).show();
});
</script>
</head>
<body>
<input type="hidden" id="xfer" value="<?php echo ( isset($_REQUEST['RSS']) ? 'RSS' : 'RSS2' ) ; ?>">
<div id="RSS" style="display:none;">
<h1>RSS DIV</h1>
Here is some information regarding the RSS div.
</div><!-- #RSS -->
<div id="RSS2" style="display:none;">
<h1>RSS2 DIV</h1>
<i>Here is some <strong>different </strong>information regarding the RSS2 div.</i>
</div><!-- #RSS -->
</body>
</html>
You can test your request with javascript:
if(location.href.indexOf("RSS=RSS") > 0) {
var element = document.getElementById('RSS')
element.id = "RSS2";
element.name = "RSS2";
element.value = "RSS2";
}
this is just an indexOf check, u could also parse the whole query string and associate the key/value pairs into an array. See How can I get query string values in JavaScript?

Getting checked value with ajax submit

First of, I'm new to ajax and Java Script.. I have spend days solving this problem, but I still haven't figured it out. I have read through threads with similar problems but I still can't get it right. So here goes;
Quite simple I want post the checked value from from one of three radio buttons. All I get though is only the value of the first radio button..
I have tried several things, but I stripped down the code so it might be easier see where the problem is :-)
The ajax
<script type"text="" javascript"="">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var svar = $('#svar').attr('value');
var date = $('#date').attr('value');
var email = $('#email').attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "svar="+ svar + "&email=" + email + "&date=" + date,
success: function(){
$('form#submit').hide();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
</script>
The form
<form id="submit" method="post" name="submit" action="">
<fieldset>
<legend>Dagens spørgsmål: <? echo $row['question'];?></legend>
<br>
<input type="radio" name="svar" id="svar" value="1"><? echo $row['opt1'];?>
<br>
<input type="radio" name="svar" id="svar" value="2"><? echo $row['opt2'];?>
<br>
<input type="radio" name="svar" id="svar" value="3"><? echo $row['opt3'];?>
<br>
<input name="email" id="email" type="hidden" value="<? echo $email ?>" />
<input name="date" id="date" type="hidden" value="<? echo $date ?>" />
<br><br>
<button type="submit" class="button positive"> <img src="img/tick.png" alt=""> Svar på dagens spørgsmål </button>
</fieldset>
</form>
Ajax.php
<?php
include ("dbc.php");
// CLIENT INFORMATION
$email = htmlspecialchars(trim($_POST['email']));
$date = htmlspecialchars(trim($_POST['date']));
$svar = htmlspecialchars(trim($_POST['svar']));
//stuff from answers
mysql_query("INSERT INTO answers
(`email`,`day`,`answer`)
VALUES
('$email','$date','$svar')") or die(mysql_error());
?>
Hope one you of you smart guys have a solution.. because this thing i driving me crazy
You have several problems.
First, your HTML is invalid. An ID must be unique, so each radio button must have its own ID. You associate a group of radio buttons by giving them the same NAME. (Having a unique ID then lets you associate a LABEL with each one using the FOR attribute which increases accessibility by making it easier for screen readers and providing bigger click targets).
Second, the value of a radio button is fixed. The question is "Is it successful or not?" and that is determined by seeing if it is checked or not. If you were doing this manually, you would have to loop over each radio button in the group until you found one that was checked (or use a selector that matched only the checked ratio button (:checked)).
Third, you are building your form data by mashing together strings without making sure the data is URL safe (with encodeURIComponent).
The solution is to forget about doing all this manually and just use the jQuery serialize method on the form.
First: you use the same id for several elements. ID-s should be unique, and you should address your elements with class name or other means. So instead of
$('#svar')
yous should use
$('input[name=svar]')
to reference the group of checkboxes.
Second: There is a slight mistake here:
$('#svar').attr('value');
is the value of the first radio button's value attribute, while
$('input[name=svar]:checked').val();
would give you the value of the checked radio button in the group you are selecting with input[name=svar].
Edit: thx #Quentin for pointing out my error.
First thing to know is id should be unique in a html document.
What makes attributes of type ID special is that no two such
attributes can have the same value;
[Quoted from css2 selector docs]
You have assigend same id to three radio buttons.
Now when you use var svar = $('#svar').attr('value');, only the first radio button will get selected. So, irrespective of radio button selected, only the first radio buttons value you will get.
Now, if you want to get the radio button selected you have to use jQuerys :checked selector.

Categories