jQuery AJAX shown form validation errors - php

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

Related

Enter data into the database using PHP & Ajax

I want to enter data into my database using PHP and Ajax.
I have a kind of user guestbook.
When I run my code it always jumps automatically to the else {} area, my text does not enter the database.
Could you guys help me please?
This is my Ajax Code
$("#addComment").on("click", function(e){
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
url: 'add_comment.php?page=<?php echo $page; ?>',
type: 'POST',
data: {comment: comment},
success: function(data){
if (data == 1) {
loadData();
alert('Comment Submitted Successfully.');
$("#commentBox").trigger("reset");
}else {
alert("Comment Can't Submit.");
}
}
});
});
This is my PHP Code:
session_start();
include("assets/include/config.php");
require_once('assets/JBBCode/Parser.php');
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
$page = $_GET['page'];
echo $username;
$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());
$error = false;
$comment = htmlentities($_POST['comment']);
$parser->parse($comment);
$bbcode = $parser->getAsHtml();
if(strlen(trim($bbcode)) == 0){
$error = true;
}
if($error == false){
$stmt = $pdo->prepare("INSERT INTO threadComments (subThreadsID, username, userid, threadContent) VALUES (?,?,?,?)");
$stmt->execute([$page, $username, $userid, $bbcode]);
}
and this is my HTML Code:
<form id="commentBox" action="subcomments.php?page=<?php echo $page ?>" method="POST">
<div class="alert alert-light" role="alert">
<div class="input-group mb-3">
<textarea name="comment" id="comment" class="form-control" row="3" placeholder="Whats up.?" required></textarea>
</div>
<button type="submit" id="addComment" name="addComment" class="button-8">Comment</button>
</form>
With the help of $_GET['page'] I tell the database which guestbook the comment should be added to.

using ajax to login with php

I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect.
I am using Ajax and a modal form in my code
Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network
I have not been able to figure out the issue.
I have tried
window.location.href
window.location.replace.
Nothing is working
need help
Thanks
This is part of the js file
$("#loginform").submit(function(event) {
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost = $(this).serializeArray();
//send them to login.php using AJAX
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function(data) {
if (data == "success") {
window.location = "user_page.php";
} else {
$("#loginmessage").html(data);
}
},
error: function() {
$("#loginmessage").html(
"<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>"
);$
}
});
});
This is part of my login.php file
//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
//Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
//If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
if (empty($_POST['remember'])) {
echo "success";
} else {
// todo logic for remember me
}
}
This is the form modal
//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
<div class="form-body">
<div class="form-head"><h3>Login form</h3></div>
<div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
<div id="loginmessage"></div>
<div class="form-inputs">
<p><input type="email" name="email" placeholder="email" /></p>
<p><input type="password" name="password" placeholder="Password" /></p>
</div>
<div class="login-session">
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="remember" />
<label for="remember">Remember me</label>
</div>
<div class="">
Forgot my password
</div>
</div>
<div class="form-submit">
<input class="btn btn-primary" type="submit" value="log in"/>
<a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
</div>
</div>
</form>
I finally found the solution to the issue.
In the index.js file:
success: function(data) {
if (data == "success") {
window.location = "user_page.php";`
was changed to:
success: function(data) {
if ($.trim(data) == "success") {
window.location = "user_page.php";`
Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.

can't get input type text via js

i bought course in Udemy to make login system and just wanted to add more input in html to get username ..... but it didn't work
it took me like 15 hours and still can't understand why it don't work
<div class="uk-section uk-container">
<div class="uk-grid uk-child-width-1-3#s uk-child-width-1-1" uk-grid>
<form class="uk-form-stacked js-register">
<h2>Register</h2>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Username</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" required='required' placeholder="Username">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="email" required='required' placeholder="email#email.com">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Passphrase</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="password" required='required' placeholder="Your passphrase">
</div>
</div>
<div class="uk-margin uk-alert uk-alert-danger js-error" style='display: none;'></div>
<div class="uk-margin">
<button class="uk-button uk-button-default" type="submit">Register</button>
</div>
</form>
</div>
jquery code:
$(document).on("submit", "form.js-register", function(event) {
event.preventDefault();
var _form = $(this);
var _error = $(".js-error", _form);
var dataObj = {
username: $("input[type='text']", _form).val(),
email: $("input[type='email']", _form).val(),
password: $("input[type='password']", _form).val()
};
if(dataObj.email.length < 6) {
_error
.text("Please enter a valid email address")
.show();
return false;
} else if (dataObj.password.length < 11) {
_error
.text("Please enter a passphrase that is at least 11 characters long.")
.show();
return false;
}
// Assuming the code gets this far, we can start the ajax process
_error.hide();
$.ajax({
type: 'POST',
url: '/ajax/register.php',
data: dataObj,
dataType: 'json',
async: true,
})
.done(function ajaxDone(data) {
// Whatever data is
if(data.redirect !== undefined) {
window.location = data.redirect;
} else if(data.error !== undefined) {
_error
.text(data.error)
.show();
}
})
.fail(function ajaxFailed(e) {
// This failed
})
.always(function ajaxAlwaysDoThis(data) {
// Always do
console.log('Always');
})
return false;
})
php code :
define('__CONFIG__', true);
// Require the config
require_once "../inc/config.php";
if($_SERVER['REQUEST_METHOD'] == 'POST' or 1==1) {
// Always return JSON format
// header('Content-Type: application/json');
$return = [];
$email = Filter::String( $_POST['email'] );
// Make sure the user does not exist.
$findUser = $con->prepare("SELECT user_id FROM users WHERE email = LOWER(:email) LIMIT 1");
$findUser->bindParam(':email', $email, PDO::PARAM_STR);
$findUser->execute();
if($findUser->rowCount() == 1) {
// User exists
// We can also check to see if they are able to log in.
$return['error'] = "You already have an account";
$return['is_logged_in'] = false;
} else {
// User does not exist, add them now.
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$username = $_POST['text'] ;
$addUser = $con->prepare("INSERT INTO users(username,email, password) VALUES(:username,LOWER(:email), :password)");
$addUser->bindParam(':username', $username, PDO::PARAM_STR);
$addUser->bindParam(':email', $email, PDO::PARAM_STR);
$addUser->bindParam(':password', $password, PDO::PARAM_STR);
$addUser->execute();
$user_id = $con->lastInsertId();
$_SESSION['user_id'] = (int) $user_id;
$return['redirect'] = '/dashboard.php?message=welcome';
$return['is_logged_in'] = true;
}
echo json_encode($return, JSON_PRETTY_PRINT); exit;
} else {
// Die. Kill the script. Redirect the user. Do something regardless.
exit('Invalid URL');
}
what happen that email and password send to database (which i get from source code of the course)
and username which i added just don't do anything .. prevent page from redirect
i really think i made an idiot mistake but i think 15 hours for trying is enough too .. forgive me for that .. and for my bad English
Thanks
edit this in html
<div class="uk-form-controls">
<input class="uk-input" name="username" type="text" required='required' placeholder="Username">
</div>
and edit dataobj in ajax
var dataObj = {
username: $("input[name='username']", _form).val(),
email: $("input[type='email']", _form).val(),
password: $("input[type='password']", _form).val()
};
and remove all the id's from html because you have define the same id for every html tag(username, email, paddword), javascript will throw an error if more than one html tag have the same id

In codeigniter How to redirect after login using ajax

I have a login popup Modal. and i am logging through ajax
Modal
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
I am trying to redirect after successful login using ajax. If email and password is correct then redirect to any page. If not then it will show the Error.
Controller
function index() {
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
echo validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
echo "Yes";
}else {
echo "No";
}
}
}
This is my controller in which i am checking login user email and password correct/incorrect.
This is my script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(msg) {
if (msg == "Yes")
window.location.href = "<?php echo current_url(); ?>";
else if (msg == "No")
$('#error-msg').html('<div class="alert alert-danger text-center">Incorrect Email & Password. Please try again ...</div>');
else
$('#error-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
});
return false;
});
</script>
As you can see in the success part, when i entered the correct email/password. It is showing Yes. But i want to redirect another page, Why this is showing YES on correct email/password.and On incorrect email/password This is showing NO.
Where i am Doing Wrong???
You need to change few lines of codes in jQuery and Controller function. Here I am attaching updated version of your code. Please refer below:
View (Bootstrap Modal)
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
This is your view file. It will remain same. On clicking on button you have written a script which need to be modified. Will attact after attaching controller's function:
Controller
function index() {
if (!$this->input->is_ajax_request()) {
echo 'No direct script is allowed';
die;
}
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
$result['status'] = 'error';
$result['message'] = validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
$result['status'] = 'success';
$result['message'] = 'Yeah! You have successfully logged in.';
$result['redirect_url'] = base_url();
}else {
$result['status'] = 'error';
$result['message'] = 'Whoops! Incorrect Email & Password. Please try again';
}
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($result));
$string = $this->output->get_output();
echo $string;
exit();
}
Script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(resp) {
if (resp.status == "success")
window.location.href = resp.redirect_url;
else
$('#error-msg').html('<div class="alert alert-danger">' + resp.message + '</div>');
}
});
return false;
});
This is the correct answer. Let me know if you face any issue.
You can use a simple redirect() (comes in the url helper) in your code if you want to jump to another controller/method from the script. However, this will not alert the user that the login was successful: it's just a plain redirect.
The proper way to do it would be returning a json file, so instead of echoing a yes or no, use this:
$response['type'] = 'error';
$response['msg'] = 'Login Succesful';
$response['redirect'] = 'http://your-url.com/controller/method';
echo json_encode($response);
die;
Then, you handle the answer in your ajax call, and some good alerting (in my case, Sweet Alert) kinda like this:
success: function(data) {
if (data.redirect) {
swal({
title: '¡Success!',
text: data.msg,
timer: 2000,
type: data.type,
showConfirmButton: false
}, function() {
window.location.href = data.redirect;
});
} else {
swal('¡Error!', data.msg, data.type);
}
}
So what this code does is that if your json response has a redirect field, will trigger the redirection after a while. But if your json response does not have the field redirect, will just show an alert.
Check your return data type. May be you can use in datatype in Ajax code. Return data can't read if condition. I am facing same problem or use this
if($.trim(msg) == 'Yes') {
Change echo "Yes"; to die("Yes");. This will make sure nothing will be sent after "Yes" or "No" and then the JS code will work as expected.
Their is also a way to redirect from your controller after success.
In this case you just need to follow these two steps to redirect
This line in your controller where you get true condition and want to redirect
if($result){
echo base_url()."welcome/";
}
else{
echo 0;
}
on your html page where you applied your ajax, on true condition you try this to redirect page
success: function(result){
if(result!=0){
// On success redirect.
window.location.replace(result);
}
else
alert('wrong');
}

AJAX > PHP Log in not working

I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>
as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)
try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>

Categories