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');
}
Related
I'm trying to submit form data from view to controller using Ajax post and return success message.And ajax in my view send data to function in controller successfully but controller function does not return response back to ajax success function.
my Controller - profile.php
function save()
{
$response = array();
$this->form_validation->set_rules('fname', 'Title cant be empty ', 'required');
if ($this->form_validation->run() == TRUE)
{
$param = $this->input->post();
unset($param['submit']);
$param['rid']=$this->session->userdata('id');
$profile_id = $param['profile_id'];
unset($param['profile_id']);
if($profile_id == 0)
{
$inserts = $this->profile_model->insert($param);
if( $inserts>0){
$response['status'] = TRUE;
$response['notif'] ="success add profile details";
}else{
$response['status'] = FALSE;
$response['notif'] = 'Server wrong, please save again';
}
}else{
}
}else{
$response['status'] = FALSE;
$response['notif'] = validation_errors();
}
echo json_encode($response);
}
view - profile_new_user.php
?>
<form method="POST" id="form_profile" action="<?php echo base_url().'profile/save'; ?>">
<input type="hidden" name="profile_id" value="0"><!-------event id---------->
<div class="form-group">
<label>Prefix</label>
<select name="prefix" class="form-control">
.
.
.
</div>
<div class="form-group">
<input type="submit" name="submit" value="Save" class="btn btn-info" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form_profile").submit(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: $(this).attr("action"),
dataType :'JSON',
data: $(this).serialize(),
success: function(data)
{
if(data.status){
alert('ok');
}else{
alert('not ok');
}
}
})
});
});
model - profile_model.php
function insert($data)
{
$this->db->insert('user_profile', $data);
return $this->db->insert_id();
}
after I click submit button page redirect to url - http://localhost/ptm6/profile/save and page shows
{"status":true,"notif":"success add profile details"}
in plain text.
I expect to show alert message without any redirection.
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>
Hi I am creating a login form with CodeIgniter using ajax but it is not function properly as i want. it is getting redirected to the page which I am doing through ajax but doesnot perform the do_login function. if i click login without entering any fields it does not shows fields required whereas i have given the validation code in do_login function. Please suggest me the appropriate solution for the problem how to redirect through ajax using those functions.
This is my controller user.php
class User extends CI_Controller {
public function index()
{
$this->load->view('login');
}
public function do_login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|callback_verifyUser');
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
$this->load->view('login');
}
else{
echo "loggedIn"; // where to put this echo to make it work through ajax
$data = array(
'username' => $this->input->post('username'),
'is_logged_in'=>1
);
$this->session->set_userdata($data);
redirect('user/members');
}
}
public function members()
{
if($this->session->userdata('is_logged_in')){
$this->load->view('home');
}
else{
redirect('user/restricted');
}
}
public function restricted()
{
$this->load->view('restricted');
}
public function verifyUser(){
$username=$this->input->post('username');
$password= $this->input->post('password');
$this->load->model('LoginModel');
if($this->LoginModel->login($username, $password)){
return true;
}
else{
$this->form_validation->set_message('verifyUser','Invalid Email or Password: Please enter it correctly');
return false;
}
}
public function logout(){
$this->session->sess_destroy();
redirect('user/index');
}
}
?>
This is my view file login.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="http://127.0.0.1/simple_login_comp/js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#frm_login").submit(function(event){
event.preventDefault();
$.ajax({
url: "http://127.0.0.1/simple_login_comp/index.php/user/do_login",
type: "POST",
data:
{
username: $('#username').val(),
password: $('#password').val()},
success: function(data)
{
if (data== 'loggedIn')
{
alert("you are logged IN");
//window.location.replace("http://127.0.0.1/simple_login_redirect/index.php/user/home");
//window.location.href="http://127.0.0.1/simple_login_comp/index.php/user/members";
}
else if(data== 'sorry'){
alert("sorry");
}
//else{
// alert(data);
//}
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="span12">
<div class="well">
<center><h1>Be a member of Mrwebsiter</h1></center>
</div>
</div>
</div>
<h1>Login</h1>
<p>Please fill your details to login</p>
<form action="" id="frm_login" method="post">
Username :</br>
<input type="text" name="username" id="username"/></br>
Password :</br>
<input type="password" name="password" id="password"/></br>
<input type="submit" value="Login" name ="submit"/>
</form>
<div class="row">
<div class="span12">
<div class="well">
<center><h3>copyright</h3></center>
</div>
</div>
</div>
</div>
</body>
</html>
And this is my model LoginModel.php
<?php
class LoginModel extends CI_Model {
public function login($username, $password)
{
$this->db->select('username', 'password');
$this->db->from('users');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query= $this->db->get();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
}
?>
My login form is not working, can anyone suggest me how to make it run and where have i done mistake. when i redirect it through ajax it does not validate the input through do_login function it directly redirects to the page.
here is your problem
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
$this->load->view('login');
}
change this to
if($this->form_validation->run()== false){
echo "sorry";exit
}
I suggest that you use echo json_encode($data); on you controller where $data is an associative array containing your require fields or any prompt.
On your ajax handle the callback with -
success: function(data) {
var response = eval('(' + data + ')');
// DOM codes here
} // rest of the codes here
If you're not familiar with this and you want to push this ajax thing on you login system, I suggest you check out javascript dom, callbacks and other related stuff.
On your Controller
public function do_login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|callback_verifyUser');
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
}
else{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in'=>1
);
$this->session->set_userdata($data);
echo "loggedIn"; // where to put this echo to make it work through ajax
}
}
On your view
<script type="text/javascript">
$(document).ready(function(){
$("#frm_login").submit(function(event){
event.preventDefault();
$.ajax({
url: "http://127.0.0.1/simple_login_comp/index.php/user/do_login",
type: "POST",
data:
{
username: $('#username').val(),
password: $('#password').val()},
success: function(data)
{
if (data== 'loggedIn')
{
alert("you are logged IN");
window.location ="http://127.0.0.1/simple_login_redirect/index.php/user/members");
}
else if(data== 'sorry'){
alert("sorry");
}
}
});
});
});
</script>
I'm using CodeIgniter for my web app and I'm currently stuck with AJAX forms.
I've made an view for my "forget password" modal and it looks like this:
<form action="<?=base_url()?>users/forgot_pass" method="post" id="forget_pass_form">
<div class="form_header">
<h1>Forgot your password?</h1>
</div>
<?php if($ajax_error == 0) { ?>
<div class="front_success">
<p>Password was succesfully sent to your email address.</p>
</div>
<?php } ?>
<?php if($ajax_error == 1) { ?>
<div class="login_error">
<p>Email address was not found in the database.</p>
</div>
<?php } ?>
<div id="loading_spinner"></div>
<p><input type="text" name="to_email" placeholder="Sähköpostiosoite" class="user" style="background-postion: -200px; margin-top: 20px;" />
<input type="submit" name="to_submit" value="Lähetä salasana" class="login_submit" id="forget-pass" /></p>
</form>
And here's my controller for it:
<?php
class Users extends CI_Controller {
public function forgot_pass()
{
if(isset($_POST['to_submit'])) {
$this->load->model('user');
$email = $_POST['to_email'];
$email_addr = $this->user->get_email_address($email);
if($email_addr) {
foreach($email_addr as $row) {
$this->load->library('email');
$this->email->from('me');
$this->email->to($email);
$this->email->subject('Testing');
$this->email->message('Your password is: ' . $row['password']);
if(!$this->email->send()) {
$data['ajax_error'] = 1;
} else {
$data['ajax_error'] = 0; }
}
}
}
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
}
?>
I won't post my Model since I know 100% sure it works and it only contains that one method to check if email is found in the database.
Now I want to make it more dynamic by using AJAX. I want it to echo the success message inside a div if the email address was found in the database and the mail was sent
to that email address, otherwise I want it to echo out the error "User was not found in the database".
Here's my js file which for now:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(){
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
}
});
return false;
});
});
The AJAX part itself is working, but I just don't know how to implement those messages. Any help would be much appreciated.
make your html code like this
<div class="front_success" style="display:none">
<p>Password was succesfully sent to your email address.</p>
</div>
<div class="login_error" style="display:none">
<p>Email address was not found in the database.</p>
</div>
small change in controller:-
if($this->email->send()) {
echo '1';
} else {
echo '0';
}
so what ever your controller return based on that success function will make the dive show
try to make you ajax code like this :-
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
},
success: function (data) {
//alert(data); alert it if you want to check the function output
if(data == '1'){
//if the email is send then it return 1 so that you show success msg
$("#login_success").show();
}else{
//if the email is not send then it return 0 so that you show error msg
$("#front_error").show();
}
$("#loading_spinner").hide();// hide when ajax complete
}
});
I want to make live search using codeigniter and jquery and mysql
but when i type something the result's not showing
here is my model code :
<?php
class artikel_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function cari_artikel($q)
{
$this->db->select('judul,contain');
$this->db->like('judul', $q);
$this->db->or_like('contain', $q);
$query = $this->db->get('artikel');
return $query->result_array();
}
}
?>
and here is my controller code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('artikel_model');
}
public function index()
{
if(isset($_GET['q']) && $_GET['q']){
$q = $this->input->get('q');
$this->data['data']=$this->artikel_model->cari_artikel($q);
}
else{
$this->data['data']=array_fill_keys(array('judul', 'contain'), NULL);
}
$this->data['body']='dashboard';
$this->load->view('welcome_message',$this->data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
this is my view code
<?php $this->load->helper('html');?>
<div class="row">
<div class="span12 offset3">
<form class="form-inline" name="form1" method="get" action="">
Search : <input type="text" class=span5 name="q" id="q"/> <label for="mySubmit" class="btn btn-primary"><i class="icon-search icon-white"></i></label> <input id="mySubmit" type="submit" value="Go" class="hidden" />
</form>
</div>
</div>
<?php echo br(15); ?>
<div id="result"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var allow = true;
$(document).ready(function(){
$("#q").keypress(function(e){
if(e.which == '13'){
e.preventDefault();
loadData();
}else if($(this).val().length >= 2){
loadData();
}
});
});
function loadData(){
if(allow){
allow = false;
$("#result").html('loading...');
$.ajax({
url:'http://localhost/helpdesk?q='+escape($("#q").val()),
success: function (data){
$("#result").html(data);
allow = true;
}
});
}
}
</script>
<?php
foreach($data as $row){ ?>
<h3><?php echo $row['judul']; ?></h3>
<?php } ?>
The live search is not working.
when i type something the output just "loading..."
and the result is not showing..
If i press enter, the result will show. but that is just the usual searching method. Not live searching.
Make a new function say "live_search" that will only return the result with the ajax search and not the "index" function. This new function will return the result with the HTML markup.
public function live_search(){
if($this->input->post(null)){
//put your search code here and just "echo" it out
}
}
$.ajax({
url:'http://localhost/domain/controller/live_search',
type : 'POST',
data : { 'q' : escape($("#q").val()) },
success: function (data){
$("#result").html(data);
allow = true;
}
});
Hope it helps you.