HTML form doesn't reset after page refresh - javascript

I complete the following HTML form in my "main" page(main.php):
<form action="sessions.php" method="post">
<input type="" placeholder="Insert Database Name" name="dbName" id="dbName">
<input type="" placeholder="Insert Server Name" name="serverName" id="serverName">
<input type="" placeholder="Insert User Name" name="userName" id="userName">
<button type="submit" name="Submit" id="sub">Connect</button>
</form>
When the user presses the "Submit" button(I made it to not refresh the page), the form data are posted to another page(sessions.php):
<?php
session_start();
$_SESSION['dbName'] = $_POST['dbName'];
$_SESSION['serverName'] = $_POST['serverName'];
$_SESSION['userName'] = $_POST['userName'];
$_SESSION['password'] = $_POST['password'];
?>
Then, those data are read from another page(graphs.php):
<?php
session_start();
$serverName = $_SESSION['serverName'];
$userName = $_SESSION['userName'];
$password = $_SESSION['password'];
$dbName = $_SESSION['dbName'];
?>
When I refresh the page, the form data are preserved.
How to delete them after page refresh?

Use session_destroy() after you have handled the data (stored in database, performed calculation etc.) HTTP is a stateless protocol, so refreshing the page would not update your session variables because it is the PHP server that is handling the session, completly unrelated to a page refresh.

`Hey Try this with the function method above input methods..
create a simple function
using onclick method in the submit button and put the values=null in side the function
eg.
"function clearForm() {
document.myform.reset();
}"
But the session_destroy(); for deleting the whole session.
And
"session_unset(); would delete only the variables from session - session still exists. Here Only data is truncated."
They both are better option.`

Related

PHP Form Submit (save data into a text file) not working

So I do have a form on my web page and I would like to save user's input (email in my case) each time the Submit button is clicked.
HTML:
<form id="email-form" method="post">
<div class="form-group">
<input type="email" class="form-control" placeholder="ex: john#gmail.com" name="email" required>
</div>
<div class="form-group">
<input type="submit" class="cta animated-cta" name="submit" value="Continue">
</div>
</form>
PHP:
<?php
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$file = fopen('list.txt', 'a');
fwrite($file, $email);
fclose($file);
}
?>
The problem is that nothing happens, while the code seems to be correct.
Things I've tried: Created myself the list.txt file (thought it doesn't get created automatically) | Put the script on my host to see if there's any difference (I coded it locally) | Added a PHP redirect to see if the code is executed once I click the button but isn't the case.
P.S: I do have a 'event.preventDefault();' in my javascript file which is executed once the Submit button is clicked (because I don't want the page to refresh once I click). Hovewer I've removed it but nothing changed.
Thank you in advance!

PHP link builder to avoid use of Java Script and hide the old URL

I'm creating a login page that accepts a username and then redirects the user to log in. This is currently done, and works with the following Java Script.
function process()
{
var url="https://example.com/users/profile" + document.getElementById("username").value;
location.href=url;
return false;
}
<p>Enter your username</p>
<form onsubmit="return process();">
<input type="text" name="username" id="username">
I'd prefer to do this without using Java Script to support users that disable it, older browsers and to hide this from the source code of the page. The subdirectories are protected anyway but I just want the added compatibility.
I'm attempting to do this with PHP instead;
<form action="/authenticate.php">
<input type="text" name="username" id="username">
I'm using the same form but have created a page called authenticate.php instead. All that authenticate.php contains is;
<p>Authenticating…</p>
<?php
$username = ["username"];
header("Location: https://example.com/users/profile/$username"); die();
?>
If steve was the input, I'd expect that to then redirect to https://example.com/users/profile/steve but it doesn't. I've set up redirects already to handle errors and the form translates text to lowercase anyway.
I'm just wondering why;
<?php
$username = ["username"];
header("Location: https://example.com/users/profile/$username"); die();
?>
won't work with the addition to the URL but does work without the $username so that's the only error. I also tried $username = $POST_["username"]; but that's not relevant and doesn't seem to work either. The current code takes me to https://example.com/users/profile/Array
If someone could advise on the correct way to do this I'd very much appreciate it.
By default form method is GET but the best practice is to mention it so you've to do:
<form action="/authenticate.php" method="get">
<input type="text" name="username" id="username">
</form>
And authenticate.php you need to get input value:
<p>Authenticating…</p>
<?php
$username = $_GET["username"];
header("Location: https://example.com/users/profile/$username");
die();
?>

Make pre-populated PHP form submit on page load

I've got a working PHP form that I've built and it contains 5 fields which are pre-populated by a URL query string.
The query string URL is on a hyperlink on an HTML email asking the recipient to click here to make a booking. I've got their details already because I've sent them the email, hence why the form get pre-populated.
How can I get the form to instantly submit on page load and redirect to the thank you page?
Here's how my form looks at the moment:-
<form name="frm" id="frm" method="POST">
<input name="firstname" id="firstname" type="text" value="<?php echo ((isset($_GET["firstname"]))?htmlspecialchars($_GET["firstname"]):""); ?>" />
<input name="lastname" id="lastname" type="text" value="<?php echo ((isset($_GET["lastname"]))?htmlspecialchars($_GET["lastname"]):""); ?>" />
<input name="email" id="email" type="text" value="<?php echo ((isset($_GET["email"]))?htmlspecialchars($_GET["email"]):""); ?>" />
<input name="company" id="company" type="text" value="<?php echo ((isset($_GET["company"]))?htmlspecialchars($_GET["company"]):""); ?>" />
<input name="contactid" id="contactid" type="text" value="<?php echo ((isset($_GET["contactid"]))?htmlspecialchars($_GET["contactid"]):""); ?>" />
<input type="submit" name="Submit" value="submit" />
</form>
And here's the JavaScript I've tried (but didn't work):-
window.onload = function() {
setInterval(function(){
document.getElementById("frm").Submit();
},5000);
}
Here's a pastebin of the whole page: http://pastie.org/private/lgpealjya8xrwqi78gropw
Thanks
Alright so basicaly you have been trying to get information through url, insert them in a form and then submit the form so you can send an email. This is all quite nice although you're just making things harder than they are.
You you need to do is wipe off the form (we don't need this really) and instead of processing all those $_POST information you wanted to get off the form, you gonna do that with the $_GET array you already got off the url, at the end of the day it's exactly the same since the informations you're inserting in the form are only the ones you're getting off the url.
So if you change this the following way, youe script will work just fine :
//Get the submitted data
$firstname = cleanText($_GET['firstname']);
$lastname = cleanText($_GET['lastname']);
$email = cleanText($_GET['email']);
$company = cleanText($_GET['company']);
$contactid = cleanText($_POST['contactid']);
So here is what's gonna happen : the user is going to clic on a link, your script is going to get the $_GET array, process it, send the email based on this array, and this send the user to the thankyou.php page. Note that you could get your script to be more efficient and save the user some time if you insert your script in the thankyou.php.
Last but not least I would like to point out to you that it's not very good practice to get an email sent on url submission... you could end up having a bot send massive amounts of emails through this url and get you email blacklisted. If I were you I'd either control the ip and make sure only 1 mail is sent every 10 minutes or whatever time suits your needs best, or i'd add a captcha to the page so the user would need to show he's a human being who actualy wants to waste some time sending email.
try using: document.getElementById('frm').submit(); instead of document.getElementById('frm1').submit();
and also make it execute once the page has been loaded:
window.onload=function(){
document.getElementById('frm').submit();
}

Redirect user back to registration page but keep their filled in form in php

I have a registration.php page and another registration_checker_page.php.
If username and / or email is taken after they submit, then it'll redirect them back to the previous (registration) page.
But then their filled in data is lost. Is there a way to redirect them without clearing their data?
if(mysql_num_rows($queryUser) > 0){
echo '<p><div id="redirect"/></p>';
}
function redir {
code ... location.href = "registration.php";
}
Edit: By filled data it is first name, username, postcode etc. But other information like password etc will be removed.
You can use session or cookie for same
if(mysql_num_rows($queryUser) > 0){
echo '<p><div id="redirect"/></p>';
}
function redir() {
$userName = $_POST['username'];
$email = $_POST['email'];
setcookie("userName", $userName, time()+3600); /* expire in 1 hour */
setcookie("emial", $email, time()+3600);
code ... location.href = "registration.php";
}
And at your form
<input type="text" name="userName" value="<?php echo isset($_COOKIE['userName']) ? $_COOKIE['userName']:'' ?>">
<input type="text" name="email" value="<?php echo isset($_COOKIE['email']) ? $_COOKIE['email']:'' ?>">
You can above same with using session.
Hope this will help
The best way to solve this, in MNSHO[1], is to make sure those values are never lost in the first place.
Lets assume, for the same of discussion, that you have a field in your HTML called 'username'
If you are using a GET (or a regular redirect), you can include username as part of the
querystring, so it is available on the registration page.
window.location.href = "registration.php?username=" . $_REQUEST(username);
And then, on your registration page:
<input name="username" type="text">
What you'd want to do is look and see if you have an existing value that came in.
<?php
$usernameValue = "";
if (isset($_REQUEST['username'])) {
$usernameValue = $_REQUEST['username'];
}
// Typing on the fly, I may have the type of quotation marks
// flipped around. N
echo '<input name="username" type="text" value="$usernameValue">';
// or this...
echo "<input name='username' type='text' value='$usernameValue'>";
?>
Now, if you are redirecting to this page from another...
[1] My Not-So-Humble Opinion
You could save them a get variable and append that to the file you are referring them too, or do it server side and save them by a temporary ID.
First possibility:
location.href="registraion.php?e=thisdudes#ema.il&u=thisdude"
Use AJAX to check for duplicate username/email immediately after the textbox loses focus and notify the user accordingly. That is how modern pages do it.
Is there a reason why you are waiting for the user to fill the complete form before checking for duplicate username/email?

reload form on submit with latest post data

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);

Categories