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.
Related
I have a PHP submit form, within that form I have a PHP image gallery that displays images from a folder. (I have a dropdown to select images from different folders).
When I click on an image from the gallery the path to that image is entered into an input field so it can be linked to the other information when submitted.
My problem is when I choose a different image gallery folder from the dropdown it submits the form. I understand why it does this, but am unsure how to change the way it uses PHP to choose different folders to JS/JQ so there is no need for a submit or refresh.
Here is the relevant code...
<script>
function change(){
document.getElementById("myfolders").submit();
}
</script>
$subF = $_POST['otherFolders'];
<form id="myfolders" method="post">
<select name="otherFolders" onchange="change()">
<option selected="selected">Other Galleries</option>
<?php
$otherFolders = $dirs2;
foreach($otherFolders as $item){
?>
<option value="<?php echo $item; ?>"><?php echo $item; ?></option>
<?php
}
?>
</select>
Thanks for any help
I believe that you dont want to refresh the page when a user clicks on submit. There is very limited info from the question, so I cannot provide changes to your code. But, what you want to do is either prevent the form from submitting by using the preventDefault(); function in JS and then reading the form elements, submitting an aJax request to your server (PHP), and using the server response to display on the page.
If you do not want the form to even submit, you can just make a button that does not submit a form, but simply has an onClick event that reads the form elements and does the same as above.
Form submit will always refresh the page if not prevented. If an action attribute is not provided, it will default to submitting the form to the current page.
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>
I'm Writing a PHP Programming with the database, I submit the form data to be inserted into the database at the same page but when it is reload it gives the respected error. I want to block the reload of the page using javascript or jQuery but I did not get any idea for it.
<!DOCTYPE HTML>
<html lang="en">
<head><title>Title</title></head>
<body>
<form method=post>
<label for="name">Name </label>
<input type=text name=name size=30>
<br/>
<input type=submit value=Sent name=submit>
</form>
</body>
</html>
I has close the form tag before the here I could not do that.
the php script is
<?php
$conn=pg_connect("host=hostname dbname=databasename user=username password=password") or die("Error, Could not connect".pg_last_error($conn));
$rs=pg_query($conn,"insert into tablename(name) values($_POST['name']");
if($rs)
{
echo "Inserted";
}
else
{
echo "ERror is occured!";
}
?>
Consider name is a unique in database then the error is generate during resubmission of form...
It is the second step when I submit the page after fillup the form..
It occurs after the re-submission of the form
Please Help me to resolve the problem..
Thanks....
You can use javascript jquery to submit your form asynchronously. Instead of using input type submit, you can use button with attribute 'onclick' that will call your javascript function. Example of form post can be found here.
In PHP file, you need to return useful result i.e status. From that status, you can decide the behaviour of your form after received the result either to proceed to other page or show errors.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am wanting to literally take the HTML form input with the ID "bet" and after the value has been entered and submitted; get the exact input for example: '100' may be entered, as I am wanting to perform an if statement to check that the value submitted isn't less than 0 for obvious reasons so then I can stop the webpage proceeding to perform the bet, and make the user instead enter a valid amount.
The code that I am having an issue with is below, upon loading the page I am getting the error: Notice: Undefined index: bet
<form action="duel.php" name="duel" id="duel">
<input type="text" id="betamount" name="betamount">
<?php
$data = $_GET['betamount'];
echo $data;
?>
</form>
I am fairly new to programming in PHP, so any help would be greatly appreciated.
You need to assign a name to the input element. In your situation, you could use the same name as your id:
<input id='bet' name='bet' type='text' value='100' />
To get the specific data for the 'bet' input field use:
echo $_POST['bet'];
On your server to view all of the post data use the code:
// Wrapping the output in the pre block makes the POST data easier to read
echo '<pre>';
print_r($_POST);
echo '</pre>';
This is an example script you can use:
php file:
<?php
if(isset($_POST['submit'];)) {
session_start();
$text = $_POST['Text'];
echo "$text";}else {echo 'Could not load text!';}
?>
<form method="POST">
<input name="Text" type="text">
<input type="submit" name="submit">
</form
So, you would make your form method "POST' and the action the url of the PHP script.
Then, in the PHP script you would use $_POST variable which would contain all of the info that was submitted in that form. See here:
http://php.net/manual/en/reserved.variables.post.php
There is a similar variable for get requests. For hte difference in get and post methods see here:
http://www.w3schools.com/tags/ref_httpmethods.asp
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.