Getting value of select option php - javascript

I want to get a value of select option php on the same page. I brought selection list from database and listed them on the select. But even though I choose something on the list, it's not posted. Is there any problem in the code below? Thanks in advance.
<div class="ibox-content m-b-sm border-bottom">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="status">Search by category</label>
<form action="" method="POST" >
<select name="category" class="form-control">
<option value="" selected>All</option>
<?php
while($category = mysqli_fetch_array($result1)) {
// output data from each row
echo "<option value=\"{$category['categoryID']}\">{$category['name']}</option>";
}
?>
</select>
<input class="btn btn-primary" type="submit" name="submit" value="Search">
</input>
</form>
</div>
</div>
</div>
</div>
<?php
if (isset($_POST['submit'])) {
echo "Got it!";
echo $_POST['category'];
}?>

You should specify a name for the option:
<option name='category' value=\"{$category['categoryID']}\"...
And try adding action='#', and then it works:
array (size=2)
'category' => string '1' (length=1)
'submit' => string 'Search' (length=6)
Got it!1
And take care, in your code the option for 'all' has no value, and won't be displayed.

You have:
<?php
while($category = mysqli_fetch_array($result1)) {
// output data from each row
echo "<option value=\"{$category['categoryID']}\">{$category['name']}</option>";
}
?>
An array key -> inside a template var -> inside an option -> in a double-quoted string (which will parse vars), -> inside a while loop (which may or may not be running). That level of nested complexity will certainly decrease your time-to-debug and simplicity-to-debug.
I would first ignore the html entirely and:
$category = mysqli_fetch_array($result1)
var_dump($category, $category['categoryID'], $category['name']);
in naked php, to make sure that you have exactly what you need before you put anything into the html.
Also, form action='' sometimes causes problems, so make that and everything else you can explicit and fixed just while debugging.
I have to say that you're making things harder for yourself by not using a template engine, especially at the early stages. Your html+php is low-readability, and that decreases the ease of debugging. Use a clean template and it'll be easier to debug echoing issues, and as a side benefit you'll get easy escaping.

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.

CakePHP dynamic form inputs

I'm using CakePHP 2.3.8 and I'm trying to create a form with dynamically added inputs from this tutorial but I'm having some issues. The adding and removing of inputs works just fine, but when I submit the form I get a black hole error message. Upon inspecting the inputs, it doesn't appear as if the key value isn't properly set and causing some issues with the id's of the inputs.
For example, with this code in an element
//Elements/users.ctp
$key = isset($key) ? $key : '<%= key %>';
<tr>
<td><?php echo $this->Form->input("Role.{$key}.user_id", array('options' => $users, 'label' => false)); ?></td>
<td class="actions">
Remove User
</td>
</tr>
this is the select that is generated
<select name="data[Role][0][user_id]" id="Role<%=Key%>UserId">
Edit
The value of $key is being set correctly on /Elements/users.ctp. I can create a row and echo the output of $key, and a number for the row appears correctly. As you can see above, the name of the element is set correctly, but the id is still being set strangely.
The name of the select element is being set properly, but not the id.
What is causing the select id to be Role<%=Key%>UserId rather than Role0UserId?
The Problem:
If you observe the generated select tag you posted in question, it shows
<%=Key%>
The variable expected by underscore library utilized by the tutorial you are using is
<%= key %>
CakePHP form input is replacing the html characters and space of that underscore variable, hence its not detectable by underscore library.
The Solution:
In order to fix the issue, you must use plain html code for the template part. Your grades.ctp must be as shown below (partial code for understanding)
<?php if (isset($key)) : ?>
<tr>
<td>
<?php echo $this->Form->input("Grade.{$key}.id") ?>
<?php echo $this->Form->input("Grade.{$key}.subject", array('label' => false)); ?>
</td>
</tr>
...rest of the code
<?php else: ?>
<tr>
<td>
<input type="hidden" id="Grade<%= key %>Id" name="data[Grade][<%= key %>][id]">
<div class="input text required">
<input type="text" required="required" id="Grade<%= key %>Subject" maxlength="200" name="data[Grade][<%= key %>][subject]">
</div>
</td>
...rest of the code
</tr>
<?php endif; ?>

How do I echo POST data into a javascript descriptor in currency format? Stripe checkout

I have a Stripe form I am trying to add a display for the purchase amount:
data-description="<?php echo $_POST['plan']; ?>"
but the above outputs errors in the display 'notice undefined variables', even with isset.
The following code work without errors, except once I try and echo POST data.
<form action="pages/scharge.php" method="post">
<div>
<input type="radio" name="plan" value="2500"> Beta membership <br>
<input type="radio" name="plan" value="3500"> VIP membership <br>
</div>
<div>
<label for="plan"> If you would like to pay another amount, enter the amount here:</label>
<input type="text" name="plan" />
<label for="invoice_num"> Enter the invoice number here:</label>
<input type="text" name="invoice_num" />
</div>
<div>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<?php echo $stripe['publishable_key']; ?>"
data-amount="<?php if(isset($_POST['plan'])); echo $_POST['plan']; ?> " data-description=" ">
</script>
</div>
</form>
How would I echo the POST data in data-description=" " in currency format (stripe is $18.00 = 1800) so that customers can see the proper amount before clicking purchase?
This should work:
data-description="<?php
if (isset($_POST['plan'])) echo htmlspecialchars($_POST['plan']);
?>"
Note that there is no ; after if (isset($_POST['plan'])). If you do put a semicolon there, PHP interprets that semicolon as the (empty) statement that the if is supposed to conditionally execute.
If you're feeling confused about the semicolons, another, perhaps safer way of writing that would be:
data-description="<?php
if (isset($_POST['plan'])) {
echo htmlspecialchars($_POST['plan']);
}
?>"
Here, you can include as many statements as you want (separated by semicolons) between the curly braces, and they will all be executed only if $_POST['plan'] is set. Make sure there's still no semicolon between the if condition and the {, though!
Also, note the htmlspecialchars(). Without it, your code is wide open to cross-site scripting (XSS) attacks, by an attacker passing in a parameter like plan="><script>alert("XSS");//.
Any time you embed a string (that isn't meant to be parsed as HTML code) in your HTML output, you should always escape it with htmlspecialchars(). Preferably, do this even if you're sure that the string cannot contain any characters that could be parsed as HTML markup; it's just a good habit, and may save your code from breaking if you ever decide to change the string later.

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

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.

Categories