I have Created View, Controller Model and connect the database with the codeigniter project.
And i have already configures codeigniter with database.
But when i run the project It Gives me the Error as follow:-
Message: Call to undefined method CI_Loader::select()
My View is:-
login.php
<html>
<head>
<title>Login to Dhoami Enterprice</title>
<script src="<?php echo base_url();?>/assets/js/jquery-3.2.1.js"></script>
<script src="<?php echo base_url();?>/assets/js/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/assets/css/sweetalert.css">
<head>
<body>
<form id="login_form" method="POST" >
<input type="text" name="u_name" placeholder="Enter E-mail">
<input type="text" name="u_pass" placeholder="Enter Password">
<button type="submit" name="login_submit">Login</button>
</form>
</body>
<script>
/* function login(){
var form_data = $('#login_form').serialize();
alert(form_data);
} */
$('#login_form').submit(function(e){
e.preventDefault();
var form_data = $('#login_form').serialize();
$.ajax({
type:'POST',
url:'<?php echo base_url();?>/login/login_ajax',
data:form_data,
success: function(){
},
error:function(xhr){
swal("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
});
</script>
</html>
Cotroller is:-
Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Login_model');
}
public function index()
{
$this->load->view('login');
}
public function login_ajax(){
$user_email = $this->input->post('uname');
$user_password = $this->input->post('upass');
$user_password = hash('sha512', $user_password);
$where = array('email'=>$user_email,'password'=>$user_password);
$data['user_status'] = $this->Login_model->check_user($where);
print_r($data['user_status']);
}
}
ModelIs as Follow:-
Login_model.php
<?php
class Login_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->db = $this->load->database('default');
}
public function check_user($where){
$this->db->select('*');
$this->db->from('user');
$this->db->where($where);
$query = $this->db->get();
echo $this->db->last_query();
//return $query->result_array();
}
}
?>
According to CodeIgniter's source, the $this->load->database('default') call will return an instance of CI_Loader class unless you pass a second boolean poaremter.
So, basically, it should be
$this->db = $this->load->database('default', true);
P.S. you really should not use CodeIgniter in any new projects.
Related
I can not insert the data by forms in the database with ajax,There is no firebug error someone can help me
View:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog</title>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.min.css"); ?>">
</head>
<body>
<h3 style="text-align: center;">CODEIGNITER AJAX</h3>
<div class="row">
<div class="alert alert-success" id="message" style="display: none;">
</div>
<div class="col-md-4"></div>
<div class="col-md-4">
<?php echo form_open('blog_c',array('id'=>'myForm'));?>
<div class="form-group">
<label>EMAIL:</label>
<input type="text" name="email" id="email" class="form-control" placeholder="EMAIL">
</div>
<input type="submit" value="ENVOYER" id="btn">
<?php echo form_close()?>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url()?>assets/js/jquery-3.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btn').click(function(){
var email=$('#email').val();
$.ajax({ //request ajax
url:"<?php echo site_url('blog_c/registre')?>",
type:POST,
data:{email:email},
dataType:json,
success: function(repons) {
$("#message").html(repons);
},
error: function() {
alert("Invalide!");
}
});
});
});
</script>
</body>
</html>
Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog_m extends CI_Model
{
function __construct()
{
parent:: __construct();
}
function registre($data)
{
$this->db->insert('utilisateurs',$data);
}
}
Controler:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Blog_c extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('blog_w');
}
public function registre()
{
// set rules
$this->form_validation->set_rules('email','EMAIL','trim|required|valid_email|is_unique[utilisateurs.email]');
if($this->form_validation->run()==FALSE)
{
echo validation_errors();
}else{
$data=array(
'email'=>$this->input->post('email'));
$this->blog_m->registre($data);
echo "<div class='alert'>Inscription success</div>";
echo "email";
}
}
}
There is no error but the data does not insert in the database and there is no success message.
Try this.
In View (AJAX Part)
<script>
$(function(){
$( "#btn" ).click(function(event)
{
event.preventDefault();
var email= $("#email").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url(); ?>index.php/blog_c/registre",
data:{ email:email},
success:function(response)
{
console.log(response);
$("#message").html(response);
$('#cartmessage').show();
}
error: function()
{
alert("Invalide!");
}
}
);
});
});
</script>
In Controller
public function registre()
{
$email = $this->input->post('email'); # add this
$this->form_validation->set_rules('email','EMAIL','trim|required|valid_email|is_unique[utilisateurs.email]');
if($this->form_validation->run() == FALSE)
{
echo validation_errors();
}
else
{
if(!$this->blog_m->registre($email))
{
echo "Something Went Wrong";
}
else
{
echo "Inscription success";
}
}
}
In Model
function registre($email)
{
$data = array(
'email'=>$this->input->post('email')
);
$this->db->insert('utilisateurs',$data);
}
In your controller load model first.Like this..
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));//loads required heplers
$this->load->model('blog_m');//loads your model
}
In view: you are using ajax so set form action empty.Like this..
<?php echo form_open('',array('id'=>'myForm'));?>
I have my React app running on localhost:3000
My CodeIgniter API running on localhost:8000
I'm trying to send an AJAX post request and pass data in JSON format but don't know how to receive it in my controller... Here is what I have
REACT
import React, { Component } from 'react';
import Request from 'superagent';
class App extends Component {
constructor(){
super()
this.state = {
email: '',
password: ''
}
}
updateEmail(e){
this.setState({
email: e.target.value
})
}
updatePassword(e){
this.setState({
password: e.target.value
})
}
createUser(e){
var query = 'star';
e.preventDefault()
console.log(this.state.email)
var url = `http://localhost:8888/CI-React-API/React_api/create`;
Request.post(url)
.set('Content-Type', 'application/json')
.send({ email: 'test' })
.then((response) => {
console.log(response)
});
}
render() {
return (
<div className="App">
<div className="App-header">
<form onSubmit={this.createUser.bind(this)}>
<input type="text"
name="email"
onChange={this.updateEmail.bind(this)}
value={this.state.email}
placeholder="email"/>
<br/>
<input type="text"
name="password"
value={this.state.password}
onChange={this.updatePassword.bind(this)}
placeholder="password"/>
<br/>
<input type="submit" value="submit"/>
</form>
</div>
</div>
);
}
}
export default App;
CodeIgniter
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class React_api extends CI_Controller {
public function create()
{
$obj=json_decode(file_get_contents('php://input'), true);
// $email = $this->input->post('email');
// echo $email;
var_dump(file_get_contents('php://input'));
die;
// IDEA $this->load->view('welcome_message');
}
}
Change url
var url = `http://localhost:8888/CI-React-API/React_api/create`;
to
var url = 'http://localhost:8888/react_api/create';
OR
var url = '<?php echo base_url("react_api/create");?>';
And load url helper in controller as below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class React_api extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
}
public function create()
{
$email = $this->input->post('email');
echo $email;
$obj=json_decode(file_get_contents('php://input'), true);
var_dump(file_get_contents('php://input'));
die;
// IDEA $this->load->view('welcome_message');
}
}
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>
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');
}
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.