Ajax 200 Success/failed execution - javascript

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.

Related

Ajax undefined value in PHP

When I call the function I always get an undefined value, I don't understand what can ruin it.
You are logged in as undefined, Error undefined
Ajax script:
function Submit() {
console.log('asd')
$.ajax({
url: "Server.php",
type: "POST",
dataType: "json",
data: {
name: "Test2",
email: "Test#gmail.com"
},
success: function(data, textStatus, jqXHR) {
console.log("You are logged in as: ", data.name);
$('#user').html("You are logged in as: " + data.name);
},
error: function(request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error + " DATA: " + data);
}
})
}
PHP Script:
<?php
header("Content-type: application/json; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
I tried every solution in vain, so I still get an indefinite value. I’m slowly starting to think there’s nothing wrong with the script.
You want to use data.name but you never return name. hence the undefined.
I've added data.name in the example below and it seems to work fine.
<?php
header("Content-type: text/html; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
Also the parameters used in the succes function are in a different order than you seem to use, in your case the request will have your data in it
the callback parameter not
success:function(request, data, error)
but
success: function(data, textStatus, jqXHR)
data.name of course undefined because it is string
and your Server.php return this
{"success":true,"message":"Success!"}
no data.name but data.success and data.message
so you have to write
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name']; // add this
}

preventDefault() doesn't work appropriately

Today I am testing an application and I have a problem with the preventDefault (), on my computer it works correctly and in most of the users they have not had any problem, of the 30 users who are testing it, 2 tell me the same error, they send them to the post file of the login form, it actually logs them in correctly since in a JSON type array I determine if the password_verify is correct or not to communicate it with ajax, but it directly redirects them to the insert_user.php file and does not take Note the preentDefault (), nor the commit AJAX alert and the redirect to where it should take them.
This is the file that carries the post request
if (isset($_POST['login-value'])) {
//die(json_encode($_POST));
$correo = $_POST['login-email'];
try {
include_once 'funciones.php';
$password = $_POST['login-pass'];
$stmt = $conn->prepare("SELECT * FROM usuarios WHERE correo_usuario = ?");
$stmt->bind_param("s", $correo);
$stmt->execute();
$stmt->bind_result($id_user, $nombre_user, $apellido_user, $correo_user, $password_user, $tipo, $status);
if ($stmt->affected_rows) {
$existe = $stmt->fetch();
if ($existe) {
if (password_verify($password, $password_user)) {
if ($status == 'activo') {
session_start();
$_SESSION['usuario'] = $correo_user;
$_SESSION['nombre'] = $nombre_user;
$_SESSION['id'] = $id_user;
$_SESSION['tipo'] = $tipo;
$respuesta = array(
'respuesta' => 'exito',
'usuario' => $nombre_user
);
} else {
$respuesta = array(
'respuesta' => 'error'
);
}
} else {
$respuesta = array(
'respuesta' => 'error'
);
}
} else {
$respuesta = array(
'respuesta' => 'error'
);
}
}
$stmt->close();
$conn->close();
} catch (Exception $th) {
echo "error: " . $th->getMessage();
}
die(json_encode($respuesta));
}
And this is the js file with the AJAX and the preventDefault ()
if (document.getElementById("login-user-form")) {
document.getElementById("login-user-form").addEventListener('submit', function (e) {
e.preventDefault();
var datos = $(this).serializeArray();
var correo = document.getElementById("login-email").value;
var password = document.getElementById("login-pass").value;
//Validaciones
if (correo == "") {
Swal.fire(
'Error!',
'Ingresa un correo válido',
'error'
)
} else {
if (password == "") {
Swal.fire(
'Error!',
'Ingresa una contraseña válida',
'error'
)
} else {
$.ajax({
type: $(this).attr('method'),
data: datos,
url: $(this).attr('action'),
dataType: 'json',
success: function (data) {
var resultado = data;
if (resultado.respuesta =="exito") {
Swal.fire({
title: 'Correcto',
text: "Inicio de sesión correcto!",
icon: 'success',
showConfirmButton: false
})
setTimeout(function () {
window.location.href = 'index-app';
},1000);
} else {
Swal.fire(
'Error!',
'Usuario o contraseña incorrecto, intentalo de nuevo!',
'error'
)
}
}
})
}
}
});
}
What puzzles me a bit is why in 94% of the users I have no problem and in these 2 there is.
The only constant is that those 2 users do not work in the Google Chrome browser, I do not know the version, since they are normal users who are not testing it by programmers of any kind.
you can try : remove "e.preventDefault();" in this script
I already solved it, in the end remove the event "preventdeafult ()", and redirect it with header from php, adding an error message by url and get

Ajax with validate.js returning undefined result from php

Hello All, I have written a one demo code to check weather the given input user is exist in the list or not using ajax and validate.js, when I'm running the code all functions are executing fine but insted of getting response message in succes function it is jumping to the error function and giving undefined response as sent form php.
Here is my code:
$.validator.addMethod("checkUserExists", function(value, element){
alert("input checking");
var inputElem = $('#hl_form :input[name="username"]'),
data = { "username" : inputElem.val(),"check": "userCheck"},
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: "services.php",
async: true,
dataType: 'json',
data: data,
success: function(result)
{
alert(result);
console.log(result);
if (result.status !== 'true')
{
return '<p>This User is already registered.</p>';
}else{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
//alert('ajax loading error... ... '+url + query);
return false;
}
});
}, 'User Alread exist in the DB');
My Validate.js Rules and and Message are
Validate Method Rule
username: {
required: true,
checkUserExists:true
}
Validate.js Method Message
username: {
required: "Please enter your Username",
checkUserExists: "User... already exist"
},
My Php Code (service.php)
<?php
header('Content-Type: application/json');
class form_services{
public $sql;
public $returnResult = array();
function checkUser($requestedUser) {
$registeredUser = array('xyz', 'abc', 'def', 'ghi', 'jkl');
if( in_array($requestedUser, $registeredUser) ){
$returnResult["status"] = 'false';
}else{
$returnResult["status"] = 'true';
}
return $returnResult;
}
} //Class Ends Here
$checkRequest = $_POST['check'];
$frmServices = new form_services();
$data = '';
switch ( $checkRequest) {
case 'userCheck': $requestedUser = $_REQUEST['username'];
$data = $frmServices->checkUser( $requestedUser);
echo json_encode($data);
break;
default: echo json_encode($data);
break;
}
?>
Please help me in resolving my issue, i'm getting undefined result in ajax call from php cod.

Is there a way to return more than just text with PHP/AJAX?

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.

jQuery ajax call not triggering success function on Safari 9.1

In a project I have a particular ajax call that works fine on PC Chrome/Firefox, but on Safari 9.1 it fails to trigger the success function.
The ajax call:
$('#new_file_form').submit(function(e) {
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
url: '/includes/ajax/file-manager.php',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
success: function(result) {
JSON.parse(result);
alert(result);
if (result == true) {
$('#new_file_form').reset;
$('#new_file_modal').modal('hide');
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-info-sign blue"></i>File successfully saved.',
callback: function() {
location.reload();
}
});
} else if (result == false) {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>File not saved.',
callback: function() {
location.reload();
}
});
} else {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>Whoa! That escalated quickly..',
callback: function() {
location.reload();
}
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
This doesn't throw any errors. The file is uploaded and the data inserted into the database, it's just the success function that sits there and seems to be laughing at me.
Based on the returned error in Safari it seems useful to post the file-manager.php code:
if(!empty($_POST['file_name']) && !empty($_POST['file_type']) && !empty($_POST['file_user'])) { // && !empty($_FILES['file'])
$ownerid = $mysqli->real_escape_string($_POST['file_user']);
$ownertype = 1;
$name = $mysqli->real_escape_string($_POST['file_name']);
$visible = $mysqli->real_escape_string($_POST['visible']);
$filetype = $mysqli->real_escape_string($_POST['file_type']);
$ownerid = filter_var($ownerid, FILTER_SANITIZE_NUMBER_INT);
$visible = filter_var($visible, FILTER_SANITIZE_NUMBER_INT);
$filetype = filter_var($filetype, FILTER_SANITIZE_NUMBER_INT);
$cdate = date('Y-m-d H:i:s');
$edate = $cdate;
$u_file_name = $_FILES['file']['name'];
$u_tmp_file = $_FILES['file']['tmp_name'];
$u_file_type = $_FILES['file']['type'];
$u_file_error = $_FILES['file']['error'];
$u_file_content = file_get_contents($_FILES['file']['tmp_name']);
$upload_result = '';
if($u_file_error == 'UPLOAD_ERROR_OK') {
if($u_file_name == '') {
$upload_result = false;
} else {
$sql = "SELECT path FROM filetypes WHERE id = '$filetype'";
$result = $mysqli->query($sql);
$record = $result->fetch_object();
$file_type_path = $record->path;
$extension = end(explode(".", $u_file_name));
if($ownertype == 1) {
$s_file_name = preg_replace("![^a-z0-9]+!i", "-", $name).'-'.date('Y-m-d_H-i').'.'.$extension;
$s_file_dest = LOCAL_BASE_PATH.'/uploads/'.$ownerid.'/'.$file_type_path;
$s_file_location = $s_file_dest.'/'.$s_file_name;
$s_file_path = '/uploads/'.$ownerid.'/'.$file_type_path.$s_file_name;
}
if(!file_exists($s_file_dest)) {
mkdir($s_file_dest, 0755, true);
}
move_uploaded_file($u_tmp_file, $s_file_location);
$sql = "INSERT INTO files (ownertype, owner, type, visible, extension, name, path, cdate, edate) VALUES ('$ownertype', '$ownerid', '$filetype', '$visible', '$extension', '$s_file_name', '$s_file_path', '$cdate', '$edate')";
$result = $mysqli->query($sql);
$upload_result = true;
}
}
echo json_encode($upload_result);
exit();
}
When I alert the ajax result before parsing it, I get a PHP error:
Strict Standards: Only variables should be passed by reference...

Categories

Resources