Refresh page after alert box using AJAX in php - php

I'm doing a form validation in my php script, take one column as an example, if the username is not filled, an alert window will pop up and say "please enter your username", after user click "ok", the whole page refresh but the information on the form will be reset too.
So I would like to keep what the user has input after refreshing the page, how can I embed the code in php using AJAX?
//username validation
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
the website is in php file, html code is embedded under the php stuff, and this is the form in the html
<div id="account">
<form method="POST">
<p><span class="error">* required field.</span></p>
Username:
<input type="text" name="Username">
<span class="error">* </span><br>
<!--other fields..-->
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="signup_button">
</form>
</div>

<?php
if(isset($_POST['signup_button'])){
$Username = $_POST['Username'];
}
?>
or...
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
/* save the value in the browser */
echo 'window.'+VarYouWantToKeep = $_POST['VarYouWantToKeep'];
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
( or use localStorage, instead of window. https://developer.mozilla.org/en/docs/Web/API/Window/localStorage )
Then, when the page loads, check if('window.'+VarYouWantToKeep)
and if it's there, set it as the value="" of the corresponding form field

try this (This is taking into account you set $username to $_POST["Username"];)
<input type="text" name="Username" value="<?php if(isset($_POST["signup_button"]) && $_POST["signup_button"]=="Submit") {echo $username; ?>"

To store variable data, you will need to use $_SESSION variables in PHP. Make sure that session_start() is at the top of the PHP page.
Here's a basic example:
//this PHP page contains the HTML form
<form>
<input type="text" value="<?php echo $_SESSION['email']; ?>" />
</form>
//ajax
$.ajax({
url:'validate.php',
type:'POST',
data:{name:inputName}
}).done(function(data){
alert(data);
});
//php page
session_start();
if(!isset($_POST['name'])){
//set session variable
$_SESSION['email'] = $_POST['email'];
//this will be sent back to PHP page with HTML
echo 'Please enter username';
}

I coded here, a super cool login page with bootstrap as you expect. Link bootstarp cdn in your html file. This will show the error under the button instead of showing a windows classic alert box. I included ajax request and php response also with some validation.
login.html
<div class="container">
<div class="col-lg-offset-8 col-md-offset-6 col-lg-4 col-md-4 login-bg">
<form class="form-horizontal" role="form" action="#" method="">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="username" type="text" class="form-control" name="username" value="" placeholder="User Name" required tabindex="1" autocomplete="off">
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<input id="password" type="password" class="form-control" name="password" value="" placeholder="Password" required tabindex="2" autocomplete="off">
</div>
<br>
<div class="form-group">
<div class="col-lg-6">
<button class="btn btn-primary-outline btn-block" type="submit" id="login">Login</button>
</div>
<div class="col-lg-6">
<button class="btn btn-success-outline btn-block" type="reset">Clear</button>
</div>
</div>
<br>
<div id="login-feedback" class="btn-block"></div>
</form>
</div>
</div>
myStyle.js
<script type="text/javascript">
$(document).ready(function()
{
$('#login').click(function()
{
var uname=$('#username').val();
var pword=$('#password').val();
if(uname!='' && pword!='')
{
$('#login-feedback').text('validating....');
$.post("login-check.php",{username:uname,password:pword},function(data)
{
if(data=="success")
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','green').fadeTo(1000,1,function()
{
document.location='index.php';
});
});
}
else
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','red').fadeTo(900,1);
//reset form
$('#login').trigger("reset");
});
}
});
return false;
}
else
{
$('#login-feedback').text("Please enter all fields").css('color','purple');
}
});
});
</script>
login-check.php
<?php
//include connextion file;
if(!isset($_SESSION))
session_start();
$username=trim($_POST['username']);
$password=$_POST['password'];
$username=mysqli_real_escape_string($con,$username);
$password=mysqli_real_escape_string($con,md5($password));
if(($username) && ($password))
{
$query = mysqli_query($con,"select * from login where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows>= 1)
{
$fetch_result = mysqli_fetch_array($query);
session_regenerate_id(true);
$_SESSION['username']=$fetch_result['username'];
$_SESSION['status']=$fetch_result['status'];
// Close session variable assigns
session_write_close();
echo "success";
}
else
{
echo 'Login failed';
}
mysqli_close($con);
}
?>

Related

Login session doesnt work "Hello, $_SESSION[name]" [duplicate]

This question already has answers here:
When do I have to declare session_start();?
(2 answers)
Closed 1 year ago.
I did the register part and everything went well. I have reached the part where the user must log in to the site. The problem is that if I enter the wrong data in the login page, I get a message that the data is wrong.
But if I add the correct data for login, it redirects me to index.php, but the header does not change. Normally instead of the login and registration button, something like this should appear: Hi, Andrew. And a logout button.
Index header with login and register buttons
<?php
if(isset($_SESSION['id'])){
echo "<a href='login.html' class='login-panel'><i class='fa fa-user'></i>Salut, $_SESSION[name]. </a>
<button type='button' class='btn btn-light'>Logout</button>";
}
else {
echo " <a href='login.html' class='login-panel'><i class='fa fa-user'></i>Login</a>
<a href='inregistrare.html' class='login-panel'><i class='fa fa-user-plus'></i>Înregistrare</a>";
}
?>
Login form from login.php
<form method="post" action="login.php">
<div class="form-group">
<label for="email">* Adresa de e-mail:</label>
<input type="text" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password">* Parola:</label>
<input type="password" id="password" name="password" class="form-control" required>>
</div>
<div class="form-group gi-check">
<div class="gi-more">
<label for="save-pass">
Salvează parola
<input type="checkbox" id="save-pass">
<span class="checkmark"></span>
</label>
Ai uitat parola?
</div>
</div>
<div class="form-group">
<button type="login" name="login" class="site-btn login-btn">Intră în cont!</button>
</div>
</form>
login.php
session_start();
include('config.php');
// Cod pentru logare
if(isset($_POST['login']))
{
$password=$_POST['password'];
$dec_password=$password;
$email=$_POST['email'];
$ret= mysqli_query($con,"SELECT * FROM utilizatori WHERE email='$email' and password='$dec_password'");
$num=mysqli_fetch_array($ret);
if($num>0)
{
$extra="index.php";
$_SESSION['login']=$_POST['email'];
$_SESSION['id']=$num['id'];
$_SESSION['name']=$num['nume'];
$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
else
{
echo "<script>alert('Nume sau parola invalide!');</script>";
$extra="index.php";
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
exit();
}
}
?>```
Kindly check that have you manage exception if condition not satisfied. also if you enter wrong data and once you logout you have to update code for session_destroy() . other wise same session has be called next time as well. I hope it will help to you.

How to Show Progress/Loading While data is added to MYSQL using PHP

I am creating a user registration form and i want to show a loading/progress on my page as soon user click submit button. Here Is my code please suggest me something to achieve this. here below is process.php file
if(isset($username)){
$con = new dbConnection();
$con->connect();
$con->add_user($username,$email,$password,$contact);
$db_class = 'ui success message';
$db_message_header = 'header';
$db_header_message = 'Your user registration was successful.';
$db_msg= 'You may now log-in with the username you have chosen';
$form_load = 'loading'; //Class for adding loading class
sleep(4);
header('location:index2.php');
}
Here is index.php
<form class="ui form attached fluid segment <?php echo $form_load; ?>" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="form">
<div class="field">
<label>Username <span id="err">*</span></label>
<input placeholder="Username Name" type="text" name="username" class="ui input success" value="<?php if(isset($username)){echo $username;} ?>" required>
</div>
<input type="submit" name="submit">Submit</input>
</form>

show message success when confirm a form by ajax & jquery

when user write her email for Newsletters, i want to show them a suuccess message
newsletter.php
<?php
$templates="templates/";
require_once 'includes/init.inc.php';
//require_once 'includes/classes/email.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (($result=mail::add_newsletter($_REQUEST['email'])) >0) {
Util::Redirect("index.php");
} else {
echo 'you register befor';
}
}
?>
footer.php
<form action="newsletter.php" method="post" class="searchform" >
<input type="text" placeholder=" type your email" name="email" />
<button type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p >come on with us to know everything for us</p>
</form>
Use session to store success message, and you can print it after redirect.

Displaying differnt border color if field is valid

So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});

php ajax post data without refresh but saving to session only works with refresh

I have been stuck on this problem for two days now. I've found the code to post data without refresh but it seems that if it doesn't refresh, the values aren't actually saved to the $_SESSION superglobal.
my jquery code:
$('.login_error').hide();
$('#sublogin').click(function(){
$('.login_error').hide();
var jusername = $('#loginusername').val();
var jpassword = $('#loginpassword').val();
if(jusername == ""){
$('label#username_error').show();
//return false;
}
if(jpassword == ""){
$('label#password_error').show();
return false;
}
var dataString = 'loginusername='+jusername+'&loginpassword='+jpassword;
$.post('login.php', dataString, function(data) {
$('#header').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500)
});
// return false
});
My login.php code:
<?php
//set the variables
$username = isset($_POST['loginusername'])? $_POST['loginusername']:'';
$password = isset($_POST['loginpassword'])? $_POST['loginpassword']:'';
$step = isset($_POST['step']) ? $_POST['step'] : '1';
if($step=='2'){
//validation is done in javascript
//if there are no errors
if(empty($loginErrors)){
//sanitizes data for use in query.
$username = trim(mysql_real_escape_string($username));
$password = md5(trim(mysql_real_escape_string($password)));
$query = "SELECT user_level, username, password FROM user WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die('query did not go through');
if($result!=false){
$query_row = mysql_fetch_assoc($result);
$_SESSION['user_level']=$query_row['user_level'];
$_SESSION['username']=$query_row['username'];
$_SESSION['password']=$query_row['password'];
}
}
}
if($step=='1'){
?>
<form class="login_fields" id="login_fields" name="login" method="POST">
<input type="hidden" name="step" value="2"/>
<div class="dtable">
<div class="dtr">
<span class="dtd">
<label name="name_label" for="username_box"> Username </label>
</span>
<span class="dtd">
<input type="text" id="loginusername" name="loginusername" maxlength="25" value=""/>
</span>
<span class="tdt">
<label for="username" id="username_error" class="login_error">Username field can not be blank</label>
</span>
</div>
<div class="dtr">
<span class="dtd">
<label name="pass_label" for="username_box"> Password </label>
</span>
<span class="dtd">
<input type="password" id="loginpassword" name="loginpassword" maxlength="20" value=""/>
</span>
<span class="tdt">
<label for="password" id="password_error" class="login_error">Password field can not be blank</label>
</span>
</div>
<div class="dtr">
<span class="dtd">
<input type="submit" name="sublogin" id="sublogin" value="login"/>
</span>
</div>
</div>
<div class="output" id="output" name="output">
</div>
</form>
<?php
}
?>
Edit: Ah yes I forgot to mention.
login.php is included in my headers file and my headers file is included in my index.php file so the session_start should cascade.
Edit 2: So if I set the return to false near the last line of the jquery code the page doesn't reload which is exactly what I want but the session isn't saved at all. Anyone able to figure out whats wrong with what I'm doing?
You should declare session_start(); at the top of your PHP script, otherwise the SESSION data won't be remembered!!

Categories