ajax request after jquery validation - javascript

I try to make an ajax request after a successful form validation. If I delete the , after url: 'loginprivate.php' the php code works but the validation dont. If I add the , the validation works but the php code not. The redirection after successful ajax request dont work anyway. How can I make that working, maybe with $(form).ajaxSubmit(); when yes where should I add this line?
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
username: {
required: true,
minlength: 2,
maxlength: 30
},
password: {
required: true,
minlength: 3,
maxlength: 30
}
},
submitHandler: function (form) { // for demo
$.ajax({
type: 'post',
url: 'loginprivate.php', //url where you want to post the stuff.
data:{
username: 'root',
password: ''
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
window.location.href = "http://localhost/localcorps/main.php";
}
});
return false; // for demo
}
});
});
my php code:
if(isset($_POST["submit"]))
{
$hostname='localhost';
$username='root';
$password='';
unset($_POST['password']);
$salt = '';
for ($i = 0; $i < 22; $i++) {
$salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
}
$_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt);
$new = 0;
try {
$dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (username, password)
VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully";
}
else{
echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0)
{
$t = time() + 60 * 60 * 24 * 1000;
setcookie("username", $_POST['username'], $t);
setcookie("userid", $new , $t);
}
else
{
}
}

Im your ajax add this
data:{
username: 'root',
password: '',
submit: true,// add this line as you are checking in php file.
},

Related

How to check existing data with jquery validation library with codeigniter 4 when csrf is set to auto?

I have a form that I'm trying to validate with jquery validation plugin and codeigniter 4, I have enabled csrf that set to auto generate for every request. I'm able get validation status on first request but when I try another request I get error 403, and when I set second param to json_encode() I get error 500. I want to be able to update csrf after each request on ajax call.
//My router
$routes->post('check-category', 'Admin\Category::check_category');
//my controller
//check if category name exist
public function check_category()
{
$name = $this->request->getPost('name');
$query = $this->db->table('categories')
->where(['cat_name' => $name])
->get()
->getResult();
$status = true;
if(count($query) > 1){
$status = false;
}else{
$status = true;
}
$data['csrf'] = csrf_hash();
echo json_encode($status, $data);
}
// javascript
$('#create_category').validate({
onkeyup: false,
rules: {
name: {
remote: {
url: 'check-category',
type: "post",
data:{
csrf_hash_name: function(){
return $('input[name="csrf_hash_name"]').val();
}
},
complete: function(data){
$('input[name="csrf_hash_name"]').val(data.csrf);
}
}
}
},
messages: {
name: {remote: "This category exists."}
},
submitHandler: function(form) { return false; }
});
Thanks in advance.
the structure of the php function json_encode() looks like this:
json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false
and returns:
a string containing the JSON representation of the supplied value.
in your controller function check_category() you are sending $status, while $data is setting an invalid flag:
echo json_encode($status, $data); // wrong
change $status = true; into $data['status'] = true;
and just echo both, status and the csrf hash
echo json_encode($data); // correct
After so much struggle I finally found the solution of my problem. Now I'm able to update csrf token with the dataFilter object and get rid off error 403 during ajax call.
Here is what I have done to my controller even I broked Mvc principle by getting data from db direct to the controller.
I know it could not the best way for what I have done, Please correct me if any suggestion I'll appreciate. Thanks!
//my controller method
public function check_category()
{
$name = $this->request->getPost('name');
$query = $this->db->table('categories')->where(['cat_name' => $name])->countAllResults();
$valid = true;
if($query > 0){
$valid = false;
}else{
$valid = true;
}
$csrf = csrf_hash();
return $this->response->setJSON(['valid'=>$valid, 'csrf'=>$csrf]);
}
// my javascript
$('#create_category').validate({
onkeyup: false,
rules: {
name: {
required: true,
remote: {
url: 'check-category',
type: 'post',
dataType:'json',
dataFilter: function(data){
let obj = eval('('+data+')');
$('input[name="csrf_hash_name"]').val(obj.csrf);
return obj.valid;
},
data:{ csrf_hash_name: function(){ return $('input[name="csrf_hash_name"]').val(); } }
}
}
},
messages: {
name: {
required: "Enter a Category.",
remote: "{0} This category exists."
}
},
submitHandler: function(form) {
return false;
}
});

Call only one function at a time

I am creating a login and register example function using php OOP method with ajax.
When i click on login button it automatically fires the register function as well and when click on register fires login function. I know the issue is when i create an object and calls both the functions below class. I want to know is there any way that i can call only one function at one time. Here is the code:
Ajax
function login() {
jQuery('#loginform').on('submit', (function(e) {
e.preventDefault();
jQuery.ajax({
url: 'scripts/controller.php/login',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
jQuery('#btn-login').html('<i class="fa fa-spinner fa-spin fa-fw"></i>');
},
success: function(data) {
if(data == 'Logged in') {
jQuery('.result').show();
jQuery('.result').html(data);
jQuery('#btn-login').html('Login');
}
else {
jQuery('.result').html(data);
jQuery('.result').show();
jQuery('#btn-login').html('Login');
}
}
});
}));
}
function register() {
jQuery('#signupform').on('submit', (function(e) {
e.preventDefault();
jQuery.ajax({
url: 'scripts/controller.php/register',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
jQuery('#btn-signup').html('<i class="fa fa-spinner fa-spin fa-fw"></i>');
},
success: function(data) {
if(data === 'An email has been sent. Please verify your account with in 3 days.') {
jQuery('.result').show();
jQuery('.result').fadeOut(5000);
jQuery('.result').html(data);
jQuery('#btn-signup').html('Sign Up');
jQuery('.result').html(data);
jQuery('#signupform')[0].reset();
}
else {
jQuery('.result').show();
jQuery('.result').html(data);
jQuery('#btn-signup').html('Sign Up');
}
}
});
}));
}
PHP Code
<?php
require('model.php');
class curd {
/************************************************/
/*** LOGIN **/
/************************************************/
public function login() {
$restricted = array('--', '#', "'--", '/*', '*/', '/**/', '/*', '1/0', '*/ 1', "'", ';', '1=1','true','false', 'BEGIN', '+', '||', '|', "' or 1=1/*", "') or '1'='1--", "') or ('1'='1--", '*', 'drop' );
$userEmail = strip_tags(stripcslashes(htmlspecialchars($_POST['email'])));
$password = strip_tags(stripcslashes(htmlspecialchars($_POST['password'])));
if(in_array($userEmail, $restricted) or in_array($password, $restricted)) {
echo 'Avoid SQL injection attacks.';
}
else if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}
else if(strlen(trim($userEmail)) < 5) {
echo 'Minimum characters in email are 5.';
}
else if(strlen(trim($password)) < 5) {
echo 'Minimum characters in password are 5.';
}
else {
$model = new curd_model();
echo $model -> login($userEmail, md5(sha1($password)));
}
}
/************************************************/
/*** REGISTER **/
/************************************************/
public function register() {
$restricted = array('--', '#', "'--", '/*', '*/', '/**/', '/*', '1/0', '*/ 1', "'", ';', '1=1','true','false', 'BEGIN', '+', '||', '|', "' or 1=1/*", "') or '1'='1--", "') or ('1'='1--", '*', 'drop' );
$username = strip_tags(stripcslashes(htmlspecialchars($_POST['username'])));
$userEmail = strip_tags(stripcslashes(htmlspecialchars($_POST['email'])));
$password = strip_tags(stripcslashes(htmlspecialchars($_POST['password'])));
$question = strip_tags(stripcslashes(htmlspecialchars($_POST['question'])));
$answer = strip_tags(stripcslashes(htmlspecialchars($_POST['answer'])));
if(in_array($userEmail, $restricted) or in_array($password, $restricted) or in_array($userEmail, $restricted) or in_array($question, $restricted) or in_array($answer, $restricted)) {
echo 'Avoid SQL injection attacks.';
}
else if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}
else if(strlen(trim($userEmail)) < 5) {
echo 'Minimum characters in email are 5.';
}
else if(strlen(trim($password)) < 5) {
echo 'Minimum characters in password are 5.';
}
else {
$model = new curd_model();
echo $model -> register($username, $userEmail, md5(sha1($password)), $question, $answer);
}
}
}
$object = new curd();
$object -> login();
$object -> register();
?>
Anytime you'll load the file the following lines would run:
$object = new curd();
$object -> login();
$object -> register();
And therefore, both of the login and register functions would run.
You have 2 options:
Split those functions into 2 different files.
In your Ajax, add a parameter which would tell this file which function to run.
In MVC you might have a Routing mechanism (for instance: /user/login -> Controller User -> Method login)
In case you don't, you can simply use a query string, like: /scripts/controller.php?do=login and in your php file have a condition:
$object = new curd();
$do = $_GET['do'];
if($do == 'login'){
$object -> login();
} else {
$object -> register();
}
and in your ajax, update the request url:
jQuery.ajax({
url: 'scripts/controller.php?do=register',
(for login request as well .. ?do=login)

Retrieve parts of jquery response to populate inputs and selects

I send a jQuery request (incorporating a business_id) to a php file to retrieve all values in the database to populate the fields and selects that are in my form and correspond to this id. However, how am I able to retrieve the response from the database in pieces? So that I can provide the fields and selects that are in the form with the values from the database. My javascript function looks as follows:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response);
}
});
}
});
},
My businessdata.php looks as follows:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID ='$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo $row['uitgevoerd_door_naam'];
echo $row['hoev_gev_stof_score'];
}
}
mysqli_close($mysqli);
?>
What I want to achieve is:
$("#uitgevoerd_door_naam").val() == $row['uitgevoerd_door_naam'];
$("#hoev_gev_stof_score").val() == $row['hoev_gev_stof_score'];
etc.....
Fix:
Use json encode:
function:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
dataType: "json",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response.a);
$("#riskpot_scorefield3").val(response.b);
}
});
}
});
},
php file:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID = '$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo json_encode(array("a" => $row['uitgevoerd_door_naam'], "b" => $row['hoev_gev_stof_score']));
}
}
mysqli_close($mysqli);
?>

Ajax request taking too long time to respond

Javascript
<script>
loginValidator = $('#login').validate({
errorClass: 'error1',
focusInvalid: false,
errorElement: "div",
rules: {
username: {
required: true,
email: true
},
password: "required"
},
messages: {
username: {
email: "Please Enter a Valid E-mail Id"
},
password: {
required: "Please Enter Your Password"
}
},
submitHandler: function (form) {
var email = $('#username').val();
var password = $('#password').val();
var url = "<pre> ?php echo site_url() ?></pre> /register/do_login";
$.ajax({
type: 'post',
url: url,
data: {'username': email, 'password': password},
dataType: 'html',
success: function (data) {
if (data == 0) {
$('.invalidlogin').html('Invalid Username or Password').css('color', 'red');
}
if (data == 1)
{
window.location.href = "<?php echo site_url(); ?>/home/landing_home";
return false;
}
if (data == 2)
{
window.location.href = "<?php echo site_url(); ?>/home/first_login_disclaimer";
}
}
});
}
});
</script>
Register.php-Controller
<?php
function do_login() {
echo $result = $this->obj_users->check_login();
exit;
}
?>
Registration.php-Model
<?php
function check_login() {
$username = $this->input->post('username');
$password = $this->input->post('password');
$last_logged = date('Y-m-d H:i:s');
$salt = sha1($password);
$password = md5($salt . $password);
$this->db->where(array('email' => $username, 'password' => $password, 'status' => '1'));
$query = $this->db->get('registration');
$result = $query->result();
if (count($result) > 0) {
$first_login_status = $result[0]->first_login;
if ($first_login_status == '1') {
$datas = array('last_logged' => $last_logged);
$this->db->where(array('email' => $username));
$this->db->update('registration', $datas);
$this->session->set_userdata('user_id', $result[0]->id);
$this->session->set_userdata('user_type', $result[0]->user_type);
$this->session->set_userdata('ADMIN_NAME', $result[0]->name);
return "1";
} else {
$this->db->where(array('email' => $username, 'password' => $password, 'first_login' => '0', 'status' => '1'));
$query = $this->db->get('registration');
$result = $query->result();
$this->session->set_userdata('first_login_user_id', $result[0]->id);
$this->session->set_userdata('first_login_user_type', $result[0]->user_type);
$this->session->set_userdata('FIRST_LOGIN_ADMIN_NAME', $result[0]->name);
if (count($result) > 0) {
return "2";
}
}
} else {
return "0";
}
}
?>
Here, the ajax request is taking more than 5 seconds to respond to the request and redirect to next page.. Please suggest me if there is any way to reduce Ajax response time. Thank you.

Ajax 200 Success/failed execution

I have an issue with ajax and I am kinda new at this. The issue that I am having is even if log in fails ajax is still running the success block of code. How do I direct the code to return a failed status.
I'm not asking for you to inspect my code just more as a reference. I just need to know how to tell my code to send anything other than a 200 for okay so that I can display the errors on the screen.
I type in false information and the ajax thinks that the login happened but it really didn't.
AJAX Section
jQuery(document).ready(function(){
document.body.style.paddingTop="3px";
$('a[href^="#fallr-"]').click(function(){
var id = $(this).attr('href').substring(7);
methods[id].apply(this,[this]);
return false;
});
var methods = {
login : function(){
var login = function(){
var username = $(this).children('form').children('input[type="text"]').val();
var password = $(this).children('form').children('input[type="password"]').val();
var remember = $(this).children('form').children('input[name="remember"]').val();
var token = $(this).children('form').children('input[name="token"]').val();
if(username.length < 1 || password.length < 1 || token.length < 1){
alert('Invalid!\nPlease fill all required forms');
console.log(token)
} else {
var data = {
username: username,
password: password,
remember: remember,
token: token,
}
$.ajax({
type: "POST",
url: "login.php",
data: data,
dataType: "text",
success: function(data){
$('#error').append('Success');
// $.fallr.hide();
// window.location.href = "http://www.bettergamerzunited.com/members/";
},
error: function(data) {
$('#error').append('falied');
}
});
}
}
$.fallr.show({
icon : 'secure',
width : '400px',
content : '<h4 class="titles">Login</h4>'
+ '<span id="error"></span>'
+ '<form>'
+ '<input placeholder="Username" name="username" type="text"/'+'>'
+ '<input placeholder="Password" name="password" type="password"/'+'>'
+ '<input type="checkbox" name="remember" type="remember"/'+'> Remember Me'
+ '<?php echo $hidden; ?>'
+ '</form>',
buttons : {
button1 : {text: 'Submit', onclick: login},
button4 : {text: 'Cancel'}
}
});
}
};
});
Login Section
require 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = New Validate ();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if ($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
$response = $login;
echo $response; // <-- Im going to have an if statement that determines if $login was true or false. But testing still.
} else {
foreach ($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
This is the class that handles the login.
public function login($username = null, $password = null, $remember = false) {
if(!$username && !$password && $this->exists()) {
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
if($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()) {
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
} else {
try{
throw new Exception('The Username or Password combination doesn\'t match. \n Please try again.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
} else {
try{
throw new Exception('The Username you provide does not match anything in our system. Please Try again or Register.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
}
return false;
}
You can add below code for ajax error section ..in this way you will get idea of what's exactly is error and can debug it.
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
}
Use the PHP header function.
header('HTTP/1.0 403 Forbidden'); // or whatever status code you want to return.
There can be nothing else outputted before using the header function.

Categories

Resources