Unable to populate dropdown with ajax in codeigniter - ajax

http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
if ($sub_cat === FALSE)
{
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category);
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// home Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//state model
class State_model extends CI_Model {
public function __construct() {
$this -> load -> database();
}
function get_states() {
$query = $this->db->order_by('state', 'ASC')->get('state');
return $query->result_array();
}
}
//city model
class City_model extends CI_Model {
public function __construct() {
$this -> load -> database();
//$this->output->enable_profiler(TRUE);
}
function get_cities($state){
if($state != NULL){
$this->db->where('state_id', $state);
$query = $this->db->get('city');
$cities = array();
$html = '';
if($query->result())
{
$html .= '<select id="city_id" name="city_id">';
$html .= '<option value="">-- Select City --</option>';
foreach ($query->result() as $city)
{
$html .= '<option value="'.$city->id .'">'.$city->city.'</option>';
}
$html .= '</select>';
return $html;
}
else
{
return FALSE;
}
}
else
{
$html = '<option value="">--Select City--</option>';
return $html;
}
}
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.

try this in controller
public function get_cities()
{
$state_id = $this->input->post('state');
$cities = $this->city_model->get_cities($state_id);
echo '<option value="">-- Select City --</option>';
foreach($cities as $city){
echo '<option value="'.$city->id .'">'.$city->city.'</option>';
}
}
in model
function get_cities($state){
$this->db->where('state_id', $state);
$query = $this->db->get('city');
return $query->result();
}
in ajax
success: function(data) { $('#city_id').html(data)}

Related

Applying Ajax (Codeigniter)

I have this script and i need to apply ajax on it. Can someone give me an idea on how to apply ajax on these codes? I need to pass those variables on the controller. It works just fine but i need to alter it into ajax. It's just, im having a hard time figuring it out, how i can reassemble to ajax. Thank you ♥
function saveData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.post('<?php echo site_url("welcome/add") ?>', {id:id, nm:name, em:slug, hp:books, ad:address}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function editData(id, nm, em, hp, ad) {
$('#id').val(id)
$('#nm').val(nm)
$('#em').val(em)
$('#hp').val(hp)
$('#ad').val(ad)
$('#id').prop("readonly",true);
$('#save').prop("disabled",true);
$('#update').prop("disabled",false);
}
function updateData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.post('<?php echo site_url("welcome/update") ?>', {id:id, nm:name, em:slug, hp:books, ad:address}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
$('#id').prop("readonly",false);
$('#save').prop("disabled",false);
$('#update').prop("disabled",true);
})
}
function deleteData(id){
$.post('<?php echo site_url("welcome/remove") ?>', {id:id}, function(data){
viewData()
})
}
function removeConfirm(id){
var con = confirm('Are you sure to delete this data? HUHHHHH?!');
if(con=='1'){
deleteData(id);
}
}
$(".clicker").on("click", function(){
$(this).siblings().slideToggle('normal');
})
$(function() {
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
});
});
</script>
Controller:
<?php
header('Access-Control-Allow-Origin: *');
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('crud_model');
}
public function index()
{
$data['books'] = $this->crud_model->getBooks();
$this->load->view('header');
$this->load->view('welcome_message',$data);
$this->load->view('footer');
}
public function view()
{
$data['books'] = $this->crud_model->getBooks();
$data['crud']=$this->crud_model->getView();
$this->load->view('view_data',$data);
}
public function add()
{
$data = array(
'id' => $this->input->post('id'),
'title' => $this->input->post('nm'),
'slug' => $this->input->post('em'),
'book_id'=>$this->input->post('hp'),
);
// $insert = $this->crud_model->postNew($data);
$data2 = array(
'book_id'=>$this->input->post('hp'),
'faqs_id' =>$this->crud_model->postNew($data),
);
$insert1 = $this->crud_model->postNewBridge($data2);
}
public function update()
{
$data = array(
'title' => $this->input->post('nm'),
'slug' => $this->input->post('em'),
'book_id'=>$this->input->post('hp'),
);
$this->crud_model->postUpdate(array('id' => $this->input->post('id')), $data);
}
public function remove()
{
$id = $this->input->post('id');
$this->crud_model->getDelete($id);
}
}
Model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Crud_model extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getBooks()
{
$this->db->select('*');
$this->db->from('book');
$query=$this->db->get();
return $query->result();
}
public function getView()
{
$this->db->select('*');
$this->db->from('book');
$this->db->join('faqs', 'book.id = faqs.book_id','inner');
$query=$this->db->get();
return $query->result();
}
public function postNew($data)
{
$this->db->insert('faqs', $data);
return $this->db->insert_id();
}
public function postNewBridge($data2)
{
$this->db->insert('book_faqs', $data2);
return $this->db->insert_id();
}
public function postUpdate($where, $data)
{
$this->db->update('faqs', $data, $where);
return $this->db->affected_rows();
}
public function getDelete($id)
{
$this->db->where('id', $id);
$this->db->delete('faqs');
}
}
Try this, Here I m giving you only saveData() in ajax
function saveData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.ajax({
beforeSend: function () {
//do something before ajax call
},
complete: function () {
//do something after ajax call done
},
type: "POST",
url: '<?php echo site_url('your_contoller/your_function'); ?>/',
data: ({id: id, nm: nm, em: em,hp: hp,ad: ad}),
success: function (data) {
setTimeout(function () {
//do something after a second
}, 1000);
}, error: function (data) {
}
});
}
i hope this helps
You simply need get() with your current code. Just use this function to call page and load it in a container with a class result with ajax.
$('#buttonId').click(function() {
$.get( "controller/function", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
});

codeigniter foreach not displaying all records in table

Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached

Best Practice: Models and Controllers

I would like to get your MVC experience on the following:
I have a table where I say which user_id is in which group_id and a second table where I say which user_id has which user_name.
Now I want a function to which I pass a group_id and it gives me all user_names in the group.
The question is, what does the Controller do and what the Model:
Controller calls a Model (get_user_ids_from_group) that returns the user ids and then the controler calls different model (get_user_name_by_id) to return the usernames.
A controller calls a Model (`get_user_names_from_group) and the model internally gets first the user ids and then the user names.
I understand that the first way is more MVC strict. But how strict would you be in a case like this? Right now I am always being very strict.
As a result my model functions have always just two lines (query and return) and my controller are bigger. So to make controller and model size more equal the second option would be possible.
Actually, it has nothing to do with MVC, as CodeIgniter doesn't implement MVC, but a sort of MVP.
However, if you're using RDBMS such as MySQL, you could JOIN these two table (within the Model) and fetch the result (within the Controller) as I suggested in a similar topic on SO.
application/models/user.php
class User extends CI_Model
{
public function get_users_by_group($group_id)
{
$this->db->select('*')->from('groups');
// While group_id and user_id have a N:1 relation
$this->db->where('group_id', $group_id);
$this->db->join('users', 'users.user_id = groups.user_id');
$query=$this->db->get();
return $query->result_array();
}
}
Then fetch and pass the result within the Controller:
application/controllers/users.php
class Users extends CI_Controller
{
public function view($group_id)
{
$this->load->model('user');
// Fetch the result from the database
$data['users'] = $this->user->get_users_by_group($group_id);
// Pass the result to the view
$this->load->view('users_view', $data);
}
}
In MVC model should not be only use for storing and getting the data but also it should contain the business logic.
Controller - Should take input communicate with model and view
Model - Should contain business logic and data store
View - Only for Output
So its like Input -> Process -> Output
Also its depend on you where to put what and you should have a balance code on controller and model, Not write everything in controller or in model
In you case I think you should uses get_user_names_from_group and just pass the group name and make a join query between two table. And when you define your function in the model its give you the option to reuse the function again in case you need same thing on next controller.
Common model example:
<?php
class Common_model extends CI_Model {
function get_entry_by_data($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '') {
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function get_entry_by_data_in($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '',$in_column='',$in_data=''){
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
if (!empty($in_data) and !empty($in_column)) {
$this->db->where_in($in_column,$in_data);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function getAllRecords($table, $orderby_field = '', $orderby_val = '', $where_field = '', $where_val = '', $select = '', $limit = '', $limit_val = '') {
if (!empty($limit)) {
$offset = (empty($limit_val)) ? '0' : $limit_val;
$this->db->limit($limit, $offset);
}
if (!empty($select)) {
$this->db->select($select);
}
if ($orderby_field)
$this->db->order_by($orderby_field, $orderby_val);
if ($where_field)
$this->db->where($where_field, $where_val);
$query = $this->db->get($table);
//return $query->num_rows;
//echo $this->db->last_query();
if ($query->num_rows > 0) {
return $query->result_array();
}
}
function alldata($table) {
$query = $this->db->get($table);
return $query->result_array();
}
function alldata_count($table, $where) {
$query = $this->db->get_where($table, $where);
return $query->num_rows();
}
function insert_entry($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
function update_entry($table_name, $data, $where) {
return $this->db->update($table_name, $data, $where);
}
public function get_data_by_join($table, $table2, $where, $table1_column, $table2_column, $limit = '', $order_column = '', $order_by = 'DESC', $select_columns = '', $is_single_record = false, $group_by = '', $join_by = '', $offset = '') {
if (!empty($select_columns)) {
$this->db->select($select_columns);
} else {
$this->db->select('*');
}
$this->db->from($table);
$this->db->join($table2, $table . '.' . $table1_column . '=' . $table2 . '.' . $table2_column, $join_by);
$this->db->where($where);
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
} else {
$this->db->limit($limit);
}
}
if (!empty($order_column)) {
$this->db->order_by($order_column, $order_by);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
if ($is_single_record) {
$rs = $query->result_array();
return $rs[0];
} else {
return $query->result_array();
}
} else {
return false;
}
}
function DeleteRecord($table_name, $where) {
return $this->db->delete($table_name, $where);
}
function managerecord() {
$count = 1;
$where = array('channel_id' => 8,
'field_id_12 !=' => '');
$this->db->where($where);
$query = $this->db->get('channel_data');
$data = $query->result_array();
foreach ($data as $value) {
$id = $value['field_id_12'];
$update = array('telephone' => $value['field_id_53'],
'about' => $value['field_id_54'],
'license' => $value['field_id_18'],
'broker' => $value['field_id_19'],
'preferred' => 'yes');
$this->db->update('members', $update, array('member_id' => $id));
}
echo "done1";
}
public function get_content_landing_page($table = false, $field = false, $id = false, $id_name = false) {
$this->db->select($field);
$this->db->from($table);
$this->db->where($id_name, $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_field_landing_page($id = false,$fields=false) {
$this->db->select($fields);
$this->db->from('terratino_form_fields_master');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
?>

how to solve "Undefined variable:id"

function empAll()
{
$this->db->where('id',$id);
$q = $this->db->get('employee');
if($q->num_rows()>0)
{
foreach($q->result() as $rows)
{
$data[]=$rows;
}
return $data;
}
Generally we pass id in the Url:
Base_url()/index.php/empAll/25. Now codeigniter automatecaly pass the $id = 25 in the method. In case id not received it will assign the id by 0 and then you will not get this error.
function empAll()
{
$q = $this->db->where('id',$this->input->post('id'))
->get('employee');
if($q->num_rows()>0)
{
foreach($q->result() as $rows)
{
$data[]=$rows;
}
}
return $data;
}

codeinighter where field = data from form

I'm trying to match up suppliers from a postcode search:
Model code:
function get_suppliers(){
$this->db->from('suppliers');
$this->db->where('postcode', $data);
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
Controller code:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
echo("postcode entered");
$data['rows'] = $this->site_model->get_suppliers($data);
print_r($data);
}
}
Obviously ignore the printers and echo thats just me bring to see whats going on I'm pretty sure i need to just change the $data in model to something just not sure what(tried heaps of things)
Model:
function get_suppliers($postcode = '*') // <-- Capture the postcode
{
$this->db->from('suppliers');
$this->db->where('postcode', $postcode); // <-- pass it in here
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Controller:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
$data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode
echo("postcode entered: " . $data['postcode'] . "<pre>");
print_r($data);
}
}
In your model:
function get_suppliers($data = ''){
i.e.: You haven't included $data as the argument

Resources