Two Buttons with different action on same php page - javascript

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";
}

Related

Submit form and redirect not working

EDIT: I should mention the form submits fine manually but with the javascript nothing seems to happen
I'm trying to get a form to autosubmit on page load and then redirect the user. Reason for this is this is part of a PHP page and the data needs to go into my database but then also POST the variables to a 3rd party SMS platform then return to the users dashboard.
My form looks like this:
<html>
<form action="https://www.example.com" id="myForm" method ="POST">
<input type="hidden" name="apiKey" value="withheld">
<input type="hidden" name="message" value="<?php echo $club_name ?> have requested you to play for them this weekend. Please login to your account to see more information and accept.">
<input type="hidden" name="to" value="<?php echo $to ?>">
<input type="hidden" name="from" value="withheld">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</html>
This seems to work fine so I assume the Javascript is incorrect which is:
<script>
document.getElementById('myForm').submit();
window.location.replace("https://www.example.com");
</script>
You have to use a different name than
name="submit"
as all name attributes are set as properties on the form,
hence overriding the default "submit" property on the form,
and the default form method "submit()" is gone.
https://developer.mozilla.org/de/docs/Web/API/HTMLFormElement
"Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute)."
In your code window.location.replace("https://www.example.com"); line won't make sense because submit() function will try to submit the form and will change the page and then replace function will prevent submitting the form and will redirect the page. The right way to do this via js can be, submit the form via ajax and in the success callback of Ajax run document.getElementById('myForm').submit()

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.

PHP: Using $_POST to display form values

I have a basic HTML form with one input text field, along with a submit button. Now, I want to use JavaScript to display the content entered by the user in the text field after form submission.
Here's the code of my form:
<form method = "POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" onclick = "postResul()" />
</form>
On clicking the submit button, the postResul() function is called:
<script>
function postResul()
{
var htmlString="<?php echo $_POST['tweet1']; ?>";
alert(htmlString);
}
</script>
Now, both these code snippets are stored inside a PHP file. However, on submitting the form, the data entered in the input form field doesn't get displayed. I'm displaying the $_POST['tweet1'] variable in order to display the entry submitted by the user.
What seems to be wrong here? Am I using the $_POST variable in PHP the wrong way?
If you want to display the input's value BEFORE sending it to your server:
document.querySelector("form").addEventListener("submit", function()
{
var value = this.querySelector("input[name='tweet1']").value;
alert(value);
return false; //disable sending the data to the server
}, false);
<form id="myForm" method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
If you want to display the input's value AFTER sending it to your server:
<form method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
<?php echo htmlspecialchars($_POST["tweet1"]); ?>
These are different things. You can use $_POST only after you've sent some datas to the server. When you open yoursite.com/index.php in your browser, you make a HTTP GET request. In this case, $_POST will be an empty array, since it's a GET request, no data is sent to the server. When you submit the form, you make a HTTP POST request. Your PHP can access only that data you sent to the server. With Javascript, you work on the visitor's computer, not on the server. The only one way to send the data to the server without refresing the page, if you use AJAX, and make a new HTTP POST request, that'll run in the "background". But you do not need this if you just want to display the input's value, and you don't want to save it on your server. That can be done with Javascript, and without PHP.
The code you posted above would work like this:
You make a HTTP GET request to yoursite.com/index.php.
No data is sent to the server, $_POST will be empty.
var htmlString="<?php echo $_POST['tweet1']; ?>"; In this line, you try to echo an non-existing member of $_POST, you might see an error if display_errors is not disabled.
You click on the submit button.
It has an onclick attribute, postResul (a Javascript function) is called. If you open the page's shource, you'll see this:
function postResul()
{
var htmlString="";
alert(htmlString);
}
After an empty popup is shown, and you press OK, the browser send the data to your server, and you'll able to acess the input's value via $_POST.
If you press the submit button again, you'll see submited value (and not the input's actual value), because if you open the source code, you'll see this:
function postResul()
{
var htmlString="entered data";
alert(htmlString);
}
But that isn't want you want, so see the examples above depending on what you want (save the data, or just display it in the browser).
This should work:
function postResul()
{
var htmlString=document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
But you should really read more on how client-side and server-side languages work.
You cannot use $_POST['tweet1'] to get the value when you are invoking a Javascript function. Basically client side and server side are totally different.
You can obtain the result using Javascript as:
function postResul()
{
var htmlString= document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
In HTML:
<form method = "POST">
<input type = "text" name = "tweet1"/>
<br>
<input type = "submit" onclick = "postResul()" />
</form>
Note: The above function runs in client side and not in server side.
$_POST can be used to get values of the submitted form in a php page.
Cheers.
You have to make another file. Change your code to:
<form method="POST" action="another.php" >
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
In file another.php you can show the variable then:
<?php echo htmlspecialchars($_POST['tweet1'], ENT_QUOTES, 'UTF-8'); ?>
You should use the form in a different way
<form method="POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
test.php file
<?php
return json_encode([1, 2, 3]);
js
$('form').on('submit', function() {
$.post('test.php', {}).done(function(response) {
alert(response);
})
})
Something like this.
Hope it's useful.
if you are using jquery library you can do this
<form method="POST">
<input type = "text" name = "tweet1" class="tweet" />
<br>
<input type = "submit" class="submit" />
</form>
$('.submit').click(function(e){
alert($('.tweet').val());
e.preventDefault();
});
jsfiddel working example http://jsfiddle.net/mdamia/j3w4af2w/2/

Process section of input URL

Simple question really, but I'm probably missing a really simple point.
I have an input form, that a user will paste a URL in to be navigated to the next section.
Say the user enters in: https://www.facebook.com/connect/login_success.html#access_token=XXXXXXXXXYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZAAAAAAAAAAAAAAAAAABBBBBBBBBBBB&expires_in=0
I want the form to only process the: XXXXXXXXXYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZAAAAAAAAAAAAAAAAAABBBBBBBBBBBB
So it will completely ignore:
https://www.facebook.com/connect/login_success.html#access_token=
and
&expires_in=0
Is this possible at all?
My form is incredibly simple:
<form action="home.php" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Access Token.</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="accesstoken"/>
</div>
<button type="submit" class="btn btn-default btn-block">Confirm</button>
</form>
"Bootstrap"
Thanks!
You could do an explode(http://nl3.php.net/explode) on the ampersand('&') and paste it together in a string or variable.
Change your form to use POST, like this:
<form action="home.php" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Access Token.</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="accesstoken"/>
</div>
<button type="submit" class="btn btn-default btn-block">Confirm</button>
</form>
Then, you can retrieve your variable in PHP, like this:
<?php $accesstoken = $_GET['accesstoken']; ?>
which can easily be echo'ed into a JavaScript variable for your use.
At first, I suggest you to parse it on server side, not client side (JavaScript can be turned off etc.). If you need to have accesstoken as GET parameter on home.php, you can redirect user here after submit. Anyway, on server side, try it with parse_url:
$urlParts = parse_url($_POST['accesstoken']); // Now you have all URL parts in array
$urlQuery = $urlParts['query']; // Now you have only query part
$queryParts = explode('&', $urlQuery); // Separate them
foreach ($queryParts as $query)
{
$singleQueryPart = explode('=', $query); // Separate key from value
if ($singleQueryPart[0] == 'access_token') // If the key is same as we are looking for...
{
$token = $singleQueryPart[1]; // ...assign value and break loop
break;
}
}
echo $token;
NOTE 1: I assume that your URL in first post has type (# instead of ?). If not, just use same script as I post, but change $urlParts['query'] to $urlParts['fragment'].
NOTE 2: If you really want to/need to use JavaScript, look at php.js implementation of parse_url.
NOTE 3: Another nice JS library to handle URL operations seems to be URI.js.
I found a much simpler solution to my issue:
<script>
$(document).ready(function() {
$('#btnSubmit').click(function(e) {
var val = document.getElementById('exampleInputEmail1').value;
$('#exampleInputEmail1').val(val.substring(val.indexOf("=") + 1, val.indexOf('&')));
});
});
</script>

submitting a form with link

I have following form structure
<form action="{Basket-Addproduct}" method="post" id="items-form">
<button class="button-text button-gray-custom" type="submit" value="Submit" name="{dynamically generated name}"><span>Submit</span></button>
</form>
here "dynamically generated name" is the key field which tells which element or product to submit..
I want it to convert it into link,
I have tried following
Add This
Its getting submitted but not able to add the product...
Its expecting the name parameter also to be passed so it knows which product to add...
Stuck....:(
Any solution appreciated...
you should have <input type="submit".
There is no need to do JavaScript.
Just remove JS and then have as many <input type="submit" buttons as you want.
The GET/POST should have the key/value you look for.
E.g.
<input type="submit" name="item1" value="submit" />
when you click it, the recipient receives (sorry PHP used here):
$_GET['item1'] = submit
and other submits do not have value.
You can use jQuery to do this clean and easy.
So, here's your link:
<a id="form-submit-btn" href="#" name="{dynamically generated name}">Add This</a>
And your form:
<form action="{Basket-Addproduct}" method="post" id="items-form">
<!-- form contents -->
</form>
Now write a JavaScript which submits your form data on a button click:
$('#form-submit-btn').click(function(e) {
e.preventDefault();
var $form = $('#items-form');
$.post($form.attr('action'), $form.serialize(), function(data){
// do something with the data
});
});
Your code should work, I have created an example for you to test, here it is: http://jsfiddle.net/afzaal_ahmad_zeeshan/yFWzE/
<form id="form">
<input type="text" name="something" id="something" />
</form>
Submit
By using this you will submit the form using the id of it. And other user told you to use jQuery, which I am afraid you don't want to. In jQuery you use .preventDefault but if you want to stick to the simple JS then you will be using href="#" which will automatically prevent any anchor tag execution.
And the result of the request can be checked, which sadly is an error. But it makes sure that the request has been sent to the server.
Then you can test the methods and other type of executions by having some if else blocks as
if(condition == true) {
// if post
} else {
// if get
}
The parameter might be mis handled on the server side, because when the form is submitted you need to take out the data from the QueryString (the request is GET). So, you need to check that, or if that's not the issue then make sure you're pointing the element well. Otherwise if there is no such element, nothing will be sent.
I am not sure, which language you're using but here is the code for ASP.NET
var value = Request.QueryString["something"];
PHP version is already present above. That all depends on the parameters you send with the request. You are more likely to convert the code to a function. Such as
Submit
And the function
function submit() {
// create variable
var value = document.getElementById("something").value;\
// now submit the form and all that other bla bla, which
// you want to be process,
}
If you find this one tricky, using jQuery as
var values = $('form').serialize();
will be easy. This will create a string of the form and will send it with the request.

Categories