Ajax request shows JSON after success - php

I am trying to do a simple login through AJAX and it works fine except that after the success callback alerts the response, the browser shows the JSON response like this:
{"status":"success","username":1234}
I have used the same piece of code several times before with no problems, but I think I am missing some knowledge as to why this is happening? There are some modifications of course, but the AJAX part is the same in both PHP and Jquery and I can't figure out what I am doing wrong.
This is the Jquery:
$('#btnLogin').on('click', function(){
login();
});
function login(){
var un = $('#loginUn').val();
var pwd = $('#loginPwd').val();
$.ajax({
url: 'index.php?page=login',
type: 'POST',
dataType: 'json',
data: {'un': un, 'pwd': pwd},
success: function(data){
alert("You are logged in as "+data.username);
},
error: function (request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error+ " DATA: " + data);
}
});
}
The PHP controller:
include_once 'models/login.class.php';
$user = new Login( $dbh );
// If the form is submitted
if(isset($_POST['un'])){
// Check if fields are empty
$fields = array('un', 'pwd');
$error = false; //No errors yet
//Loop trough each field
foreach($fields AS $fieldname) {
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$error = true; //Yup there are errors
}
}
// If there are no errors
if(!$error) {
$un = $_POST['un'];
$pwd = $_POST['pwd'];
$user->checkUser($un, $pwd );
}
}
$view = include_once"views/login-html.php";
return $view;
And finally the model generating the response:
class Login {
private $dbh;
// Connect to database
public function __construct ( $pdo ) {
$this->dbh = $pdo;
}
public function checkUser ($un, $pwd ){
$sth = $this->dbh->prepare('SELECT password, username FROM employees WHERE username = ?');
$sth->execute(array($un));
//Getting the data from db
while($r=$sth->fetch()){
$password = $r['password'];
$username = $r['username'];
}
if($un == $username && $pwd == $password){
$array = array('status' => 'success', 'username' => $username);
// echo "<script>alert('You are logged in as ".$username."');</script>";
// echo "<script>window.location.href='index.php';</script>";
// echo json_encode(array('status' => 'success', 'username' => $username);
$forEcho = json_encode($array);
echo $forEcho;
}else{
echo json_encode(array('status' => 'failure'));
}
exit;
}// End checkUser function
}// End of class
This is the HTML:
<div class="container text-center">
<div class="col-sm-4 col-sm-offset-4">
<h1>Login</h1>
<form role="form" method="post">
<div class="form-group">
<div class="row">
<h3>Username</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-user"></span>
</div>
<input type="text" name="un" class="form-control" id="loginUn" placeholder="Please type in your username">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<h3 id="lblPassword">Password</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-key"></span>
</div>
<input type="password" name="pwd" class="form-control" id="loginPwd" placeholder="Please type in your password">
</div>
</div>
</div>
<button id="btnLogin" type="¨button" name="btnLogin" class="btn btn-success">Submit</button>
</form>
</div>
</div>
If somebody could tell me where I am going wrong I would really appreciate it! Have been looking for a solution/explanation with no result for several hours.
EDIT: Added the HTML. The alert in the success callback works just fine, but when closing it the JSON is all that is displayed on a blank screen. Never had this happen to me before.

You have an invalid value for the type attribute:
type="¨button"
… so the button reverts to the default and is a submit button.
You are seeing the results of submitting the form normally instead of using Ajax.
As a short term fix, remove the ¨. In the long term, you should adopt unobtrusive JavaScript as a best practise.

I bet btnLogin is a submit button, huh.. return false or prevent default to prevent the form from submitting..
$('#btnLogin').on('click', function(e){
e.preventDefault();
login();
});

Related

How to integrate remember me after successful login using jquery ajax?

view: login.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
remember_me = $("#remember_me").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin,"remember_me":remember_me},
url:"<?php echo base_url(); ?>redirect",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$(".login_success").html('<p>' + data.error + '</p>');
}
}
});
});
});
</script>
<div class="tab-pane" id="profile" role="tabpanel" data-mh="log-tab">
<div class="title h6">Login to your Account</div>
<form class="content">
<div class="login_success"></div>
<div class="row">
<input class="form-control" placeholder="" type="email" id="elogin">
<input class="form-control" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox">Remember Me
</div>
Login
</div>
</div>
</form>
</div>
controller:
public function login_redirect()
{
$email = $this->input->post('elogin');
$password = $this->input->post('plogin');
$remember = $this->input->post('remember_me');
if($email=='' || $password=='')
{
echo json_encode(array('error' => 'All fields are mandatory. Please fill all details.'));
}
else
{
$this->db->select('*');
$this->db->from('user');
$where = "email='".$email."' and password='".$password."' and status='1'";
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$this->session->set_userdata('user_id',$result);
if (!isset($_POST))
{
header ("Location:".base_url()."thankyou");
}
else
{
echo json_encode(array('redirect' => base_url().'thankyou'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
}
In this code, I am creating a login module which works fine. Now, I also want to integrate the remember me option when user check remember me checkbox server ask to want to save detail or not. When user logout it doesn't require to fill it's detailed again inside the login form. Once the user checks on remember me checkbox. So, How can I do this? Please help me.
Thank You
You can make this by using cookie.
try following code:
//php (controller):
//after success login
if($remember){
//set cookie
$this->input->set_cookie('email', $email, 86500);
$this->input->set_cookie('password', $password, 86500);
}else
{
//delete cookie
delete_cookie('email');
delete_cookie('password');
}
view: login.php
//set cookie value if checked remember me.
<div class="row">
<input class="form-control" value="<?php if (get_cookie('email')) { echo get_cookie('email'); } ?>" placeholder="" type="email" id="elogin">
<input class="form-control" value="<?php if (get_cookie('password')) { echo get_cookie('password'); } ?>" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox" <?php if (get_cookie('email')) { ?> checked="checked" <?php } ?>>Remember Me
</div>
You can create the cookie with your javascript when you get the response of your ajax call. You should use document.cookie() if you choose this way to do.
If you choose the server side, CodeIgniter have a Cookie Helper. For use it, you have to add it 'cookie' on your autoload. You can load it with this line too :
$this->load->helper('cookie');
when the helper is loaded, you have to create the cookie in your controller like this :
$this->input->set_cookie('cookie_name', $value, time_in_seconds);

jQuery PHP: Check if username already exist

I'm trying to check the existence of an username already registered on my application using jQuery+Ajax+POST.
HTML
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" id="username" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="col-sm-9 col-sm-offset-3" id="userCheck">
<div class="alert alert-info" id="userCheckLabel"></div>
</div>
jQuery
$('#username').focusout(function() {
var username = $('#username').val();
checkUserExist(username);
})
function checkUserExist($uname) {
$.post( "../core/lib/checkUserExist.php", function( data ) {
if(data.html == 'true') {
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});
PHP
<?php
require_once('../../core/class.user.php');
$user = new USER();
$uname = $_POST['username'];
$stmt = $user->runQuery("SELECT user_nameFROM users WHERE user_name=:uname ");
$stmt->execute(array(':uname'=>$uname));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['user_name']==$uname) {
print 'true';
} else {
print 'false';
}
?>
I Don't include class.user.php cause It's only handling the PDO Connection, If I remove the if(data.html == 'true') the connection work as expected and the message come out.
Behavior
The code work if I remove the if(data.html == 'true'). but with this it doesn't do anything, no errors in console. So I think the error is in the way I handle the PHP part.
Any suggestion?
Since you are returning string not HTML, so you have to do like below:-
$.post( "../core/lib/checkUserExist.php",{username: uname }, function( data ) {
console.log(data);// check this and let me know the output
if(data == 'true') { // or try if(data)
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});

Unable to pass login information through AJAX using Codeigniter MVC system

Good afternoon,
I'm looking for some advise on Codeigniter and getting an Ajax login form to work with my controller and upon being successfully logged in then to take me to a dashboard/homescreen for the particular user.
Here is my 'auth.php' Controller code:
class Auth extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('data_model');
$this->load->database();
}
//** Check Status & Redirect To Login **//
public function index() {
if($this->session->userdata('admin_login') == 1)
redirect(base_url() . 'admin/dashboard', 'refresh' );
else if($this->session->userdata('staff_login') == 1)
redirect(base_url() . 'staff/dashboard', 'refresh' );
else if($this->session->userdata('client_login') == 1)
redirect(base_url() . 'client/dashboard', 'refresh' );
$this->load->view('login');
}
//** Login Function **//
function ajax_login() {
$response = array();
//** Credentials of user login **//
$email = $_POST["email"];
$password = $_POST["password"];
$response['submitted_data'] = $_POST;
//** Validating the login **//
$login_status = $this->validate_login($email, $password);
$response['login_status'] = $login_status;
if ($login_status == 'success') {
$response['redirect_url'] = $this->session->userdata('last_page');
}
}
//** Validating Credentials **//
function validate_login($email = '' , $password = '') {
$credentials = array('email' => $email, 'password' => sha1($password));
//** Checking Admin Credentials **//
$query = $this->db->get_where('admin', $credentials);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('admin_login', '1');
$this->session->set_userdata('login_user_id', $row->admin_id);
$this->session->set_userdata('name', $row->name);
$this->session->set_userdata('login_type', 'admin');
return 'success';
}
& here is my login.php view.
<div class="login-container">
<div class="row">
<div class="col-sm-6">
<script type="text/javascript">
jQuery(document).ready(function($)
{
// Reveal Login form
setTimeout(function(){ $(".fade-in-effect").addClass('in'); }, 1);
// Validation and Ajax action
$("form#login").validate({
rules: {
email: {
required: true
},
password: {
required: true
}
},
messages: {
email: {
required: 'Please enter your email.'
},
password: {
required: 'Please enter your password.'
}
},
// Form Processing via AJAX
submitHandler: function(form)
{
$.ajax({
url: "auth/validate_login",
method: 'POST',
dataType: 'json',
data: {
do_login: true,
email: $(form).find('#email').val(),
password: $(form).find('#password').val(),
},
success: function(resp)
{
show_loading_bar({
delay: .5,
pct: 100,
finish: function(){
// Redirect after successful login page (when progress bar reaches 100%)
if(resp.accessGranted)
{
window.location.href = 'auth/index';
}
else
{
toastr.error("You have entered wrong password, please try again. User and password is <strong>demo/demo</strong> :)", "Invalid Login!", opts);
$passwd.select();
}
}
});
}
});
}
});
// Set Form focus
$("form#login .form-group:has(.form-control):first .form-control").focus();
});
</script>
<!-- Errors container -->
<div class="errors-container">
</div>
<!-- Add class "fade-in-effect" for login form effect -->
<form method="post" role="form" id="login" class="login-form fade-in-effect">
<div class="login-header">
<img src="<?php echo base_url();?>assets/images/logo#2x.png" alt="" width="80" />
<span>log in</span>
</a>
<p>Dear user, log in to access your user area!</p>
</div>
<div class="form-group">
<label class="control-label" for="username">Username</label>
<input type="text" class="form-control input-dark" name="email" id="email" placeholder="Email" data-mask="email" />
</div>
<div class="form-group">
<label class="control-label" for="passwd">Password</label>
<input type="password" class="form-control input-dark" name="password" id="password" placeholder="Password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-dark btn-block text-left">
Log In
</button>
</div>
<div class="login-footer">
Forgot your password?
</div>
</form>
From the code above, I have declared a model but this doesn't actually contain any information as I have a get DB within my controller. Hopefully someone could shed some light on this.
Thank you!
Zak Hargreaves.

Login with ajax not working

Here is my html
<div id="stylized" class="myform">
<form action="index.php" method="post" class="formPadd">
<div align="right">
<fieldset class="FloatLeft">
</fieldset>
<fieldset class="FloatRight" style="padding-right:14px;">
<div style="height:40px; line-height:30px; text-align:center;">
<label>Username:</label><br>
<input class="inputbox" type="text" style="text-align:center; padding-right:14px;" name="uname" value maxlength="50">
</div><br><br>
<div style="height:30px; line-height:30px; text-align:center;">
<label align="center">Password:</label>
<input class="inputbox" type="password" name="pass" style="text-align:center; padding-right:14px;" value maxlength="50"><br><br>
</div><br>
<div>
<button id="login" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Login</span>
</button>
</div>
</fieldset>
</div>
</form>
</div>
</div>
and heres my php
<?PHP
include("db.classes.php");
$g = new DB();
$g->connection();
if($_POST)
{
$un = $g->clean($_POST["username"]);
$pw = $g->clean($_POST["password"]);
$g->login($un, $pw);
}
$g->close();
?>
and here's my db.classes
ublic function login($un, $pw)
{
$result = mysql_query("select username, password from admin where username='$un' and password='$pw'");
$data = $this->getResults($result);
$uName = $data["username"];
$password = $data["password"];
if($uName === $un && $password === $pw)
{
echo ('Correct');
}
else
{
echo 'Incorrect username/password';
}
}
And here's my ajax request
$( "#login" ).button().click(function( event ) {
event.preventDefault();
var un = $("input[name=uname]").val();
var pw = $("input[name=pass]").val();
var dataString = 'username='+ un + '&password='+ pw;
$.ajax({
type: "POST",
url: "processLogin.php",
data: dataString,
success: function(){
if (data === 'Login') {
window.location.replace('list.php');
}
else {
alert('Invalid Credentials');
}
}
});
});
I have already checked if my sql staments if they are to blame but they are fine. I think my problem is somewhere in the ajax request but i can't seem to point it out.
You need to narrow down where the problem is exactly, but the first thing I would change, is the way you build your query string in javascript. I am not sure if a data string gets encoded correctly if you send it directly, so I would use jQuery to make sure it does (in case your password contains funny characters for example).
Apart from that you are not using the data sent back from your ajax request in your javascript:
$.ajax({
type: "POST",
url: "processLogin.php",
data: $('form.formPadd').serialize(),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ serialize your form
success: function(data){
// ^^^^ get the data
if (data === 'Correct') {
// ^^^^^^^ this is what you echo in php
window.location.replace('list.php');
} else {
alert('Invalid Credentials');
}
}
});
You would also have to change the names of the form fields or the POST variables in php so that they match again.
As a side-note, if you are going to redirect to another page in javascript, there is not much point in using ajax in the first place.

Codeigniter twitter bootstrap login using Jquery

Am fairly new to using Jquery and am creating a login for a simple site am creating using CodeIgniter and bootstrap. After submitting the Log in button, it won't show any error or success message, meaning that I don't even know if it actually post the data to the controller
here's my code,
Jquery Code
<script>
//Wait until the DOM is fully loaded
$(document).ready(function(){
//Listen for the form submit
$('#loginform').submit(logIn);
});
//The function that handles the process
function logIn(event)
{
//Stop the form from submitting
event.preventDefault();
//Hide our form
// $('#loginform').slideUp();
//Collect our form data.
var form_data = {
email : $("[name='email']").val(),
password : $("[name='password']").val(),
};
//Begin the ajax call
$.ajax({
url: "admin",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
success: function (json) {
if (json.error==1)
{
//Show the user the errors.
$('#message').html(json.message);
} else {
//Hide our form
$('#loginform').slideUp();
//Show the success message
$('#message').html(json.message).show();
}
}
});
}
</script>
login.php
<?php
echo $this->session->flashdata('alert');
?>
<div id="message"></div>
<?php
$attr = array('class' => 'admin-login form-horizontal well form-signin', 'id' => 'loginform');
echo validation_errors('<div class="alert alert-error">', '</div>');
?>
<?php echo form_open(site_url('admin'), $attr) ?>
<!--<form action="<?php echo site_url('track-order'); ?>" method="post" class="form-horizontal form-search" id="trackModalform">-->
<div class="control-group">
<label class="control-label">Track Your Order</label>
</div>
<div class="control-group">
<label class="control-label" >Email:</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-qrcode"></i></span>
<input type="text" name="email" class="input-block-level email" placeholder="Email address">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" >Password:</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-key"></i></span>
<input type="password" name="password" class="input-block-level password" placeholder="Password">
</div>
</div>
</div>
<div class="form-actions" style="margin-bottom: 0px; padding-bottom: 0px;">
<input type="submit" class="btn btn-primary " name="signin" value="Sign In!" id="login">
</div>
</form>
my controller
public function index()
{
if (!file_exists('application/views/admin/index.php'))
{
//sorry that page is not available
show_404();
}
$this->form_validation->set_rules('email', 'Name', 'required|min_length[5]|max_length[50]|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() === TRUE)
{
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
} else {
//Save the data to the database, of course you will need all the data first.
if($this->admin_model->validate_admin_login()):
//Send the success to our javascript file.
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
endif;
}
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
}
model
public function validate_admin_login()
{
$this->str = do_hash($this->input->post('password')); // SHA1
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->str);
$query = $this->db->get('ip_admin');
if($query->num_rows == 1)
{
$data['admin_sess'] = $this->admin_model->admin_details($this->input->post('email'));
$data = array(
'email' => $this->input->post('email'),
'is_admin_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
}
public function admin_details($user)
{
$query = $this->db->select('*')->from('ip_admin')->where('email', $user);
$query = $query->get();
return $data['admin_sess'] = $query->row();
}
I don't really responding or outputting any message to indicate success or failure, maybe I got everything wrong to start with.
I need it to query the db, returns the message for me on the view page using the json parameter on my controller.
Thanks all.
I suggest you add a data in var_data like this:
var form_data = {
email : $("[name='email']").val(),
password : $("[name='password']").val(),
//add a data which is
ajax: '1'
};
And in your controller check if it is POST'ed:
if($this->input->post('ajax'){
//do something
}else{
//do something
}
so from there you could check if it is working or not. and also install firebug for debugging purposes in Firefox. In Chrome try to inspect element and see console
I honestly haven't gone through all your code as it really isn't that complicated, instead I'd like to suggest you install Firebug to debug your jquery if you haven't already installed it. Its essential when developing with javascript. It will print any errors or success as events are called and handled.
How to use: Firebug FAQ
EDIT:
As you asked for code:
if($this->form_validation->run() === TRUE)
{
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
} else {
//Save the data to the database, of course you will need all the data first.
if($this->admin_model->validate_admin_login()):
//Send the success to our javascript file.
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
endif;
}
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
Wtihin this block, you're echo'ing json once and then spitting out the HTML view afterwards. Just try removing the:
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
Or create separate controller functions for your requests, things get really messy when you try to stuff everything into a single function.

Categories