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.
Related
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.
I'm writting a code using CodeIgniter
ajax
var formData = {};
var url = $(form_id).attr("action");
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
make_alert();
} else {
$('#error-msg').html(result.message);
}
},
error: function(result) {
// error code here
}
});
Which will sent a data formData to add function in controller
add function
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
and this part here receive the formData values
$post_data = $this->input->post('formdata');
$data = array (
'username' => $post_data['username'],
'email' => $post_data ['email'],
'password' => $post_data ['password']
);
and this part run the validation
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
}
which return json
echo json_encode($result);
before using ajax, the code run smoothly without problem, but when using ajax, the validator return a message saying fields should be required, meaning, it doesn't receive form data submitted.
this part,
$data = array (
'username' => $post_data['username'],
'email' => $post_data ['email'],
'password' => $post_data ['password']
);
when using var_dump() on $data show it received form data submitted using ajax.
My question is, how to validate this $data using form_validation?
You cant validate using form_validation library
You should validate manually usin if statement and you will set error message as you want
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 have a problem with Jquery form validation.
I have this script:
$(document).ready(function () {
var validateUsername = $('.info');
$('#username').blur(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass();
validateUsername.addClass('info');
validateUsername.html('<img src="images/load.gif" height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
async: false,
cache: false,
url: 'process.php',
data: 'action=validateusername&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.removeClass();
validateUsername.addClass(j.class);
validateUsername.html(j.msg);
}
});
}, 500);
this.lastValue = this.value;
}
})
});
and in php something like this :
public static function validateUserName($username) {
$username = trim($username); // remove white spacing
$response = array(); // define response array
if(!$username) { // check if not empty
$response = array(
"ok" => false,
"class" => "error",
"msg" => "Please specify your username");
} elseif (strlen($username)<5) { // check the lenght
$response = array(
"ok" => false,
"class" => "error",
"msg" => "UserName must be at least 5 characters long");
} elseif (!preg_match('/^[a-zA-Z0-9.\-_]+$/',$username)) { // check the pattern
$response = array(
"ok" => false,
"class" => "error",
"msg" => "Your username can contain only Aplhanumerics, dash, underscore and period");
} elseif (!self::userNameAvailable($username)) { // check availability
$response = array(
"ok" => false,
"class" => "error",
"msg" => "UserName already taken !");
} else { // everything good
$response = array(
"ok" => true,
"class" => "success",
"msg" => "This username is free");
}
return $response;
}
As you can see php returns 3 fields of data....
problem is the user can still send the form even when php returns "false" and i have no idea how to fix it.
I could just let the form to be sent a do one more validating purely with php,
but what is the point of using ajax then.
I´d be very thankful if somebody could help me.
Why do you validate every 500ms and not on form submit or input change?
General pattern for form validation using jQuery is to validate on form's submit() event, like:
$('form').submit(function () {
...
(validation code here)
...
});
If validation doesn't succeed, you can just return false from submit() to avoid submitting the form.
Also note that you need to do server-side validation of posted data, too, as jQuery validation can be fooled easily.
I think a simple solution is to set a global variable:
var validform = false;
And check it in form submit event :
$("#myform").submit(function(){
return validform;
});
Now you can set it as TRUE or FALSE on your AJAX callback.
$.ajax({
// Whatever',
success: function (j) {
validform = true;
}
});
you can do a little more customization too.
I just want to tell the user either with AngularJS or AJAX or JQuery, or whatever is easiest, that the username and email are already registered.
I already have AngularJS implemented for other checks, just not those that need php.
Here is my php function:
public function user_exists() {
$username = $this->db->escape($this->input->post('username'));
$data = array(
'username' => $username,
'email' => $this->db->escape($this->input->post('email')),
'password' => crypt($this->db->escape($this->input->
post('password'))),
'user_id' => md5('I really like pie, '. $username)
);
$does_user_exist = "SELECT COUNT(`user_id`) FROM `users` WHERE
`username` = " . $data['username'] . " || `email` = " .
$data['email'] . "";
$query = $this->db->query($does_user_exist);
if($query->num_rows() > 0) {
return true;
}
}
Please and thank you.
Why you use $data array in method? To check exists user or not you need use MVC architecture and something like this code.
For model:
class User_Model extends CI_Model
{
public function is_exists($username, $email)
{
$this->db->select('user_id');
$this->db->where(array(
'username' => $username,
'email' => $email
));
$this->db->limit(1);
return $this->db->get('users')->row('user_id');
}
}
This code for controller:
class User extends CI_Controller
{
public function is_exists()
{
$email = $this->input->post('email');
$username = $this->input->post('username');
$this->load->model('user_model');
if(!$this->user_model->is_exists($username, $email))
{
$result = array('status' => 200, 'message' => 'Username and email are free');
}
else
{
$result = array('status' => 400, 'reason' => 'User already exists');
}
echo json_encode($result);
}
}
Ajax query:
$.ajax({
url: 'user/is_exists',
type: 'POST',
dataType: 'JSON',
data: {username: username, email: email},
success: function(data, status, jqXHR){
if(data.status == 200){
alert(data.message);
}
else{
alert(data.reason);
}
}
});
username and email js variables you need get from your regisration form.
Also you can use Ion Auth or Tank Auth extensions
When the user clicks the submit button on the registration form submit it using $.post() in jQuery. The action attribute of the form should map to the appropriate controller/method. The method you call can return a JSON encoded message to display in the browser.
It could look something like this:
$(function() {
$('#registration', 'input[type="submit"]').on('click', function(event) {
event.preventDefault();
var action = $(this).closest('form').attr('action');
var form = $(this).closest('form').serialize();
$.post(action, form, function(data) {
alert(data.message);
});
});
});
In the above example the ID of the form is #registration. The JS var 'data' is the JSON object returned by your PHP method and 'message' is a property of that object containing a message to display to the user.