Multiple Forms, check input from all with one submit button - php

I've got multiple forms like this on one page:
<form method="post" action="#">
<input type="hidden" name="product_id" value="'.$item['articlenumber'].'" />
<input type="text" name="update_quantity" value="'.$pg->quantity.'" />
<input type="hidden" name="packing" value="'.$item['packing'].'" />
<input type="hidden" name="unit" value="'.$item['unit'].'" />
<input type="submit" name="addtocart" value="Update" />
</form>
And I've got one submit button at the bottom:
<input name='placeorder' type='submit' value='Place order' />
How can I check all forms when I press the submit button? I need to validate that the input that was given is the correct quantity.
UPDATE
I now got all the values from the forms in JavaScript and the validation is correct. Now I want to store the variables into PHP SESSIONS. I saw the answer from Ben and that would work if the values where in PHP, they are now in JavaScript. I need them on other pages so I thought Sessions would be the best thing here (if not, other suggestions are welcome).
I saw this answer and there they say it is not possible on one page. I understand that because PHP is server side and Javascript client side. Is this the only possible way to send Javascript variables to PHP?

Alright, first you should remove the type='submit' on the input. So change it to :
<input name='placeorder' value='Place order' />
Then you just need to add a javascript function to validate.
$(document).ready(function() {
$("input [name='placeorder']").click(function() {
var formOK = true;
$("form input").each(function(index, element) {
var value = $(element).val();
if (value != "OK") {
formOK = false;
}
});
if (formOK) {
submitForms();
} else {
alert("Form Input Inccorect");
}
});
});
function submitForms() {
$("#form1").add("#form2").submit();
}

With regards to your question about storing form data in a session variable Try something along these lines:
session_start();
if (isset($_POST['placeorder'])) {
$_session['ProductID'] = $_POST['product_id'];
$_session['UpdateQuantity'] = $_POST['update_quantity'];
$_session['Packing'] = $_POST['packing'];
$_session['Unit'] = $_POST['unit'];
}
Hope that helps

Both answers helped me a little bit but I needed to combine them so I ended up with a solution like the following. I got the values from the inputs by their unique name like this:
var sizeS25 = parseInt($("input[name='size-s25']").val(), 10) || 0;
var sizeM25 = parseInt($("input[name='size-m25']").val(), 10) || 0;
Then I send the variables to a PHP file:
window.location.href = "phpsessions.php?sizeS25=" + sizeS25 + "&sizeM25=" + sizeM25;
In the PHP file I set the variables as sessions:
$_SESSION['sizeS25'] = $_GET['sizeS25'];
$_SESSION['sizeM25'] = $_GET['sizeM25'];

Related

PHP multiple forms

So the issue I'm running into is I have a project with nested forms to select options and for some reason I cant get it to get beyond the first form. If you run this and select the first button it correctly displays the second button, but after that it just returns to the beginning.
How do I do this correctly? I've tried various methods such as isset, using functions, wiping the $_POST variable, etc and to no avail. Would Google or Stackoverflow this but I'm not quite sure what this problem is called.
This is all being done within a single php file because I don't want to have to deal with leaving the page, and this started out as a simple assignment that I've greatly expanded to fit my needs. Also I know nothing of Javascript and have no interest in using it.
<html>
<body>
<?php
echo <<< HERE
<form method = "post">
<input type = "submit" name = 'button' value = 'Do thing 1'>
<br>
</form>
HERE;
$button = $_POST['button'];
if ($button == 'Do thing 1'){
echo <<< HERE
<br>
<form method = "post">
<input type = "submit" name = 'button2' value = 'Do another thing'>
</form>
HERE;
$button2 = $_POST['button2'];
if ($button2 == 'Do another thing'){
echo 'doing another thing';
}
}
?>
</body>
</html>
The way I would solve this kind of issue is by sending all the fields and naming the buttons:
<form>
<input name="input_1">
<input name="input_2">
<button type="submit" name="button" value="button">Button</button>
<input name="input_n">
<button type="submit" name="button" value="button2">Button2</button>
</form>
Then once submitted:
if($_POST['button'] == 'button') {
/* sanitize input 1*/
/* sanitize input 2*/
/* do something */
}
if($_POST['button'] == 'button2') {
/* sanitize what you need */
/* sanitize input n*/
/* do something */
}

jQuery making forms disappear and appear after each other

As the title says This is the code that I tried with. The forms must appear one by one because information from previous forms determine how the next ones will look.
$(document).ready(function(){
$('#first_form').submit(function(){
$('#first_form').fadeOut('fast');
$('#second_form').fadeIn('fast');
});
});
<form action="new_patch.php" method="POST" id="first_form">
Title: <input type="text" name="patch" placeholder="Patch 4.20">
<br/>
Number of Champions: <input type="number" name="champ_number" min="1" max="99">
<br/>
<input type="submit" value="submit">
</form>
<form action="new_patch.php" method="POST" id="second_form" style="display: none;" >
<input type="text" value="text">
<input type="submit" value="submit">
<?php
$champ_number = null;
if(isset($_POST['champ_number']))
{
$champ_number = $_POST['champ_number'];
for($champ_number;$champ_number>0;$champ_number--)
{
echo "<br/>Champion ".$champ_number."<input type=\"number\" name=".$champ_number." min=\"1\" max=\"99\">";
}
}
?>
</form>
You're mixing client-side and server-side form code. Submitting the form will reload the page entirely, so from the looks of your code it will fade in the new form when the old form is submitted, but then reload the page so the old form will show again anyway.
You could either:
Let the PHP determine how the next form appears based on the submission of the first form, e.g. if (isset($_POST["First_form_submit"]) { Show second form... }
Probably better and more user-friendly: make the second form appear below once the user has filled in the relevant inputs on the first form before they've submitted
you can use:
$('#first_form').submit(function(){
$('#first_form').fadeOut(function() {
$('#second_form').fadeIn('fast');
});
return false;
});
From the jQuery documentation the syntax is fadeIn( [duration ] [, complete ] ) it accepts a duration and a onComplete callback that you can use to execute the next action when the first is completed.
I did this once too, just add a submit class to the button and make it like this:
<input type="submit" value="submit" class="submit">
Change script to a click function.
$(document).ready(function(event){
event.preventDefault();
$('.submit').click(function(){
$('#first_form').fadeOut(400);
$('#second_form').fadeIn(400);
});
});
PS, also you need to prevent submit default...otherwise it will just submit the form, see this JSfiddle

PHP: change page action of a form by url in select

hy, i have a problem with a form. i know the question is simple but i can not have a solution. Well, this is my form:
<form id="search" method="post" action="cerca_redirect2.php" >
<select id="tipo" name="tipo"class="chzn-select" style="width:165px;" tabindex="1" >
<option value="http://case.vortigo.it/vendita-immobili/index.php"> Vendita</option>
<option value="http://case.vortigo.it/affitto-immobili/index.php">Affitto</option>
</select>
<input id="field" name="field" type="text" value=""/>
<input id="submit" type="submit" value="" />
</form>
my goal is when i select "Vendita" and i submit the form i have to go to the url in the select "Vendita", for each select. someone can help me? thanks
In the server side php code, do something like this
if (isset($_POST['tipo']) && !empty($_POST['tipo']))
{
header('Location: ' . $_POST['tipo']);
}
Note: This is a very basic version, you will want to ensure the url is valid by either maintaining a list of urls on the server, or something similar.
There are many different ways, but you can for example use following:
See the onsubmit part in the form definition
<form id="search" method="post" action="cerca_redirect2.php" onsubmit="this.action=document.getElementById('tipo')[document.getElementById('tipo').selectedIndex].value" >
If I understan your question correctly, you need a way to change the action value to the selected option's value
this is how to do that
$(document).ready(function(){
$("#tipo").on("change", function(){
$("#search").attr("action", $(this).val());
});
});
DEMO: http://jsfiddle.net/6ybMP/
You want to change the action of the form based on the select? The following should be along the lines of what you want.
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
UPDATE
You will want to wrap this code in $(document).ready() so that the event will be registered after the DOM has been loaded.
Like so:
$(document).ready(function() {
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
});

I want to post a php variable from a form

I have a php variable "echo $id". Now I want to use the $_POST method to post the variable. I just want to know how to do this for a variable because $_POST[$id] does not work?
I think you are misunderstanding a basic concept here.
The $_POST super global is used to receive input (in the form of a POST request) from the user. While it is possible to set variables in it, you shouldn't.
Your question does not make sense. If you have an HTML form:
<form action="" method="post">
<input type="text" name="something" />
<input type="submit" value="Submit" />
</form>
Then you get the variable $_POST['something'] with whatever the user typed in the text box.
On its own, $_POST is just a variable like any other. You can assign to it $_POST['test'] = 123;, you can delete from it unset($_POST['test']);, you can even make it something other than an array $_POST = "Hello, world";, it just happens to be pre-populated with form data, if any.
With the method $_POST you must be posting to something.
My suggestion to you is to create a form, then have the form going to the file you wish to post to:
So something like this:
echo '<form action = "fileToPostTo.php" method = "post">
<input type = "text" hidden value = "'.$id.'" />
</form>';
And then submit the form when the document loads through jquery or javascript.
You can do it by $_POST['id'] = $id (then You will have it in $_POST['id'] variable (but You shouldn't do it :P).
Or You can send $id by form. Like example:
<form action="/pageToPOST.php" method="post">
<input type="text" value="<?=$id ?>" name="id" />
<input type="submit" name="" value="submit it!" />
</form>
And You'll have $_POST['id'] on http://yourdomainname.com/pageToPOST.php page
you can get and pass the value without page load and form.
<input type="text" name="something" id="something" />
<input type="button" value="ok" onclick="value();"/>
function value()
{
var something=$("#something").val();
var dataparam="oper=show&something="+something;
$.ajax({
type:"post",
url:"yourphpname.pnp",//this is very important.
data:dataparam,
success:function(data)
{
alert(data);
}
});
}
$oper =(isset( $_REQUEST['oper'])) ? $_REQUEST['oper'] : '';
if($oper == "show" and $oper != '')
{
$something=$_REQUEST['something']
echo $something;
}
what you want to do is assign a value submitted to your script using the POST method, to your $id variable. Something like:
$id = $_POST['id'];

Get value of input box, without a form?

Does anyone know how I can get the value of an input box, without having a form? I want a submit button, but instead of submitting a form, I want it to change data in a MySQL database. Something like this maybe?
$img1="WHAT DO I PUT HERE?"
$idx=1
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";
$result=mysql_query($sql);
Could I use that code on a "onclick" event? The input box's name and id is "img1".
If you don't want to submit a form, the only two other ways of accomplishing this are to click a link with the data as query parameters in the url, or use AJAX to send the data to the server in the background.
update:
Javascript, as usual. You'd put a link or button somewhere on the page with "Send to Server" or whatever for the text. The script would pull your information from the input fields, and then send it on to the server via an AJAX call. Something along these lines (note that I'm using Mootools for all this, as it makes life much easier than having to do the remote calls yourself):
function clickHandler() {
var img1 = $$("input[name='img1']")[0].value;
var r = new Request.JSON({
'url: 'http://yourserver.example.com/script.php',
'method': 'post',
'onComplete': function(success) { alert('AJAX call status: ' + (success ? 'succeeded': 'failed!'); },
'onFailure': function() { alert('Could not contact server'); },
'data': 'img1=' + img1
}).send();
}
and on the server you'd have something like:
<?php
$img1 = mysql_real_escape_string($_POST['img1']);
$idx=1;
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";
$result=mysql_query($sql);
echo (($result !== FALSE) ? 1 : 0);
You'd probably want something more complicated than this, but this is the basis of an AJAX application. Some client-side javascript that makes requests, and a script on the server that handles them and returns any data/errors as needed.
Don't know if your completely against using a form or just might not know how to keep it hidden.
You can create a hidden form that submits the info with the click of a button.
<form name="hidden-form" action="youraction.php" method="post">
<input type="hidden" name="submitme" value="I get submitted">
<input type="hidden" name="submitmetoo" value="I get submitted">
<input type="hidden" name="submitmeaswell" value="I get submitted">
<input type="hidden" name="dontleavemeout" value="I get submitted">
<input name="submit" type="submit" value="SUBMIT" />
</form>
However anyone that looks at your html will be able to see this
I guess this is what you looking for.
this will only work if your html and php are on the same file...
<html>
<head>
</head>
<body>
<input type='text' id='user' placeholder='user'>
</body>
</html>
<?php
$val = "
<script>
document.write(document.querySelector('#user').value);
</script>
";
echo $val;
?>

Categories