Targetting button outside of a form in action.php? - javascript

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.

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>'
?>

how to keep correct checkbox value check array after submit/document.form[0] submit or refresh page SOLVED

<script>
function refreshPage()
{
document.forms[0].submit();
}
</script>
<?php
foreach($values as $value)
{
?>
<input type = "checkbox" name = "food[]" value = "<?php echo($value['dinner']);?>">
<?php
}
?>
<button name = "pass" onClick = "refreshPage()">refresh</button>
so I have n amount of check box (depending on how many values user has)I want to keep them the check box check after the page refresh (by clicking on refresh button). I tried searching and saw similar form but the answer did not work for me.
For example the most popular answer was:
<input type="checkbox" name="txtCheck" value="your value"
<?php if(isset($_POST['txtCheck']))
echo "checked='checked'"; ?>
/><br />
this had two problem after i hit the refresh button value would not be save until i hit it twice to save(i want it to save after one click. Also sometime it save after one click but if i hit the refresh 3 time values are lost I want it to be save no matter how many time user refresh)
the second problem was it check all of the box would be check. I only want to keep the one user has check to be save.
I looked at various other possible solution but nothing worked
so if you could please help much would be appreciated. Also I need the value to be kept. I am using the checkbox value somewhere else
Edit something like this but for my array food[]. This only works for invidiual values
<input type="checkbox" name="small" class="checkbox" <?php if
($_POST['small']) echo 'checked'; ?> /> Small

php form wont submit with javascript

I have a dashboard page, and for the easiest solution I've made the entire page a form (as there are several drop downs scattered across the whole page). I want to implement a feature that can submit the form every 30 minutes, be it with JavaScript, jQuery or anything else, but when I've tried it just refuses to execute the code, so I tried going back to something basi such as submitting the form when the drop-down is changed via "OnChange".
Here is an example snippet of a seperate page with some code from my dashboard page. This in itself should be working but I just can't see why it won't execute the code, maybe I'm missing something obvious? Can you help me fix this:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function submit_my_form(myfield)
{
myfield.form.submit();
}
function submitForm() {
document.getElementById("branchForm").submit();
}
</script>
</head>
<body>
<?php
$branch_array = array(
array(1,"BRANCH 1",1, "http://BRANCH.BRANCH1:1"),
array(2,"BRANCH 2",1, ""),
array(3,"BRANCH 3",3, "http://branch3:3"),
);
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST" name="branchForm" id="branchForm">
<select name="query" id="query" class="select" onChange="submit_my_form(this);">
<?php
foreach ($branch_array as $x) { // populate select box with branches available from array
echo '<option value ="'.$x[0].'"';
if (isset($_POST['query']) && $_POST['query'] == $x[0])
{
echo ' selected="selected" >'.$x[0].". ".$x[1].'</option>';
} else {
echo ' option="'.$x[0].". ".$x[1].'">'.$x[0].". ".$x[1].'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Refresh" class="btnRefresh" />
<input type="button" value="go" name="click" onClick="submitForm();" />
</form>
<?php echo "<br/>Output: {$_POST['query']}"; ?>
</body>
</html>
Nothing happens when the drop-down is changed, and nothing happens when the "go" button is pressed.
Since you don't mind using jQuery, here you go:
var form = $("#formId");
$("select[name=selectField]").on("change", function(e){
form.trigger("submit");
});
http://jsfiddle.net/zt8zz1j5/
All it essentially does is listen for change on the select element, and simply triggers the submit event on the form. Of course you'll need to change the names and IDs to fit your code, but I'm sure you can handle that :), and remember to include jQuery in the document.
And for the button it's the same thing. You listen for the 'click' event and then trigger 'submit' on the form.

Cant submit form

Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did.
<input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if ($row["star"] =="5") echo "checked";?> value="5"/>
a querystring is required for the form so I'm using a form action like this
<form name="submit" action="http://example.com/page.php?id=<?php echo $urlid;?>&title=<?php echo $title;?>" method="POST">
and my php is
if ($_POST["submit"]) {
$rating = $_POST['star'];
$title = $_GET['title'];
$verification = ($_GET['verification']);
} else {
//run the page like usual
}
After testing, I found that onclick, it runs the form action, but on the php side, it goes to "else" where is runs the page like usual instead. Any ideas?
Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement.
If you want to check if the form was posted then you should instead check for:
if (!empty($_POST)) {}
or
if ($_SERVER['REQUEST_METHOD'] == 'POST') {}
The form element seems to have invalid attributes, missing a quote and space.
It's generally easier to write a little more code, and keep it clearer
<?php
$url = "http://example.com/page.php?id=". $urlid ."&title=". $title;
?>
<form name="submit" action="<?php echo $url; ?>" method="POST">
Since you are checking with -
if ($_POST["submit"]) { // this checks whether there is any item named 'submit' inside the POST or not
} else {
//run the page like usual
}
The easiest would be to put a hidden item with name submit so that the check validates to true-
<form .. >
....
<input type='hidden' name='submit' value='submit' />
</form>

Two Buttons with different action on same php page

I have a PHP page with two Buttons named as Save and Submit.One for Saving form Data and other for submiting the final data.
<button id="save" name="save" onclick="saveForm();">Save</button>
<button id="submit" name="submit" onclick="validate();">Submit</button>
here are the two JavaScript functions:
function saveForm() {
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
function validate() {
// some validation code here
// after validation the rest will work
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
In 'SubmissionCheck.php' page I have defined two separate actions for save and submit button, but I am facing the same process of submit button when I click the save button. How do I solve this? Any one help please. Thank you in advance.
<button id="save" value="save" name="method" onclick="saveForm();">Save</button>
<button id="submit" value="submit" name="method" onclick="validate();">Submit</button>
PHP
if(isset($_POST["method"])){
if($_POST["method"] == "save"){
echo "Saving File";
}elseif($_POST["method"] == "submit"){
echo "Submitting File";
}
}
When you are doing what you are trying to do I tend to keep my name's the same. So that I can test against them. I generally use names such as action, method, mode,and data which I can then test the values. Another good practice I do, is just var_dump then entire $_POST
example
var_dump($_POST);
var_dump($_GET);
var_dump($_REQUEST);
By performing these test conditions you can have more control over your code without getting overwhelmed by names. Another thing I like to do is use these for page actions, these action,mode,method help me generate the exact page the user is looking for.
example
<input type="text" value="" name="method" placeholder="Insert a method">
<input type="text" value="" name="action" placeholder="Insert a action">
<input type="text" value="" name="mode" placeholder="Insert a mode">
Then when submitted I can use these like so
$path = "";
if(isset($_POST["method"])){
path.="method=".$_POST["method"];
if(isset($_POST["action"])){
path.="&action=".$_POST["action"];
if(isset($_POST["mode"])){
path.="&mode=".$_POST["mode"];
}
}
header("Location: /path/".$path);
}
This will output three ways... if only method, if method and action, and if method,action,and mode. So generally speaking, testing against universal names sometimes is better. Hope this little walk down PHP $_POST usage helps you a little bit.
note I never sanitized any of the $_POST values, but if you are using them as a path you really should, or if you are access mySQL database use mysqli_real_escape_string and other sanitation methods.
Also is your forms default action being prevented, because since you have no values, $_POST will be empty every time. Unless it's prevented then submitted correctly.
<form onsubmit="return false">
//buttons
</form>
you can differentiate in actions like this
function saveForm() {
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
function validate() {
--some validation code here---
--after validation the rest will work--
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php?validate";
document.submission.submit();
}
then in SubmissionCheck.php file check
if(isset($_GET['validate']))
{
// perform actions for validation
}
check isset:
if (isset($_POST["save"]))
{
echo "save action";
}
if (isset($_POST["submit"]))
{
echo "submit action";
}

Categories