Codeigniter & jquery Ajax - php

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'));?>

Related

Error in Codeigniter :- Call to undefined method CI_Loader::select()

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.

CodeIgniter Login Form Using Ajax

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>

How to add options to drop down list and save it to the database?

I'm new to codeigniter and I'm really confused on how to add options to the drop down list and save the added options in the drop down list to the database. Can anyone help me with this?
My View:
<!doctype html>
<html>
<head>
<title>My Form</title>
<script src="<?php echo base_url();?>assets/js/jquery-1.11.1.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#myselect').change(function(e) {
if ($(this).val() == "addother") {
$('#addother').show();
$('#addother_input').val('');
} else {
$('#addother').hide();
}
});
$('#add').click(function() {
$.ajax({
type: "POST",
url: window.location,// use ci url here(i.e call controller)
data: { selectboxvalue: $options.val() } ///value will be sent
})
.done(function( msg ) {
$('#add').html(msg);
});
});
});
</script>
<style>
#addother {
display: none;
}
</style>
</head>
<body>
<div id="container">
<?php
$options = array(
'small' => 'Small Shirt',
'med' => 'Medium Shirt',
'large' => 'Large Shirt',
'xlarge' => 'Extra Large Shirt',
'addother' => "Add other..."
);
echo form_dropdown('shirts', $options, null, 'id="myselect"');
?>
<div id="addother">
<?php echo form_input(array('id'=>'addother_input', 'name'=>'add', 'placeholder'=>'Enter name of school...')); ?>
<input type="submit" id="add" name="submit" value="+" />
</div>
</div>
</body>
</html>
My Controller:
function add() {
$this->load->model('fruit_model');
$data['selectboxvalue'] = $this->input->post('selectboxvalue');
$res = $this->model->addItem($data);
$this->load->view('myform');
}
function drop() {
$this->load->model('getAll');
$data["opt"] = $this->fruit_model->getAll();
$this->load->view('myform');
}
My Model:
function getAll() {
$query = $this->db->get('fruits')
return $query->result();
}
function addItem($data){
$this->db->insert('fruits', $data);
return;
}
How to save the added options into the database?
I giving simple php answer....change that to ci type
html & ajax code:
<input type="text" name="selct" id="name" ><input type="submit" id="submit"/>
<div id="box"> <select name="selectbox" id="testselect"></select></div>
<script>
$('#submit').click(function(){
$.ajax({
type: "POST",
url: "some.php",// use ci url here(i.e call controller)
data: { selectboxvalue: $("#name").val() } ///value will be sent
})
.done(function( msg ) {
$('#box').html(msg);
});
});
</script>
Some.php page
database connection
insert $_post['selectboxvalue'] value in your database and fetch all values
from database and populate in select box.i think it is easy so i am not writing
the code
try this example
<?php
class Options extends CI_Controller{
function index()
{
$this->load->view('view name');
}
function create()
{
$data = array(
'name' => $this->input->post('name'),
'price' => $this->input->post('price'));
$this->data_model->addItem($data);
$this->index();
}
}
Model
<?php
class Data_model extends CI_Model {
function getAll() {
$q = $this->db->query("SELECT * FROM items");
if($q->num_rows() >0){
foreach($q->result() as $row){
$data[]=$row;
}
}
return $data;
}
function addItem($data){
$this->db->insert('items', $data);
return;
}
}
?>
View
<html><head></head><body>
<style type="text/css">
label {display: block;}
</style>
<h2>Create</h2>
<?php echo form_open('controllername/function name/'); ?>
<p>
<label for="name">Name</label><input type="text" name="name" id="name" />
</p>
<p>
<label for="name">Price</label>
<select name="price">
<option value="1">$100</option>
<option value="2">$200</option>
<option value="3">$300</option>
</select>
</p>
<p><input type="submit" value="Submit" /></p>
<?php echo form_close(); ?>
</body>
</html>

CodeIgniter Ajax is not working

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');
}

JQuery Live Search in codeigniter

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.

Categories