jQuery Code Inside PHP File Being Displayed While Using AJAX - php

Whilst trying to use AJAX for validation on my website, it is completely displaying to the user with exception of the PHP variables, the jquery code I am using for styling my inputs. I am trying to change the styles of my inputs accordingly and provide and error message, which is successful, however, the javascript code is also being displayed
index.php
<html>
<head>
<link rel="stylesheet" href="css/template.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery/template.js"></script>
<script type="text/javascript" src="jquery/index.js"></script>
</head>
<body onload="startUp();">
<!-- Banner Image -->
<div id="banner"><img id="bannerImage" src="abcdefd.com.jpg" alt=""></div>
<!-- Body Wrapper -->
<div id="wrapper">
<!-- Content -->
<div id="content">
<!-- <h2 id="title">Log In</h2> -->
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<input class="click" type="submit" name="submit" id="submit" value="Log in">
</form>
<p id="err"></p>
</div>
</div>
</body>
</html>
index.js
$(document).ready(function(){
$("#loginForm").submit(function(event){
event.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
var submit = $("#submit").val();
$("#err").load("config/config.index.php",{
email: email,
password: password,
submit:submit
});
});
});
config.index.php
<?php
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = $_POST['password'];
$errEmptyAll = false;
$errEmptyEmail = false;
$errEmptyPassword = false;
$errEmail = false;
if(empty($email) && empty($password)){
echo 'Please enter an email and password.';
$errEmptyAll = true;
} else if(empty($email)){
echo 'Please enter an email.';
$errEmptyEmail = true;
} else if(empty($password)){
echo 'Please enter a password.';
$errEmptyPassword = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo 'Please enter a valid email.';
$errEmail = true;
}
}
?>
<script>
var errEmptyAll = "<?php echo $errEmptyAll; ?>";
var errEmptyEmail = "<?php echo $errEmptyEmail; ?>";
var errEmptyPassword = "<?php echo $errEmptyPassword; ?>";
var errEmail = "<?php echo $errEmail; ?>";
if(errEmptyAll == true){
$("#email, #password").addClass("inputErr");
}
if(errEmptyEmail == true){
$("#email").addClass("inputErr");
}
if(errEmptyPassword == true){
$("#password").addClass("inputErr");
}
if(errEmail == true){
$("#email").addClass("inputErr");
}
</script>

The config PHP file should not have any JS at all.
Don't use .load(). Use $.ajax to send POST data and listen for server responses.
Build a json_encode response on PHP which will be returned to the browser via AJAX. Read the response data (from PHP) in JavaScript jQuery via the :success property or in the .done() method of $.ajax
index.html
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" name="submit">Log in</button>
</form>
<p id="err"></p>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script srrc="index.js"></script>
index.js
jQuery(($) => { // DOM ready and $ alias in scope
const $err = $("#err");
$("#loginForm").on("submit", function (ev) {
ev.preventDefault(); // prevent browser submit
$(this).find(`[name]`).removeClass("inputErr");
$.ajax({
type: "POST",
dataType: "JSON",
url: this.action, // from form action value
data: $(this).serialize(),
}).done((res) => {
// res is the JSON Response from PHP
console.log(res); // Do with this whatever you want. i.e:
if (res.errors.length) {
$err.text(res.errors.join(", "));
res.fields.forEach(field => {
$(`[name="${field}"]`).addClass("inputErr");
});
} else {
// SUCCESS!!!
}
});
});
});
config/config.index.php
<?php
$response = (object)[
"status" => "error",
"errors" => [],
"fields" => [], // IDs of fields with error
];
if (
$_SERVER["REQUEST_METHOD"] === "POST" &&
isset($_POST["email"]) &&
isset($_POST["password"])
) {
$email = $_POST["email"];
$password = $_POST["password"];
$passwordEmpty = empty($password);
$emailEmpty = empty($email);
$emailInvalid = !filter_var($email, FILTER_VALIDATE_EMAIL);
if ($passwordEmpty) :
$response->errors[] = "Invalid Password";
$response->fields[] = "password";
endif;
if ($emailEmpty) :
$response->errors[] = "Empty Email";
$response->fields[] = "email";
elseif ($emailInvalid) :
$response->errors[] = "Invalid Email";
$response->fields[] = "email";
endif;
if (empty($response->errors)) :
$response->status = "success";
endif;
}
echo json_encode($response);
exit;

Related

How to redirect React submit button to php page

I have created a form with live validation in react, but I want to post this form to a PHP page so it gets inserted into the database. The code currently validates but doesn't allow me to access the PHP page, I have access to the SQL database which is on config page and it works well.
react js form
<!DOCTYPE html>
<?php
include ("includes/header.php");
?>
<html lang="en">
<title>Demostration of Forms in React</title>
<script src= "https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src= "https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src= "https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<body>
<h1> Register Page</h1>
<div id="root"></div>
<script type="text/babel">
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
//this.state = {value: 'Write your Name'};
this.handleChange = this.handleChange.bind(this);
this.password = this.password.bind(this);
this.manager = this.manager.bind(this);
this.phoneChange = this.phoneChange.bind(this);
this.emailChange = this.emailChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
//this.setState({value: event.target.value.toLowerCase()});
//perform validation length of the input values or others
//const textval = this.state.value;
var textval = this.state.value;
//if ((textval.length < 5) || (textval.length > 15))
//alert("Your Character must be 5 to 15 Character");
//user validation of the special characters
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < textval.length; i++) {
if (iChars.indexOf(textval.charAt(i)) != -1) {
alert ("Your username should not have !##$%^&*()+=-[]\\\';,./{}|\":<>? \nThese are not allowed.\n Please remove them and try again.");
//return false;
}
}
//if(isNaN(textval))
//alert(textval);
}
phoneChange(event){
this.setState({phone: event.target.value});
var textval2 = this.state.phone;
var iChars2 = "0123456789";
for(var j = 0; j< textval2.length; j++){
if(iChars2.indexOf(textval2.charAt(j)) == -1){
alert("Your phone number should be between 0 and 9");
}
}
}
password(event){
this.setState({password: event.target.value});
}
manager(event){
this.setState({manager: event.target.value});
}
emailChange(event){
this.setState({email: event.target.value});
var emailval = this.state.email;
var emailCheck= "#.";
for(var i =0; j<emailval.length; i++){
if(emailval.indexOf('#')>-1){
alert("Your email must contain an #");
}
}
}
//without .preventDefault() the submitted form would be refreshed
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" id="reg_name" value={this.state.value} onChange={this.handleChange} /><br/><br/>
Email:
<input type="text" id="reg_email" value={this.state.email} onChange={this.emailChange} /><br/><br/>
Phone:
<input type="text" id="reg_phone" value={this.state.phone} onChange={this.phoneChange} /><br/><br/>
Password:
<input type="password" name="reg_password" value={this.state.password} onChange={this.password} /><br/><br/>
Is this an manager account:<br/>
<input type="checkbox" name="reg_manager" value={this.state.manager} onChange={this.manager}/> <br/><br/>
</label>
<br/>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
</script>
</body>
</html>
PHP page to insert database.
<!DOCTYPE html>
<?php
include ("includes/header.php");
$firstname = $_POST['reg_fname'];
//$lastname = $_POST['reg_lname'];
$email = $_POST['reg_email'];
$phone = $_POST['reg_phone'];
$password = $_POST['reg_password'];
//$password2 = $_POST['reg_password2'];
$manager = $_POST['reg_manager'];
if ($manager='on') {
$dbadmin = 1;
}else{
$dbadmin = 0;
}
$query = "INSERT INTO users(firstname,,email,password,manager) VALUES(?,?,?,?,?)";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
//prepare and bind
if ($stmt = $dbo->prepare($query)) {
$stmt->bind_param("sssss", $firstname,$email,$hashed_password,$dbadmin);
$stmt->execute();
$stmt->close();
}
?>
<html>
<head>
<title>Registered user</title>
</head>
<body>
<h2>Registered User<?php echo ($firstname) ; ?></h2>
</body>
</html>
you can use axios in react ensuite
after you use his post and get functions ...
via the link of your API or backend
here is an example
  axios.post (http://localhost: 8800/ data /, {username: username}). then (res => {
     console.log (rec); // for example print : i get username from backen
   });

How to stay on same page after login

I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. My code is:-
index.php:-
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Registration</title>
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<!--Login div-->
<div id="logincontainer">
<form id="loginform" method="post">
<h3>Login</h3>
<div class="display-error" style="display: none;"></div>
<input type="email" name="lemail" placeholder="Enter email address" required>
<input type="password" name="lpassword" placeholder="Enter password" required>
<input type="submit" value="Sign In">
<p>Forgot Password</p>
<p id="bottom">Don't have an account yet? Sign up</p>
</form>
</div>
<div id="signupcontainer">
<form id="registerform" method="post">
<h3>Register</h3>
<div class="display-error" style="display: none;"></div>
<input type="text" name="rname" placeholder="Full Name" required>
<input type="email" name="remail" placeholder="Enter valid email" required>
<input type="password" name="rpassword" placeholder="Password" required>
<input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>
<input type="submit" value="Create Account">
<p id="bottom">Already have an account? Sign In</p>
</form>
</div>
<!--Testing refresh portion-->
<div id="after-login" style="display: none;">
<?php
echo "Hello ".$_SESSION["name"]."<br/>";
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
<!--Testing portion ends-->
</div>
<script>
$(document).ready(function(){
$("#loginform").submit(function(){
var data = $("#loginform").serialize();
checkRecords(data);
return false;
});
function checkRecords(data){
$.ajax({
url : 'loginprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(){
alert("Email/Password is Incorrect");
}
});
}
});
</script>
<!--Signup Ajax-->
<script>
$(document).ready(function(){
$("#registerform").submit(function(){
var data = $("#registerform").serialize();
signupRecords(data);
return false;
});
function signupRecords(data){
$.ajax({
url : 'signupprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
alert('You have successfully Signed Up \n Please Login now.');
setTimeout(function(){
location.reload();
},500);
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(jqXHR,exception){
console.log(jqXHR);
}
});
}
});
</script>
</body>
loginprocess.php
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);
if(empty($email)){
$errorMsg .= "<li>Email is required</li>";
}
else{
$email = filterEmail($email);
if($email == FALSE){
$errorMsg .= "<li>Invalid Email Format</li>";
}
}
if(empty($password)){
$errorMsg .= "<li>Password Required.</li>";
}
else{
$password = $password;
}
if(empty($errorMsg)){
$query = $db->prepare("SELECT password from users WHERE email = ?");
$query->execute(array($email));
$pwd = $query->fetchColumn();
if(password_verify($password, $pwd)){
$_SESSION['email'] = $email;
//Testing piece
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
exit;
}
else{
json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
exit;
}
}
else{
echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}
?>
As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it.
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"]).
IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login).
//Something like
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("span#name_placeholder").text(data.name) //return name from loginprocess.php
$("#logincontainer").hide();
$("#after-login").show();
}
The best solution would to be to create a html element like this for the
<div id="after-login" style="display: none;">
<h5 id="Username"></h5>
<?php
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
then after this include the username in the json like this
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
//$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
exit;
on the ajax call you can now access the json response with the username included and feed the span element with the username like this
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#username").test(data.username);
$("#logincontainer").hide();
$("#after-login").show();
}

Variables not passing between IF statements PHP

Okay so I'm writing a piece of code which checks a number of conditions which are set in IF statements in order to display a button to signup for a website. However, the variables I am declaring as true/false in my IF statements don't seem to be transferring over to the statement where it determined whether they are all true. Ive looked online and can't seem to find any problem like this anywhere, so i don't know if its me being stupid or there is a genuine problem. Here's my code:
<?php
include_once('db_conx.php');
//CHECKING USERNAME IS NOT TAKEN
if(!empty($_POST["username"])) {
$usernameAuth = false;
$username = $_POST['username'];
$sql = "SELECT * FROM users WHERE username='$username'";
$queryUname = mysqli_query($conn, $sql);
$username_check = mysqli_num_rows($queryUname);
if($username_check>0){
echo "Username Not Available.";
} else {
echo "Username Available.";
$usernameAuth = true;
}
}
//CHECKING EMAIL HAS NOT BEEN USED BEFORE
if(!empty($_POST["email"])) {
$emailAuth = false;
$email = $_POST['email'];
$sql = "SELECT * FROM users WHERE email='$email'";
$queryEmail = mysqli_query($conn, $sql);
$email_check = mysqli_num_rows($queryEmail);
if($email_check>0){
echo "Email already registered.";
} else {
$emailAuth = true;
}
}
//CHECKING THAT THE PASSWORDS MATCH AND ARE VALID
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
$passAuth = false;
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
if($password1 != $password2) {
echo "Your passwords do not match.";
} elseif(!preg_match("#[0-9]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Number!";
} elseif(!preg_match("#[A-Z]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Capital Letter!";
} elseif(!preg_match("#[a-z]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Lowercase Letter!";
} else {
$passAuth = true;
}
}
//CHECKING TO SEE IF ALL THE VALIDATION CONDITIONS ARE MET
if(!empty($_POST["checkinput"])){
if(($usernameAuth) && ($emailAuth) && ($passAuth)){
echo '<button id="button" class="btn waves-effect waves-light" type="submit" onclick="signup()" name="action">Register<i class="material-icons right">send</i></button>';
} else {
echo 'shite';
}
}
?>
If you need to know more or want any more pieces of the project, just say and I'm happy to provide them.
UPDATE
Added the AJAX JQUERY and index.php code:
<!DOCTYPE html>
<!--stylesheet -->
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<!-- MaterializeCSS -->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!-- fullPage.js -->
<link rel="stylesheet" type="text/css" href="fullPage.js-master/jquery.fullPage.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="vendors/jquery.easings.min.js"></script>
<script type="text/javascript" src="fullPage.js-master/vendors/jquery.slimscroll.min.js"></script>
<script type="text/javascript" src="fullPage.js-master/jquery.fullPage.js"></script>
<!--TILE SCROLLING-->
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#fullpage').fullpage({
verticalCentered: true,
sectionsColor: ['#1bbc9b', '#2c3e50', '#34495e'],
anchors: ['homepage', 'Login', 'Register'],
afterRender: function(){
//playing the video
$('video').get(0).play();
}
});
});
</script>
<!-- VALIDATING THE NEEDED FIELDS -->
<script type="text/javascript">
//CHECKING USERNAME
function UserAvailability() {
jQuery.ajax({
url: "scripts/validation.php",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
},
error:function (){}
});
}
//CHECKING EMAIL
function EmailAvailability() {
jQuery.ajax({
url: "scripts/validation.php",
data:'email='+$("#email").val(),
type: "POST",
success:function(data){
$("#email-availability-status").html(data);
},
});
}
//CHECKING PASSWORDS MATCH
function passwordCheck() {
jQuery.ajax({
url: "scripts/validation.php",
data:'password1='+$("#password1").val()+'&password2='+$("#password2").val(),
type: "POST",
success:function(data){
$("#password-status").html(data);
},
});
}
//SIGNUP
function checkInput() {
jQuery.ajax({
url: "scripts/validation.php",
data:'checkinput=success',
type: "POST",
success:function(data){
$("#register-button").html(data);
},
});
}
//CHECKING LOGIN DATA IS VALID
function register() {
jQuery.ajax({
url: "scripts/validation.php",
data:'forename='+$("#firstName").val()+'&surname='+$("#lastName").val(),
type: "POST",
});
}
</script>
</head>
<body>
<div id="fullpage">
<div class="section " id="section0">
<video autoplay loop muted id="myVideo">
<source src="video/homeVideo.mp4" type="video/mp4">
</video>
<div class="layer">
<ul id="menu">
<li data-menuanchor="Login">Login</li>
<li data-menuanchor="Register">Register</li>
</ul>
</div>
<div class="layer">
<h1>Title</h1>
</div>
</div>
<div class="section" id="section1">
<div class="loginCard">
<form action ="scripts/login.php" method="post">
<input type="text" id="usernameLogin" name="username" placeholder="Username">
<input type="password" id="passwordLogin "name="password" placeholder="Password" onblur="loginCheck()">
<span id="login-status"></span>
</form>
</div>
<br>
<div class="registerCard">
<form action="scripts/signup.php" method="post" class="input-field" oninput="checkInput()">
<input type="text" name="firstName" placeholder="First Name" id="first_name" class="validate" >
<input type="text" name="lastName" placeholder="Surname">
<input type="text" nenter code hereame="username" id="username" placeholder="Username" onkeyup="UserAvailability()">
<span id="user-availability-status"></span>
<input type="email" name="email" id="email" placeholder="Email" onkeyup="EmailAvailability()">
<span id="email-availability-status"></span>
<input type="password" name="password" id="password1" placeholder="Password">
<input type="password" name="passwordVerify" id="password2" placeholder="Re-enter Password" onkeyup="passwordCheck()">
<span id="password-status"></span><br>
<span id="register-button"></span>
</div>
</div>
</div>
</body>
The way you are doing it, when these POST params are empty, the variable was never initialized.
A variable that will be used further down and not just inside this if-statement, should have its initial default value initialized outside all the if-statements.
Change
if(!empty($_POST["username"])) {
$usernameAuth = false;
to
$usernameAuth = false;
if(!empty($_POST["username"])) {
AND
if(!empty($_POST["email"])) {
$emailAuth = false;
to
$emailAuth = false;
if(!empty($_POST["email"])) {
AND
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
$passAuth = false;
to
$passAuth = false;
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
Or even better yet, initialize the initial default value of all these flags at the top of the file:
$usernameAuth = false;
$emailAuth = false;
$passAuth = false;
...
if(!empty($_POST["username"])) {
...
if(!empty($_POST["email"])) {
...
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
That will make the logic much cleaner to follow, and leave less room for a mistake.
And then check for more of these oversights.

jQuery AJAX shown form validation errors

I got problem with shown validation error on below script, for example what I tested, I enter a correct email and wrong password, the request will returned both Wrong email address and Wrong password under each input textbox, it is not only Wrong Password is expected to shown, I tried hardcode required data in request.php and run this script directly, for either giving wrong data in in $_POST, the console response {"error":{"lemail":"Wrong email address","lpassword":"Wrong password"}}, can someone please have a look in my code what's goes wrong?
form with AJAX call:
<body>
<form role="form" method="post" id="login_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="lemail" name="lemail" placeholder="Your email"><span class="error" id="lemail_error"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="lpassword" name="lpassword" placeholder="Password"><span class="error" id="lpassword_error"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btn_login" data-loading-text="Loading...">Sign In</button>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btn_login').click(function(){
var parameters = $('#login_form').serialize();
$.ajax({
url: 'inc/callback/request.php',
type: 'POST',
data: {'parameters' : parameters},
dataType: 'json',
success: function(response){
if(response.success == 'logged'){
$('#login_form')[0].reset();
alert(response.success);
}else if(response.inactivate == 'inactive'){
alert('Your account is inactive!');
}else{
$('[id$="_error"]').html(''); //clear valid error msg
// display invalid error msg
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
});
});
});
</body>
request.php
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));
$func = new Functions();
$message = array();
//validate user's email and password from database
$check = $mysqli->query("SELECT * FROM `users` WHERE user_email='".$email."' AND user_password='".sha1(sha1($password))."'") or die($mysqli->error);
$rows = $check->fetch_array(MYSQLI_BOTH);
$num = $check->num_rows;
$uId = $rows['user_id'];
$uEmail = $rows['user_email'];
$uPwd = $rows['user_password'];
$uType = $rows['account_type'];
$uStatus = $rows['account_status'];
// validate user's account
if(empty($email) || $email !== $uEmail){
$message['error']['lemail'] = 'Wrong email address';
}
if(empty($password) || sha1(sha1($password)) !== $uPwd){
$message['error']['lpassword'] = 'Wrong password';
}
if(!isset($message['error'])){
if($uStatus == 0){
$message['inactivate'] = 'inactive';
}else{
$message['success'] = 'logged';
}
}
echo json_encode($message);
Edited:
Solved! nothing went wrong, just out of logic on variables comparison!! ;P
in you php code first you have to deserliazed ur code.. put these lines at top..
$searcharray = array();
parse_str($_POST[parameters], $searcharray);
$email = $mysqli->real_escape_string(strtolower(trim($searcharray['lemail'])));
$password = $mysqli->real_escape_string(trim($searcharray['lpassword']));
You are posting string not array, you need to use parse_str function first.
Remove this enctype="multipart/form-data" from form
<form role="form" method="post" id="login_form">
Replace your data: line with this
data: {'parameters' : parameters},
After add this to your PHP
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));

How to add AJAX Submit to PHP validation and return message?

I've been working my way up on validating a form and got the JS and PHP validation to work but I am still having a hard time adding ajax(with or without JQUERY) to submit to the php file and return a success message.
My form with CSS and JS validation:
<html>
<head>
<style type="text/css">
#nameerror {
color:red;
}
#emailerror{
color:red;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
var email = document.forms['form']['email'].value;
var atpos = email.indexOf('#');
var dotpos = email.lastIndexOf('.');
var name = document.forms['form']['name'].value;
if (name == null || name == ""){
document.getElementById('nameerror').innerHTML="Please enter your name";
return false;
} else if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
document.getElementById('emailerror').innerHTML="Please enter a valid email";
return false;
} else {
}
}
</script>
</head>
<body>
<div>Sign Up</div>
<form name="form" action="form_validation.php" id="form" onsubmit="return Validate();" method = 'post'>
<label>Name:</label><br/>
<input id='name' type="text" name='name' /><br/>
<span id="nameerror"></span><br/>
<label>Email:</label><br/>
<input type='text' name='email' id = 'email'/> <br/>
<span id= "emailerror"></span><br/>
<label>Comments:</label><br/>
<textarea name='comments' id ='comments'></textarea><br/>
<span id="comerror"></span>
<input type="submit" name="submit" value="Submit"/>
<span id="success" style="display:none">Your message has been sent successfully.</span>
</form>
</body>
</html>
And this is form_validation.php:
<?php
if(isset($_POST['submit'])){
if($_POST['name']){
$name = $_POST['name'];
}
if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
echo "Name can only contain letters.";
return false;
} else {
echo "Name accepted";
}
if($_POST['email']){
$email = $_POST['email'];
}
$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if(!preg_match($pattern, $email)){
echo "Please enter a valid email address.";
return false;
} else {
echo "Email Valid";
}
if($_POST['comments']){
$comments = $_POST['comments'];
}
if (strlen($comments) > 100){
echo "please enter less than 100 characters.";
return false;
}
}
?>
thanks for the help!
$('form').on('submit',function() {
$.ajax({
url: 'form_validation.php',
data: $(this).serialize(),
type: 'POST'
}).done(function(data){
// you can append a success message to your document here
});
});

Categories