I am having trouble in combining CodeIgniter and AJAX. I have a sign up form. What I want is that when user clicks on sign up button on my home page, he gets a sign up form in pop up. If he enter wrong details in the form , he is prompted on the pop up itself that your details are invalid, He must not be redirected to new page to show errors. So I am using bpopup to make my form pop up and ajax request, but I am not able to perform form_validation, I am little confused. If user does not pass form validation a HTML document is alerted to the user because of view being loaded. If I will not load the view , it will not show login page. If I will directly load view , how will I show user individual errors , like password must be 6 characters long. Here is my code :
My login view :
<html>
<head>
<title>Sign In</title>
<script type="text/javascript">
var frm = $('form');
frm.submit(function () {
$("#status").empty();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if (data == "invalid") {
$('#status').html("Invalid Login Details");
}
else if(data == "valid")
{
$('#status').html("Login successful");
setTimeout(function(){
location.reload();
},600);
}
else
{
$('#status').html("Your Account is not Activated");
}
}
});
return false;
});
</script>
</head>
<body>
<div class="Header">
<h3>Sign In </h3>
</div>
<div id="status"></div>
<div class="main">
<?php echo form_open('xyz/signin'); //Renders the form element and adds extra functionality like Adds a hidden CSFR prevention field.?>
<h5>Email</h5> // For the time being I have remove echo form_error.
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="25"/>
<h5>Password *</h5> // For the time being I have remove echo form_error.
<input type="password" name="password" size="25"/>
<div><input type="submit" value="Submit" "/></div>
</form>
</div>
</body>
</html>
and here is my sign in function of xyz controller :
public function signin()
{
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'email',
'label' => 'Email Address',
'rules' => 'trim|required|valid_email|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|xss_clean'
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE) /
{
$this->load->view('pinflag/login.php');
}
else //format of form is correct
{
$email = $this->input->post('email');
$password = md5($this->input->post('password'));
$data = array(
'email' => $email,
'password' => $password
);
$result = $this->user_model->get_users($data);
if($result->num_rows == 1) //login details are correct
{
$result = $result->result_array();
if($result[0]['status'] == 0)
{
echo "notActivated";
}
else
{
$this->session->set_userdata('id',$result[0]['id']);
$this->session->set_userdata('name',$result[0]['fname']);
echo "valid";
}
}
else //when user enter invalid login details
{
echo "invalid";
}
}
}
Sorry, indentation got all messed up when I pasted the code here.
i didn't get how your pop is coming but for error and success messages try
$this->session->set_flashdata("msg","<span class='m_error'>".$this->lang->line('global_insert_error')."</span>");
before your page to be loaded.
and inside your login view any part
if($this->session->flashdata('msg'))
{
echo $this->session->flashdata('msg');
}
Related
I am using codeigniter HMVC. I'm trying to create a sign up form that opens when sign up button is clicked. However, validation errors for the sign-up form appears on the parent page where the login form is located the dialog also closes after submitting data. What I want to do is to display the errors on the sign-up form dialog.
vw_login.php
<button id="show-sign-up-dialog">Sign Up</button>
<dialog id="sign-up-dialog" >
<button id="close"><i class="fa fa-times"></i></button>
<?php echo form_open('user/sign_up', 'id = "reg_form" class="form-horizontal" role="form"'); ?>
<!-- REGISTER USERNAME -->
<div class="form-group">
<div class="col-12">
<label for="name"></label>
<?php
$regi_username_attrib = array(
'name' =>'register_username',
'class'=>'form-control mdl-input-login',
'rows' =>'4',
'placeholder'=>'Username'
);
echo form_error('register_username');
echo form_input($regi_username_attrib, set_value('register_username', ''));
?>
</div>
</div>
//Script to submit sign up form
<script>
$(document).on("click", "#btn_sign_up", function ()
{
$.ajax({
type: "POST",
url: "<?php echo base_url('user/sign_up');?>",
data: $(this).serialize(),
success: function(data) {
var obj = $.parseJSON(data);
if(obj!==null)
{
$('#error_msg').html(obj['error_message']);
}
}});
});
</script>
//Script to open sign up form
<script>
var dialog_AddEntry = document.querySelector('#sign-up-dialog');
var showDialogButton_AddEntry = document.querySelector('#show-sign-up-dialog');
if (! dialog_AddEntry.showModal) {
dialogPolyfill.registerDialog(dialog_AddEntry);
}
showDialogButton_AddEntry.addEventListener('click', function() {
dialog_AddEntry.showModal();
});
dialog_AddEntry.querySelector('#close').addEventListener('click', function() {
dialog_AddEntry.close();
});
</script>
Controller
class User extends My_Controller {
public function index()
{
$this->load->view('vw_login');
}
public function login()
{
//|is_unique[tbl_user.user_username]
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE) // If username and password is invalid
{
$this->load->view('vw_login');
}
else
{
}
}
public function sign_up()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('register_username', 'Username', 'trim|required');
if ($this->form_validation->run() == FALSE) // If username and password is invalid
{
$this->load->view('vw_login');
$data = array('error_message' => form_error('register_username'));
echo json_encode($data);
}
else
{
}
}
}
Add the following
<span id="error_msg"></span>
after
<label for="name"></label>
I have a login form in boostrap's modal window
<form method="post" id="loginForm" action="index.php">
<label for="email">Email:</label>
<input class="form-control" type="text" name="email" value="" id="emailLogin"/><br/>
<label for="password">Password:</label>
<input class="form-control" type="password" name="password" value="" id="passwordLogin"/><br/>
<div id="loginAlert" class="alert alert-danger" role="alert">Email or password incorrect</div> <!-- Hidden by default -->
<button type="submit" name="login" class="btn btn-primary" id="loginButton">Login</button>
<script src="checkLoginForm.js"></script></form>
I would like to check this form (if email and password are correct) before submitting it. If the function, which checks the email and password returns 1, there is something incorrect. Form should not submit in this case and it should just make the alert visible.
If everything is correct, it should submit.
Thing is: I can prevent the form from submitting, if the the email and password are incorrect, but I can't submit it, if they are correct. Here is the code from checkLoginForm.js
$(document).ready(function() {
$("#loginForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'include/ajax.php?action=checkLogin',
data: {
email: $("#emailLogin").val(),
password: $("#passwordLogin").val(),
},
success: function(result) {
console.log(result);
if(result == 0) {
} else {
$("#loginAlert").css({"display": "block"});
}
}
});
});
});
I have no idea what to do, when the result == 0. If I do $("loginForm").submit();, that does not submit the form (else part does work).
Thank you for your replies.
I would advice you to use a simple $.post, it's a shorthand way of using $.ajax for POST requests. Just check if the values provided are correct in your php file, if they are correct process that data and return true or redirect the user to another page else return false.
$(document).ready(function() {
$("#loginButton").on('click', function (e){
e.preventDefault();
var email = $("#emailLogin").val();
var passwd = $("#passwordLogin").val();
$.post('include/ajax.php?action=checkLogin', {email: email, password: passwd}, function (data) {
var res = $.parseJSON(data);
if (res.result == true) {
//you can redirect the or display a message to the user.
//redirect the user to another page
//$("#loginAlert").css({"display": "block"}).html("login successful");
}else {
$("#loginAlert").css({"display": "block"});
}
});
});
});
Then in your php file
if (isset($_GET['action']) && $_GET['action'] == 'checkLogin') {
$passwd = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
//validate inputs here
//get data from db
//then compare values
//if values match return true
//$db_mail and $db_passwd are from the db.
if ($email == $db_mail && $passwd == $db_passwd) {
//if the provided information is correct
//process it here, login the user.
//redirect if necessary.
// or return results to JS
echo json_encode(['result' => true]);
} else {
//if the information is wrong return false to JS
//and alert the user
echo json_encode(['result' => false]);
}
}
I'd like some help please.
I'm having a form placed inside a bootstrap modal window.
<div class="modal-content">
<div class="modal-body">
<div id="ajaxResults"></div>
<?php echo form_open('controller-name/form-process'), array('id' => 'modal-form'); ?>
<input type="hidden" name="title" id="hid-title" />
<div class="form-group">
<?php echo form_input('first_name', set_value('first_name', $this->input->post('first_name')), 'id="first-name" class="form-control" placeholder="First name"'); ?>
</div>
<div class="form-group">
<?php echo form_input('last_name', set_value('last_name', $this->input->post('last_name')), 'id="last-name" class="form-control" placeholder="Last name"'); ?>
</div>
<div class="form-group">
<?php echo form_input('email', set_value('email', $this->input->post('email')), 'id="email" class="form-control" placeholder="Email"'); ?>
</div>
<div class="form-group">
<?php echo form_input('company', set_value('company', $this->input->post('company')), 'id="company" class="form-control" placeholder="Company"'); ?>
</div>
<?php echo form_close(); ?>
</div><!-- /.modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn border-black" data-dismiss="modal">Close</button>
<button type="button" class="btn btn border-theme" id="form-submit-btn">Submit form</button>
</div><!-- /.modal-footer -->
</div><!-- /.modal-content -->
When I click the Submit the Form button I'm sending an ajax request to my form_process controller where I do the form validation. Here's my code for the form_process function and the ajax script
public function form_process() {
if ($this->input->post()) {
$rules = array(
'first_name' => array(
'field' => 'first_name',
'label' => 'First name',
'rules' => 'required|trim|min_length[2]',
),
'last_name' => array(
'field' => 'last_name',
'label' => 'Last name',
'rules' => 'required|trim|min_length[2]',
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|trim|valid_email',
),
'company' => array(
'field' => 'company',
'label' => 'Company',
'rules' => 'required|trim',
),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($rules);
// validate the form
if ($this->form_validation->run()) {
$response = array(
'status' => '200',
'message' => 'Thank you! We have sent an email to ' . $this->input->post('email') . ' to get your white paper.',
);
} else {
$response = array(
'status' => '400',
'message' => validation_errors(),
);
}
// return the result of the form process
$this->output->set_status_header($response['status'])->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT))->_display();
exit();
}
The ajax script looks like this
$('#myModal').on('show.bs.modal', function (event) {
$('#modal-form').show();
$('#ajaxResults').removeClass('alert alert-success alert-error');
// Button that triggered the modal
var button = $(event.relatedTarget);
// Extract info from data-* attributes
var recipient = button.data('whatever');
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('.modal-title').html('New message to <br/>' + recipient);
modal.find('.modal-body input[type=hidden]').val(recipient);
// submit the form
$('#form-submit-btn').on('click', function (event){
event.preventDefault();
var url = $('#modal-form').attr('action');
// send ajax request
$.ajax({
url: url,
type : 'POST',
data : {
'first_name' : $('#first-name').val(),
'last_name' : $('#last-name').val(),
'email' : $('#email').val(),
'company' : $('#company').val(),
'title' : $('#hid-title').val(),
},
dataType: 'json',
success : function(response) {
alert(response.message);
// console.log(response.message);
$('#ajaxResults').removeClass('alert alert-success alert-error');
if (response.status == 200) {
$('#modal-form').hide();
$('#ajaxResults').addClass('alert alert-success').html(response.message);
alert('AAAAAAAAAAAAAAAAAAAAAAAAAAAA');
}
if (response.status == 400) {
$('#modal-form').show();
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
alert('BBBBBBBBBBBBBBBBBBBBBBBBBBBB');
}
},
error: function(response){
// code ...
$('#ajaxResults').removeClass('alert alert-success alert-error');
if (response.status == 200) {
$('#modal-form').hide();
$('#ajaxResults').addClass('alert alert-success').html(response.message);
alert('CCCCCCCCCCCCCCCCCCCCCCCCCCC');
}
if (response.status == 400) {
$('#modal-form').show();
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
alert('DDDDDDDDDDDDDDDDDDDDDDDDDDDD');
}
}
});
});
});
EDIT I did an update on my ajax script and placed some alert messages, as you can see. When I click the submit button without submitting the form ( so there are errors), the alert DDDDDDD pops up.
When I fill all fields and submit the form the alert CCCCCCC pops up (!!!). In addition the ajaxResults div gets the .alert and .allert-success classes, but still can't see any message.
Any ideas what I'm doing wrong ?
Additional question: Is the error: function(response) used to show the the case where validation fails ?
I have also tried to move the validation errors inside this function and keep on success : function(response) only the success submition of the form, but still no luck.
I can see you are not parsing the data properly
example : in alert('DDDDDDDDDDDDDDDDDDDDDDDDDDDD'); line
before appending data to your ajaxResults you need to convert data Properly
response.responseText => will give you json string .
JSON.parse => will convert string to JSON Obj so that you can
use it like .variableName
Please add the following code before your
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
add following line
var mess = JSON.parse(response.responseText).message;
replace response.reason to mess it should show you error Messages
Please mark it as answer if it works
full Code :
if (response.status == 400) {
$('#modal-form').show();
var mess = JSON.parse(response.responseText).message;
$('#ajaxResults').addClass('alert alert-error').html(mess);
alert('DDDDDDDDDDDDDDDDDDDDDDDDDDDD');
}
working
If it takes you to the error part, then you must use something like this to catch it:
,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError) ; // or alert(xhr.responseText);
$('#ajaxResults').addClass('alert alert-error').html(thrownError) ;
}
And if the ajax call is successful, something like this:
,
succes: function(data, status, jqXHR){
if (status == 200) {
$('#modal-form').hide();
$('#ajaxResults').addClass('alert alert-success').html(response.message);
alert(data);
}
}
The "problem" was this output->set_status_header($response['status']) the request was always successful, but setting a header to 400 messed up the functionality.
I removed this piece of code and now works fine! However I still needed to add the
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError) ; // or alert(xhr.responseText);
$('#ajaxResults').addClass('alert alert-error').html(thrownError) ;
}
to get any errors in cases that the request fail.
CodeIgniter Ajax is not working for me.
This is what I have tried so far.
v_login.php
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('#username').val(),
password : $('#password').val(),
ajax : '1'
};
$.ajax({
url: "<?php echo site_url('c_login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<div class="container">
<div class="jumbotron">
<?php
$attributes = array('class' => 'form-signin');
echo form_open('c_login', $attributes); ?>
<h2 class="form-signin-heading">VMS Login System</h2>
<input type="username" name="username" id="username" class="form-control" placeholder="Username" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<input class="btn btn-primary" type="submit" id="submit" value="Login">
<input class="btn btn-primary" type="reset" value="Cancel">
<?php echo form_close(); ?>
<div id="message">
</div>
</div>
</div>
C_login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
}
function index() {
$this->load->view('include/header');
$this->load->view('v_login');
$this->load->view('include/footer');
}
function ajax_check() {
if($this->input->post('ajax') == '1') {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user == '1') {
echo 'login successful';
} else {
echo 'unknown user';
}
}
}
}
}
/* End of file c_login.php */
/* Location: ./application/controllers/c_login.php */
m_access.php
<?
class M_access extends CI_Model {
public function check_user($username,$password) {
$this->query = $this->db->select('COUNT(*)')->from('users')->where(array('username'=>$username,'password'=>$password))->limit(1)->get();
return $this->query->row_array();
}
}
I don't know what's wrong, I have already set up config.php and routes. But it's not working at all. Any ideas? Help is much appreciated. Thanks.
After a long chat with OP the solution is this
Your model
class M_access extends CI_Model {
public function check_user($username,$password) {
$args = array(
'username' => $username,
'password' => $password
);
$query = $this->db->select('*')->from('users')->where($args)->get();
if($query->num_rows()) {
return $query->row_array();
}
return false;
}
}
In your controller, use
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'), $this->input->post('password'));
if($user) {
// right user
}
else {
// wrong user
}
Don't need to send ajax:1 because jQuery sends a request header to server, like this
X-Requested-With': 'XMLHttpRequest'
and in CodeIgniter you may check for ajax request using
if($this->input->is_ajax_request()){
// it's an ajax request
}
Also, you asked for a gif loader to shw, so this could be used as
$('#submit').click(function() {
var form_data = { ...};
// show the gif loader
$.ajax({
...
data: form_data,
success: function(msg) {
// hide the gif loeader
$('#message').html(msg);
}
});
});
Update : For inserting an image you may check this fiddle example, like
$('#submit').click(function(e){
e.preventDefault();
var loader = $('<img/>', {
'src':'url_of_the_image',
'id':'ajax_loader'
});
loader.insertAfter($(this));
});
and to remove the image in your success callback, you may use
$('#ajax_loader').remove();
error 404 due to the calling path because file name with "C" and you calling it with "c", rather than that
in my opinion you need to have a deeper look at codeigniter form validation helper
before you try the ajax call
once you did it server side perfectly & if you still want to validate using ajax , make another function as a webservice only for this purpose along the orignal server side validation function , it'd be something like that
function ajax_check(){
$username_check=true;
//your code goes here to check if username unique or not and result assigned to $username_check
if(!$username_check){
echo json_encode('fail');
return;
}
echo json_encode('success');
}
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.