I have a simple form with a submit button (below). I am trying to let the user type in the text box then when he/she clicks submit the page will refresh and echo out what they typed in a div. The data the user types is stored in a database before being echoed. The problem is that when I click submit, the input doesnt show immediatly. I have to click refresh for it to show and when I do my browser gives me a popup (safari) asking to resend the data. This will result in duplicate data inserted in the DB. I have a feeling I need to use javascript and I could also make it more elegant with a fadeIn, but I dont know how to do that. I guess I'm asking if there's a way to use javascript to take a user's text and insert it into a mysql DB and also display it after submit is clicked all on 1 or 0 (prefereably) refreshes. thanks
Here's my code:
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
<?php
$input=$_POST['text'];
$put=mysql_query("INSERT INTO table VALUES ('$input')");
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo "</div>";
?>
I would put the php statements before you're actual html code and would modify you're code like this
<?php
if (isset($_POST['text']))
{
$input = mysql_real_escape_string($_POST['text']);
$put=mysql_query("INSERT INTO table VALUES ('$input')"); //At this point the info has been put inside the DB
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo mysql_query("SELECT * FROM table");
echo "</div>";
}
?>
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
The reason why you don't see it is that the HTML is loaded before you php I think. So I would do a php page where all the sql treatement would be done and once that is done recal you index.php and in there query you're information from the database.
Setting aside SQL injection attacks your code is vulnerable with, the standard practice is to respond to the POST with a redirect back to where the form was. In your case, it will be the page which runs SELECT from table.
No need to use AJAX here. Just make sure that you do one of the following:
Make sure you SELECT from the DB after you have INSERTed the data.
Better, is that if ($_SERVER['REQUEST_METHOD'] == 'POST'), then rather than performing an extra SQL query, just display the POSTed value since you already know it.
A side note on your code sample. If you don't have magic_quotes enabled, it's susceptible to SQL injection, so make sure you properly escape user input before using it in queries.
Related
I have already refered to this question and the accepted answer did not work for me: How to get input field value using PHP
This is my code result.php file:
...
<th>
<form name="form" action='checkout.php' method='POST'>
<input class='mx-2' type='number' id='price' name='price' placeholder='Donation Amount'">
</form>
</th>
<script
src='https://checkout.stripe.com/checkout.js' class='stripe-button'
data-key='key'
data-amount=get value of input field with id price here
data-name='Name'
data-description='Description'
data-currency='usd'
data-locale='auto'>
</script>
...
I have also tried fetching the value of the input like this and then using that variable:
<?php $price = isset($POST['price']) ? $POST['price'] : 0; ?>
Another method I tried:
<?php
$htmlEle = "<span id='SpanID'>Span Sports</span>";
$domdoc = new DOMDocument();
$domdoc->loadHTML($htmlEle);
$spanValue = $domdoc->getElementById('SpanID')->nodeValue;
I found the above snippet on https://phpcoder.tech/how-to-get-html-tag-value-in-php/ and modified it as per my need but did not work.
How can I do this? My app is pay what you want so I want the price to be filled in by the user on the client side.
I am open to different approaches and solutions to the one I asked for.
If you don't want to wait for the client to submit the form, you will need some javascript as PHP is a server-rendering language.
Basically you would need to set-up a listener on the input and after the client types the data in a format you want and you validate it, you can pass that to stripe script.
<th>
<form name="form" action='checkout.php' method='POST'>
<input class='mx-2' type='number' id='price' name='price' placeholder='Donation Amount'">
<input type="submit">
</form>
</th>
submit button in missing here, so add a submit button.
And update your PHP code
<?php $price = isset($_POST['price']) ? $_POST['price'] : 0; ?>
$_POST - is PHP Superglobals for getting form's post values.
$POST (which you are using) is a normal PHP variable.
Please update your code like this.It will works.
You have used the wrong POST syntax, the correct is: $_POST, while you are trying get: $POST.
The docs: https://www.php.net/manual/en/reserved.variables.post.php
--In JavaScript part--
If you want to handle PHP the price before call Stripe, you should use other configuration, because this one will not work anyway.
You can:
call Stripe on like ajax or other request that in background post the forst
call Stripe on other page
don't do form, just plain text field (if you don't need PHP, handle price before Stripe request)
It depends what you want to do.
I used a different method to solve the problem. I put the text box on a separate page and the pay button on the checkout page, so I am passing the price from the previous page to the checkout page now and accessing it using query parameters
<form name="form" action='checkout.php' method='POST'>
<input class='mx-2' type='number' id='price' name='price' placeholder='Donation Amount'">
<button name="submit" type="submit" >submit button</button>
</form>
///in checkout.php code
if(isset($_POST['submit']){
$price = $_POST['price'];
echo $price;
}
///I hope this would work
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.
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.
I have code that queries an SQL database and displays all of the users in a table, that all works fine, from there you are able to click any user and it displays another table that contains all of their information, that also works fine.
The problem I am running into here is on the page that displays the table of the selected users information. On that page I have a button that allows the user information to be edited and update the DB.
Here is the code for the button:
print "<form method='post' action='adminedituser.php'>
<input type='hidden' name='id' value='$id' />
<input type='submit' value='Click here to edit this user' />
</form>";
When I click this it takes me to a page with an input box that needs to display the current username and allow the user to put in a new value and submit.
I'm trying to call a php variable inside of the HTML form I have:
<?php
$id = filter_input(INPUT_POST, "id");
//Make db connection
$conn=mysql_connect("localhost","root","")or die(mysql_error());
//Step 2: select your db to use
mysql_select_db("final",$conn);
//Step 3: Write the sql that we want to run against the database
$result = mysql_query("select id, firstname, lastname, email, phone, username, password, favchar, bio from user where id=$id");
$username = $result["username"];
?>
<form method='post' id='myForm' name='input' action='adduser.php'>
Username: <input type='text' value="<?php echo ($username); ?>" id='uName' name='uName'>
<input type='submit'>
</form>
The problem is that the variable $username is not being displayed as the text box value.
What am I doing wrong?
Firstly, if I don't say it someone else is: Use mysqli instead of mysql. You can still use the procedural style, if you want (although I can say firsthand it is VERY easy to learn the object style), you just need to do a quick brush up on mysqli. Mysql is deprecated, so it is sort of useless to use. You'll have to learn it eventually, so when you're building a new program, it might be easiest.
Moving on to what you are doing wrong, is that you have not actually fetched anything. MySQL will give you an object, and then you need to sort the rows.
So, what you need to do is pull mysql_fetch_array.
You can do so like this:
while($row = mysql_fetch_array($result)) {
$username = $row["username"];
}
The form code shuld be changed to:
<input type='hidden' name='id' value='<?= $id ?>' />
You forgot to "print" the $id value.
and the code of adminedituser.php:
$id = filter_input(INPUT_POST, "id");
Get the "id" field from POST request of your form.
I have a form to post content into a database. The existing database content for the form is posted into the form as the value. enalbeing the form to show the existing database content.
On submit the database is updated and to view the newly updated content in the form the page must be reloaded.
I have produced a reload script in javascript to reload the page on submit. The page reloads but the php content doesn't update. The page still need to be reloaded manually for the new content to show up.
This is the code for my form.
<form method="POST" action="">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Javascript
function reload(){
document.location.reload(true);
}
I have also tried
window.location = window.location.href;
Both are relaoding the page but the php isn't being refreshed.
you should first update the db with submitted value before selecting the records to display in the form value.
use <?php $_SERVER['PHP_SELF'] ?> in form action.
mysql_query("UPDATE xyz SET title=$_request['title'],... WHERE id = 1") .
2.Then select query mysql_query("SELECT * from xxx where id =1").
These may solve your problem of reloading to get new values.
java script excecute only on the client side. php is Server side. you need to reload the PHP.
<form method="POST" action="<<NAME OF YOUR PHP>>.php">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Is there a reason it needs to be done with ajax? If you don't need ajax it's better to handle it with php. ajax is more work and doesn't have the same rate of success as submitting a form via php, sometimes weird things happen. You can just do a redirect after saving the form:
header("Location: /routeToYourPage&id=".$ID,TRUE,303);