Back Button History: Skipping Page After multiple POST - javascript

I have a php page with a form that submits to itself. On this same page I have a button that uses a javascript function to go back to the previous page.
My issue is that I want to avoid going back to the same page as it is possible to submit to the form multiple times and I cannot use a link because there are multiple ways to access this page.
Current script function:
<script type="text/javascript">
function goBack() {
window.history.back();
}
</script>
... to further clarify I am happy with the way the form is posting multiple times, I just need to fix the back button issue. Thanks!

Solution:
<?php
$previous = $_SERVER['HTTP_REFERER'];
if (isset($_POST["submit"])) {
$previous = mysqli_real_escape_string($link, $_POST['previous']);
}
?>
<html>
<form>
<input id="previous" type="hidden" name="previous" value="<?php echo $previous;?>">
...(rest of form)
</form>
BACK BUTTON
</html>
</form>

Related

Stop refreshing on submit button [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 4 years ago.
Is there any way to stop refreshing the page on submit button if your if condition goes false and show all the input fields with values entered?
Since you mentioned PHP, then why not use it?
I assume your question has two parts like below.
Part one - you wrote:
show all the input fields with values entered
By above, you mean using $_SESSION to repopulate the fields with the submitted data?
Part two - you wrote:
Is there any way to stop refreshing the page on submit button if your if condition goes false
Note that submit and any on is an event within the client side processing scope. You can use jQuery or JS validations for that.
Here below are two files for your learning test.
The posting php:
<html>
<body>
<form action="action.php" method="POST">
<input type="text" name="feedback" value="" />
<input type="hidden" name="token" value="123456ABCDEF" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?
session_start();
$token = '123456ABCDEF';
if(isset($_SESSION)){
if($_SESSION['token'] == $token){
echo "Your feedback:<br />";
foreach($_SESSION as $field=>$value):
echo $field.": ".$value."<br />";
endforeach;
}else{
echo " Bad token! Cross-Site Request Forgery (CSRF)";
}
}else{
echo "Nothing!";
}
The posted to php:
<?php
session_start();
$_SESSION = $_POST;
$_SESSION['message'] = "Thank you for the feedback!";
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
Hope I got you right and above helps.
First off, this is a duplicate of JavaScript code to stop form submission
Now, when we got that out of the way, here is abrief explanation. You cannot prevent the browser itself from refreshing. But what you can do is prevent the form from being submitted (and in turn causing a refresh). And this is the usual solution when dealing with form validation in JS.
You can check the abode linked answer for more details.
You can use Post / Redirect / Get Pattern. If you have errors redirect to same page with form and show errors. You can't just "stop" the form during POST.
Other way if you don't want "showing" any redirect you can use ajax request. Form wont "blink".
You can also use javascript for checking field onchange event of input elements.

How to submit a form on page load without using jquery in AngularJS?

I have a form in AngularJS application. I need to auto submit this form upon page load without using jquery because of cross domain issue.
When I submit the form by using a submit button it works and the target url loads in the browser. If I remove the submit button and try to submit in the onload event,
it does not work. The page displays just ";". Any idea why onload does not work here? Thank you!
<form name="myForm" method="post" action="#Model.Settings["URL"]" ng-controller="PostCtrl">
<input type="hidden" name="Name" value="{{Details.Name}}">
<input type="hidden" name="Amount" value="{{Details.Amount}}">
#*<button type="submit" class="action blue"><span class="label">Click here</span></button>*#
<script>
window.onload = function () {
document.myForm.submit();
}
</script>
</form>
I have some suggestions for you. But first you have to add an id to your form: 1: Go to your <html> element and call the onload function there --> <html onload="document.getElementById('yourform').submit();"> or 2: call the JavaScript function with php
<?php
echo "<script>document.getElementById('yourform').submit();</script>";
?>
Or 3: try to change your Script to
<script>
window.onload = function () {
document.getElementById('yourform').submit();
}
</script>

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 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.

Why doesn't javascript redirect work?

I have a form that should redirect the user to a page when clicking the Delete button. This is the only object in the form.
<input type="submit" name="delete" value="Delete" class="submitbutton" id="submitbutton" onclick="Redirect();">
Unfortunately the redirect is not working:
<script type="text/javascript">
function Redirect()
{
alert('b');
window.location="http://www.tutorialspoint.com";
}
</script>
The alert is displayed. Then nothing happens. I also tried window.navigate. I am pulling my hairs out.
There is a session in the beginning of a page if that matters:
<?php
session_start();
?>
<html>...
I tried in chrome and firefox. I am clearly missing something.
It's probably running your script and then submitting the form.
You should use:
<input type="button" ...>
Instead of:
<input type="submit" ...>
It was in front of my eyes the whole time:
The accepted solution on this page:
Try to combine javascript confirm box with php post method?

Categories