I am creating a search Bar using Jquery autocomplete in Codeigniter 3 using and ajax and MySQL
Here is Controller College.php Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class College extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->model('College_model');
}
public function index() {
$this->load->view('college_view');
}
function get_autocomplete() {
if (isset($_GET['term'])) {
$result = $this->college_model->search_college($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row) {
$arr_result[] = array(
'name' => $college_name,
'description' => $row->college_description,
);
echo json_encode($arr_result);
}
}
}
}
}
?>
This is College_model.php
<?php
class College_model extends CI_Model
{
function get_all_college() {
$result = $this->db->get('college');
return $result;
}
function search_college($name) {
$this->db->like('college_name', $name, 'both');
$this->db->order_by('college_name', 'ASC');
$this->db->limit(10);
return $this->db->get('college')->result();
}
}
?>
This is view page college_view.php
<div class="tab-content py-3 px-3 px-sm-0 m-auto" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
<form action="http://vufind.carli.illinois.edu/vf-aru/Search/Home" method="get" role="search" target="vufind" name="searchForm">
<div class="input-group lrcInputs">
<input value="1" name="start_over" type="hidden">
<label></label>
<input class="form-control" id="college" name="college" type="text" placeholder="Search for books, ebooks, & media">
<div class="input-group-btn">
<button class="btn btn-success lrcSearchButton" type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#college').autocomplete({
source: "<?php echo site_url('college/get_autocomplete'); ?>",
select: function (event, ui) {
$('[name="college"]').val(ui.item.name);
}
});
});
</script>
How to remove the error of 404 not found. if need more code or file i will help.
I m getting error in chrome console as GET http://localhost/apluscollege/college/get_autocomplete?term=as 404 (not found)
jquery.min.js
what is the isuue in the code ...I have checked from every possible angle of code.
In the controller, please write
$this->load->model('college_model');
instead of
$this->load->model('College_model');
The model name should be the same case when you load and use it
Related
Here I am trying to make a form which enables admin to add a new company , i need to implement the form validation and after that insert data to table (company_details),here is what i have done, using codeigniter and ajax, I am not sure if there is other simple ways to do this process without using ajax , so if there is i would appreciate you help me. here is my code but now when i press create button notting actually happens, and i get
"error :Failed to load resource: the server responded with a status of 500 (Internal Server Error). company:1"
Company.php Controller
<?php
class Company extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('admin');
$this->load->model('company_model');
}
function index()
{
$data['company'] = $this->company_model->getCompanyDetails();
$this->load->view('admin/company', $data);
}
function validation()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('Cname' , 'Company Name' , 'required');
$this->form_validation->set_rules('shname' , 'Short Name' , 'required');
$this->form_validation->set_rules('regNo' , 'Registration No' , 'required|valid_regNo');
if($this->form_validation->run())
{
$this->company_model->create();
$array = array(
'succsee' => '<div class="alert alert success">Your Company Added Sucessfully</div>'
);
redirect('admin/company/');
}
else
{
$array = array(
'error' => true,
'Cname_error' => form_error('Cname'),
'shname_error' => form_error('shname'),
'regNo_error' => form_error('regNo'),
);
}
echo json_encode($array);
}
}
company.php view
<div class="companyAdd" style="display: none;">
<h2 class="heading">Add Company</h2>
<span action="<?php echo site_url('admin/staff/validate');?>" id="success_message"></span>
<form method="post" id="AddCompanyForm">
<div class="row">
<div class="form-group col-md-4">
<label for="email">Company Name</label>
<input type="text" class="form-control" id="Cname" placeholder="Name" name="Cname">
<span id="Cname_error" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="pwd">Short Name</label>
<input type="text" class="form-control" id="shname" placeholder="Short Name" name="shname">
<span id="shname_error" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="pwd">Registration No</label>
<input type="text" class="form-control" id="regNo" placeholder="01234567" name="regNo">
<span id="regNo_error" class="text-danger"></span>
</div>
<div class="col-md-12">
<div class="btn-section float-right">
<button class="btn btn-outline-primary" type="submit"><i class="fa fa-plus-circle" aria-hidden="true" id="Ccreat"></i> Create</button>
<button class="btn btn-danger float-right" id="cancelCompany" type="button" onClick="window.location.href=admin/company"><i class="fa fa-plus-circle" aria-hidden="true"></i> Cancel</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
This is my script tag in company.php view
<script>
$(document).ready(function(){
$('#AddCompanyForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"<?php echo site_base();?>admin/company/validation",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#Ccreat').attr('disabled', 'disabled');
},
success:function(data)
{
if(data.error)
{
if(data.Cname_error != '')
{
$('#Cname_error').html(data.Cname_error);
}
else
{
$('#Cname_error').html('');
}
if(data.shname_error != '')
{
$('#shname_error').html(data.shname_error);
}
else
{
$('#shname_error').html('');
}
if(data.regNo_error != '')
{
$('#regNo_error').html(data.regNo_error);
}
else
{
$('#regNo_error').html('');
}
}
if (data.success)
{
$('#success_message').html(data.success);
$('#Cname_error').html('');
$('#shname_error').html('');
$('#regNo_error').html('');
$('#AddCompanyForm')[0].reset();
}
$('#Ccreat').attr('disabled',false);
}
})
});
});
</script>
And here is Company_model.php
<?php
class Company_model extends CI_Model
{
//table name: company_details
function getCompanyDetails()
{
return $this->db->get('company_details')->result();
}
function create()
{
$arr['company_name'] = $this->input->post('Cname');
$arr['short_name'] = $this->input->post('shname');
$arr['registration_no'] = $this->input->post('regNo');
$this->db->insert('company_details',$arr);
}
}
This is my first time working with codeigniter and ajax , i would appreciate if someone can help me to solve it.
This is controller College.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class College extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->model('College_model');
}
public function index() {
$this->load->view('college_view');
}
function get_autocomplete() {
if (isset($_GET['term'])) {
$result = $this->college_model->search_college($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row) {
$arr_result[] = array(
'name' => $college_name,
'description' => $row->college_description,
);
echo json_encode($arr_result);
}
}
}
}
}
?>
This is College_model.php
<?php
class College_model extends CI_Model
{
function get_all_college() {
$result = $this->db->get('college');
return $result;
}
function search_college($name) {
$this->db->like('college_name', $name, 'both');
$this->db->order_by('college_name', 'ASC');
$this->db->limit(10);
return $this->db->get('college')->result();
}
}
?>
This is view page college_view.php
<div class="tab-content py-3 px-3 px-sm-0 m-auto" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
<form action="http://vufind.carli.illinois.edu/vf-aru/Search/Home" method="get" role="search" target="vufind" name="searchForm">
<div class="input-group lrcInputs">
<input value="1" name="start_over" type="hidden">
<label></label>
<input class="form-control" id="college" name="college" type="text" placeholder="Search for books, ebooks, & media">
<div class="input-group-btn">
<button class="btn btn-success lrcSearchButton" type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#college').autocomplete({
source: "<?php echo site_url('college/get_autocomplete'); ?>",
select: function (event, ui) {
$('[name="college"]').val(ui.item.name);
}
});
});
</script>
How to remove the error of 404 not found. if need more code or file i will help.
i m getting error in chrome console as GET http://localhost/apluscollege/college/get_autocomplete?term=as 404 (not found) jquery.min.js
i m making a search bar using autocomplete using jQuery ana ajax
I have Created the MY_Controller in the core folder. In which I declared public $footerScript;. Here is the code of MY_Controller.
<?php
class MY_Controller extends CI_Controller
{
public $footerScript;
public $data = array();
public function __construct()
{
date_default_timezone_set( 'Asia/Karachi' );
parent::__construct();
$this->load->library(array('ion_auth','form_validation'));
$this->data['C_FullName'] = 'CodeigNiter Shop';
$this->data['C_ShortName'] = 'CI Shop';
}
}
?>
This Home Controller extends the MY_Controller. This Home Controller shows the add_items file in the views folder.
<?php
class Home extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('image_lib');
}
public function items()
{
$this->show("admin/add_items");
}
}
?>
This is the form in the add_items in which I give id to the submit button. When I click this button a jquery event will be called :
<form id="form1" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="Header Text" class="control-label" > Title </i></label>
<input type="text" placeholder="Title" id="title" name="title" class="form-control" tabindex="1">
</div>
<!-- /.form-group -->
</div>
<div class="row">
<div class="col-md-2">
<input type="submit" name="submit" id="Add" value="Add Items" class="btn btn-success">
</div>
<!-- iCheck -->
</div>
<!-- /.col (right) -->
</form>
and this code is written at the end of the add_items file. The links in the script tag are working fine but when I click the button to show alert it does not work.
<?php
//This Section footerScripts Should Execute In Footer/End of the Page.
$this->footerScript = sprintf('
<script src="'.base_url().'assets/bower_components/jquery/dist/jquery.min.js"></script>
<script src="'.base_url().'assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$("#Add").on("click", function (e) {
e.preventDefault();
var title= $("#title").val();
alert(title); return false;
}
</script>
');
?>
Since you are using jquery, don't forget to add a document ready like:
$(function() {
$("#Add").on("click", function (e) {
e.preventDefault();
var title= $("#title").val();
alert(title); return false;
}
});
now it waits to execute your function until the DOM is loaded completely. see docs
I have a CRUD with ajax working , but i want to implement a file upload to it.
Everything works fine except the image upload , the image is the only thing that is not saving on database and folder , all the other data are saving.
This is my CRUD Controller(just the add part) where I've implemented the upload code (dados)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('dados_model');
$this->load->database();
}
public function index()
{
$data['dados']=$this->dados_model->get_all_dados();
$this->load->view('dados_view',$data);
}
public function dados_add()
{
$config = array(
'upload_path' => "./assets/uploads",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
);
$this->load->library('upload',$config);
$this->upload->do_upload('userfile');
$data2=array('upload_data' => $this->upload->data());
$data = array(
'Name' => $this->input->post('Name'),
'City' => $this->input->post('City'),
'address' => $this->input->post('address'),
'lastname' => $this->input->post('lastname'),
'Image' =>$data2['upload_data']['file_name']
);
$this->dados_model->dados_add($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->dados_model->get_by_id($id);
echo json_encode($data);
}
And this is my Model, I use it to store the data on the database(dados_model)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados_model extends CI_Model
{
var $table = 'dados';
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_dados()
{
$this->db->from('dados');
$query=$this->db->get();
return $query->result();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('ID',$id);
$query = $this->db->get();
return $query->row();
}
public function dados_add($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
This is my Ajax code to save
<script type="text/javascript">
$(document).ready( function () {
$('#table_id').DataTable();
} );
var save_method; //for save method string
var table;
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal
title
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data:$('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
and this is my Modal Form to save
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">dados Form</h3>
</div>
<div class="modal-body form">
<form action="#" method="post" enctype="multipart/form-data" id="form"
class="form-horizontal">
<input type="hidden" value="" name="ID"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Name</label>
<div class="col-md-9">
<input name="Name" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input name="City" placeholder="City" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<input name="Address" placeholder=""
class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input name="lastname" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile" placeholder="" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
<input type ="submit" name="submit" value="Salvar" id="btnSave "
onclick="save()" class="btn btn-primary" />
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
</body>
</html>
First, try adding a '/' to the end of 'upload_path' => "./assets/uploads" in your code. This way you have a complete path for the image to go to.
Also, just so your aware, uploading an image like this will save the image on your server in the path provided. This means you need to store the file name in the database.So Make sure that 'Image' =>$data2['upload_data']['file_name'] actually has the correct file name so that when you query that file name from the db you can then find it at ./assets/uploads/filename on your server.
Additionally,
What do you get if you var_dump($data2['upload_data']['file_name'])?
What do you get if you var_dump($this->upload->display_errors()) after calling do_upload?
after searching some ajax codes, this is what worked for me
I changed my ajax function save to this
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
$('#form').submit(function(e)
{
$.ajax({
url : url,
type: "POST",
data: new FormData(this),
dataType: "JSON",
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
});
}
I am currently working on a program that uses php jquery and bootstrap, the update function, there is a an error so that database does not change but the script is running normally, Maybe somebody able to help me where is my mistake? thank you
My controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Subbidang extends CI_Controller {
public function index()
{
$this->load->model('model_subbidang');
$this->model_security->getsecurity();
$isi['content'] = 'Subbidang/tampilan_datasubbidang';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Sub Bidang';
$isi['data'] = $this->db->get('tsubbidang');
$this->load->view('tampilan_home',$isi);
}
public function tambah()
{
$this->load->model('model_subbidang');
$this->model_security->getsecurity();
$isi['content'] = 'Subbidang/form_tambahsubbidang';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Sub Bidang';
$this->load->view('tampilan_home',$isi);
}
public function simpan()
{
$this->model_security->getsecurity();
$this->load->model('model_subbidang');
$key['IDSubBidang'] = $this->input->post('kode');
$data['IDSubBidang'] = $this->input->post('kode');
$data['IDBidang'] = $this->input->post('bidang');
$data['NamaSubBidang'] = $this->input->post('subbidang');
$query = $this->db->get_where('tsubbidang',$key);
if ($query->num_rows()>0)
{
$this->db->update('tsubbidang',$key,$data);
//echo "Data Berhasil Diubah";
echo "Update";
}
else
{
$this->db->insert('tsubbidang',$data);
//xecho "Data Berhasil Disimpan";
echo 'Insert';
}
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
My View
<script type="text/javascript">
$(document).ready(function(){
$("#simpan").click(function(){
var string = $("#my-form").serialize();
//alert(string);
$.ajax({
type : 'POST',
url : '<?php echo site_url();?>/subbidang/simpan',
data : string,
success : function(data){
alert(data);
}
});
});
});
</script>
<form class="form-horizontal" name="my-form" id="my-form">
<div class="control-group">
<label class="control-label"bidang</label>
<div class="controls">
<select name="bidang" id="bidang">
<option value="">-Pilih-</option>
<?php
$bidang = $this->db->get('tbidang');
foreach ($bidang->result() as $row) {
?>
<option value="<?php echo $row->IDBidang;?>"><?php echo $row->Bidang;?> </option>
<?php };?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Kode Sub Bidang</label>
<div class="controls">
<input type="text" name="kode" id="kode" palceholder="kode" class="span3">
</div>
</div>
<div class="control-group">
<label class="control-label">Sub Bidang</label>
<div class="controls">
<input type="text" name="subbidang" id="subbidang" palceholder="Sub Bidang" class="span3">
</div>
</div>
<div class="controls">
<button type="button" name="simpan" id="simpan" class="btn btn-primary btn-small"> Simpan</button>
</div>
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_subbidang extends CI_model {
public function gettampildatasubbidang($key)
{
$this->db->where('IDBidang',$key);
$query = $this->db->get('tbidang');
if($query->num_rows()>0)
{
foreach ($query -> result() as $row) {
$hasil = $row->Bidang;
}
}
else
{
$hasi='';
}
return $hasil;
}
public function getlistsubbidang()
{
return $this->db->get('tbidang');
}
public function getdata($key)
{
$this->db->where('IDBidang',$key);
$hasil = $this->db->get('tBidang');
return $hasil;
}
public function getupdate($key,$data)
{
$this->db->where('IDBidang',$key);
$this->db->update('tBidang',$data);
}
public function getinsert($key,$data)
{
$this->db->insert('tBidang',$data);
}A
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
The echo work fine but the database doesnt change. The Insert function also work fine
You need to pass right data to update function
change
$this->db->update('tsubbidang',$key,$data);
to
$this->db->where('IDBidang', $key);
$this->db->update('tsubbidang',$data);
and Everything will be fine.
and one more thing is that you must do functionality related to database in your model not directly in controller, it is not according to the MVC structure. it destort it. and if you done everything seperetly then it is easy to understand and clear to everyone who code after you on the same.