preventDefault() doesn't work appropriately - javascript

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

Related

Ajax response isn't showed on page

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.
PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...
What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

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.

How to get ajax responses from php?

I run the ajax via this php with js:
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
jQuery(".modal-body").html("Done!");
}
});
}
</script>
<?php }
Then I run
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}
In both cases I get "Done!" as a response. I need to set up responses based on:
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
The above php bits work if I run them as a standard php.
try:
on your php
if( wp_insert_category( $my_cat ) ) {
echo json_encode( 'Category added successfully');
} else {
echo json_encode( 'Error while creating new category');
}
} else {
echo json_encode( 'That category already exists');
}
on js instead
$(".modal-body").html("Done!");
use
$(".modal-body").html(data);

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.

submit prevented by preventDefalut()

I am using ajax to make validation of login. I am having a problem with javascript e.preventeDefault(), when use it prevents submit and always shows validation empty field. When remove it is right but echo json data and doesnt shows validation messages inside dialog box, instead it redirects to url and echo the right json message. I think e.preventDefault prevents submit, is there any other way to put validation message inside dialog box insted of e.preventDefault() ?
$('#login_form').on('submit', function(e) {
e.preventDefault();
var username = $('#login_form input[name=sign_in_username]').val();
var password = $('#login_form input[name=sign_in_pass]').val();
$.ajax({
url: "login.php",
type: "POST",
data: {username: username,
password: password
},
dataType: 'json',
success: function(response) {
if(response.status){
$(this).unbind('submit').submit()
console.log(response);
window.location = response.url;
}
else{
$('#invalid_content').html(response.msg);
}
}
});
});
login.php
if (((!isset($_POST["sign_in_pass"]) || !isset($_POST["sign_in_username"]) ) || trim($_POST["sign_in_pass"]) == "" || trim($_POST["sign_in_username"]) == "")) {
echo json_encode(array('msg' => "Username or password are empty.", 'url' => "", 'status' => false));
exit();
}
$rows = query("SELECT * FROM customers WHERE username = ?", $_POST["sign_in_username"]);
// nese form eshte bere submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (count($rows) == 1) {
$row = $rows[0];
if (crypt($_POST["sign_in_pass"], $row["hash"]) == $row["hash"]) {
$_SESSION["id"] = $row["id"];
echo json_encode(array('msg' => "Success.", 'url' => "index.php", 'status' => true));
}
} else {
echo json_encode(array('msg' => "Username or password invalid.", 'url' => "", 'status' => false));
}
} else {
echo json_encode(array('msg' => "Username or password invalid.", 'url' => "", 'status' => false));
}
Your problem is not the e.preventDefault(). Your fields just don't match up, which is why they're empty.
Your data parameter should be: data: {sign_in_username: username, sign_in_password: password}.
The request your PHP script receives has the wrong field names in it.
In the future, for debugging purposes, on your PHP script, try var_dump($_POST);. This will give you an idea of what the request you received had in it.

Categories

Resources