PHP remembers POST value after refresh - javascript

I've got a problem with a html form. Php seems to remember my POST value after refreshing my page. It has to do with a login form that I uses.
I'm using cookies to let php communicate with javascript, telling javascript if the user is logged in or not.
Php code:
<?php
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = MD5($_POST['password']);
echo '<script>console.log("' . $username . '", "username"); </script>';
echo '<script>console.log("' . $password . '" , "password"); </script>';
/* against sql injections */
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = "SELECT user_id FROM User WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row[user_id]){
$cookie_name = "login";
$cookie_value = "1";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
} else{
echo '<script> alert("Incorrect username and password combination");</script>';
}
}
?>
The form:
<form method="POST" id="loginForm">
<b>Login</b>
<table style="margin-top: 10px">
<tr><td>Username: </td><td><input type="text" name="username" placeholder="username" required="required"></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" placeholder="password" required="required"></td></tr>
<tr><td><input type="submit" name="login" value="Login" style="margin-top: 5px"></td></tr>
</table>
</form>
Because I love javascript, I'm using a ajax call to communicate with php and the server database.
Javascript code:
function openPage(page) {
var content;
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
document.getElementById('contentMiddle').innerHTML = data;
}
});
}
}
The problem is whenever I try to refresh the page, my php code will always run and $_POST['username'] and $_POST['password'] will always have the POST value from before refreshing the page.
I always make sure I remove the cookie before refreshing the page.
Any idea?

You've most likely already submitted the page and by hitting refresh the browser is attempting to send the POST data along with the refresh.
Since you're using Ajax to process your form you can/should remove type="submit" from the login button since there's no need for it. Instead you can have Login.
Then update your Ajax to run when the button is clicked. You can also use jQuery to get your elements by ID, for example:
$("#btn_login").on("click", function() {
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
//document.getElementById('contentMiddle').innerHTML = data;
$("#contentMiddle").html(data);
}
});
});
To address the comment by #charlietfl, handling an Enter press to submit the form you'd use something like this.
document.onkeydown = function(){
if(window.event.keyCode=='13'){
$("#loginForm").submit();
}
}

Related

How to post both a javascript variable and a html form via $.ajax post?

I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz

How to make AJAX request to SQL, and change what's displayed on the DOM?

I have this code to display a user's name:
<div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div>
I'd like to change what's displayed in <span id="output"></span> when a user changes their profile.
This is what I use to change their profile data in the database (shortened to only include what's needed):
<form action="" method="POST">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<button type="submit" name="submit">Submit</button>
</form>
if (isset($_POST['submit'])) {
$username = $_SESSION['username'];
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($connect, $query) or die(mysqli_error());
$profile = mysqli_fetch_assoc($result);
$update = "UPDATE users SET firstname = '$firstname' WHERE username = '$username'";
$result2 = mysqli_query($connect, $update);
if (mysqli_query($connect, $update)) {
$_SESSION['firstname'] = $firstname;
echo 'Profile updated successfully';
}
}
The thing is, I don't know how to change the "output" to the new $_SESSION['firstname'] without refreshing the page.
I would assume that I'd need to use JQuery's ajax function, but I'm not sure how to specifically use this function to get it done.
A lot of things are wrong with the code. Besides that point here is a simple ajax request.
$('.submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'yourscript.php',
data: {firstname: $('#firstname').val()},
success: function(data){
$('#firstname').html(data);
}
});
})
And for PHP:
# 'yourscript.php',
if(isset($firstname = $_POST['firstname'])){
// do your stuff.
echo 'your new data you want to display';
} else {
echo 'something went wrong';
}

Login with POST Form, which trigger a javascript validation, and AJAX to a PHP file. Trouble storing data to PHP

Brief
I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page ("Map.php").
I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.
In details
I want to do a "Login.php", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.
Upon validation, I will use AJAX to call another php file called "Auth.php", which will have make a connection with a MySQL database, to search for that particular user verify the user.
The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page ("Map.php") upon successful login.
Below are parts of my codes in the "Login.php" and "Auth.php".
Login.php
<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
</div>
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
</fieldset>
</form>
<script>
function validateForm() {
//event.preventDefault();
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email == null || email == "") {
alert("Email must be filled.");
return false;
}
if (password == null || password == "") {
alert("Password must be filled.");
return false;
}
if(re.test(email)) {
var data = {
"email": email,
"password": password
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "auth.php",
data: data,
success: function(data) {
alert("You have successfully logged in!");
// TODO store user details in session
return true; // return true to form, so will proceed to "Map.php"
}
});
return false;
}
else {
alert("You have entered an invalid email address!");
return false;
}
return false;
}
</script>
Auth.php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid=true;
if (isset($_GET['email']) && isset($_GET['password'])) {
$email = addslashes($_GET['email']);
$password = addslashes($_GET['password']);
} else {
$valid = false;
$arr=array('success'=>0,'message'=>"No username or password!");
echo json_encode($arr);
}
if($valid == true){
$query = "SELECT * FROM user WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Login failed");
echo json_encode($arr);
}
}
// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);
Your ajax call should be like this:
data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
console.log(response);
});
you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with

asynchronous commenting using ajax

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

Categories