When checking if a username is taken in the DB, the code always shows the message that the username is taken. If I change the condition in ajax the message changes, but it shows always same even if user is in the DB
$(document).ready(function() {
$("#email").keyup(provjeraEmaila);
$("#korime").blur(function() {
if ($("#korime").val().length >= 5) {
$.ajax({
type: "POST",
url: "korisnici.php",
data: {
fieldName: "korisnicko_ime",
filedVal: $("#korime").val()
},
success: [function(data) {
if (data == 0) {
$("#username-span").html("username is taken!");
$("#username-span").attr('class', 'username-span');
} else {
$("#username-span").html("username is free!");
$("#username-span").attr('class', 'username-span');
}
}]
});
$("#username-span").html("");
}
});
});
This is the PHP code:
<?php
include_once 'baza.class.php';
if (isset($_POST['registracija']))
{
$veza = new Baza();
$veza->spojiDB();
$korime = $_POST['korime'];
$upit = "SELECT korisnicko_ime FROM korisnik WHERE
korisnicko_ime='$korime'";
$rezultat = $veza->selectDB($upit);
if (mysqli_num_rows($rezultat) > 0)
{
echo 0;
}
else
{
echo 1;
}
}
?>
Related
I'm trying to change the style of '$.notify' within my AJAX code from my PHP form processing code. I need it to return 'success' or 'error'.
Here's an example of my AJAX code:
$(function() {
$("#name-submit").submit(function(event) {
event.preventDefault();
if ($("#name").val() != "") {
$.ajax({
method: "POST",
url: "<?=updateNameFile?>",
data: {
name: $("#name").val()
}
}).done(function(msg) {
$.notify(msg, "success");
});
} else {
$.notify("<?php echo $language_form_message_invalid_data; ?>", "error");
}
});
});
Here's an example of my PHP code:
public function updateName($name, $id){
$pdo = $this->pdo;
if(isset($name) && isset($i)){
$stmt = $pdo->prepare('UPDATE users SET name = ? WHERE id = ?');
if($stmt->execute([$name, $id])){
$_SESSION['user']['name'] = $name;
session_regenerate_id();
return true;
} else {
$this->msg = 'An error occurred when changing your name';
return false;
}
} else {
$this->msg = 'Please provide valid information';
return false;
}
}
Again, I need it to return 'error' or 'success' into my AJAX code to style the notifications correctly.
I am trying to submit a form that validates, and than logs in the user in PHP. I return false when there is an error, but it does not stop the form from submitting. How can I prevent the form from submitting only when there is an error? I put a return false at the bottom but that stopped the whole form from submitting, even if the login was good.
login.js
$('#login_form').submit(function(e) {
if (validate({required: "email, password"}) == true) {
return attemptLogin();
} else {
return false;
}
});
function attemptLogin() {
var email = $("#email").val();
var password = $("#password").val();
var json = "JSON";
$.ajax({
url: "/login",
type: "POST",
data: {
email: email,
password: password,
json: json
},
success: function (data) {
data = JSON.parse(data);
if (data['message'] != 'undefined') {
if (data['message'] != 'success') {
$('#errors').html(data['message']);
return false;
}
}
}
});
}
and my PHP
if ($validation === true) {
$user->findByEmail($_POST['email'], array('first_name', 'password', 'id'));
if (!$user->login($_POST['password'], $user->password, $user->id)) {
if (isset($_POST['json'])) {
echo json_encode(array('message' => 'Invalid email or password.'));
die;
} else {
$redirect->to('/login', '<div class="message message-error">Invalid email or password.</div>');
}
} else {
echo json_encode(array('message' => 'success'));
//die;
$redirect->to('/home', '<div class="message message-success">Hi ' . $user->first_name . ', you have been logged in!</div>');
}
You can use e.preventDefault() - it will prevent any default browser events;
$('#login_form').submit(function(e) {
e.preventDefault();
if (validate({required: "email, password"}) == true) attemptLogin();
});
The return false only in if statement. I would like to store a flag that you can return from success function(data). Try this,
success: function (data) {
data = JSON.parse(data);
var flag = true;
if (data['message'] != 'undefined') {
if (data['message'] != 'success') {
$('#errors').html(data['message']);
flag = false;
return flag;
}
}
return flag;
}
I am trying to run a validation check and need to call the database and get result before I proceed, I am using ajax promise handler to wait for the response but for some reason it execution flow does not stop.
$("#attr").blur(function() {
var attrValue = $("#attr").val();
if (attr.length > 256) {
$("#Validation").text(" has a max of 256 characters");
$("#Validation").show();
$("#attr").focus();
} else {
if (attrValue.length > 0) {
$.when(check_attribute_name(attrValue)).done(function (data) {
if (data.result == false) {
$("#Validation").text("Another exists with this name. Try again!");
$("#Validation").show();
$("#attr").focus();
$("#unique").val("fasle");
} else {
$("#attrValidation").hide();
}
});
}
}
});
function check_attribute_name(attrValue) {
return $.ajax({
type: "Post",
url: "#Url.Action("Validation", "validator")",
data: { name: attrValue },
});
}
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.
I did an update with all things you told me, this is my result.
COMPLETE UPDATE:
$(document).ready(function(){
$("#submit").submit(function(e){
e.preventDefault();
var username = $("#username").val();
var result;
var request;
if(username){
request = $.ajax({
url: 'check.php',
data: {data: JSON.stringify(username)},
type: 'POST',
dataType: "json",
success: function (data) {
result = data;
}
});
} else {
alertify.error( "ERROR" );
}
request.done(function() {
console.log(result);
if(request.result == 1) {
alert("yes")
} else {
alert("no")
}
});
});
});
check.php:
$usernameChecker = new UsernameChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
if(!empty($data)) {
if ($usernameChecker->check_regex($data)) {
if($usernameChecker->check_length($data)) {
if (!$usernameChecker->check($data)) {
echo json_encode(array("error" => "Username already taken" , "result" => 0));
} else {
echo json_encode(array("error" => "Username available" , "result" => 1));
}
} else {
echo json_encode(array("error" => "Username too long" , "result" => 0));
}
} else {
echo json_encode(array("error" => "Allowed symbols: a-z , A-Z , 1-9 and \"_\"" , "result" => 0));
}
} else {
echo json_encode(array("error" => "You forgot to type your username" , "result" => 0));
}
This is what I have now, just console says:
"result is not defined"
SO:
When I submit empty input, I get request is undefined.
When I submit filled input, I get alert "no". Moreover this part:
"Username available"
is marked red.
But data.result is "1" in console?
Assign data to another variable to use outside of the $.ajax function
var username = $("#username").val();
var result;
var request;
if(username){
request = $.ajax({
url: 'check.php',
data: {data: JSON.stringify(username)},
type: 'POST',
dataType: "json",
success: function (data) {
result = data;
}
});
} else {
alertify.error( "ERROR" );
}
Here is the edit for you
request.done(function() {
console.log(result.result);
if(result.result == 1) {
alert("yes")
} else {
alert("no")
}
});