$this -> cart->insert(); not working on live while working on localhost - codeigniter-2

Hi i am having problem on my live server when i am checking the add to cart builtin function of CI. But its working fine on my localhost.
Here is my Model code where i am saving the cart
$id = $this->input->post('product_id'); // Assign posted product_id to $id
$qty = 1;// Assign posted quantity to $cty
$this->db->from($this->table_name);
$this->db->join($this->desc_table_name, "$this->desc_table_name.products_id = $this->table_name.id");
$this -> db -> where('id', $id); // Select where id matches the posted id$this->db->from($this->table_name);
$this -> db -> limit(1);
$query = $this->db->get(); // Select the products where a match is found and limit the query by 1
// Check if a row has been found
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => "$row->title",
'options' => array('description' => $row->description,'short_desc'=> $row->short_desc,'image'=>$row->image,),
);
//print_r($data);
$res = $this -> cart -> insert($data);
return TRUE;
}
// Nothing found! Return FALSE!
}else{
return FALSE;
}`
and my ajax function is like this
var link = window.location.protocol + "//" + window.location.host + "/youth_fashion/";
$(".add_item").click(function() {
// Get the product ID and the quantity
var id = $(this).attr('id');
$.post(link + "front/cart_controller/add_cart_item1", { product_id: id, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "front/cart_controller/show_cart", function(cart){
$("#cart_content").html(cart);
var x = location.href;
window.location.href= x;
});
}else{
alert("Product does not exist");
}
});
return false;
});`
I am using CI 2.0. Thank you in advance

The issue is resolved.
The issue is in session file (config.php). I am using the library of cart but it is not storing the data into table.
$config['sess_use_database'] = TRUE; i turned true and its storing and working for me

Related

CakePHP-2.4 : subcategories according to categories by ajax

I am trying to get subcategories according to categories by ajax.So I have sent data in controller by ajax get method like bellow code in add.ctp
$('document').ready(function(){
$( "#division" ).change(function() {
var value=$('#division').val();
$.get("<?php echo Router::url(array('controller'=>'userStoreSelections','action'=>'add'));?>",{list:value},function(data){
$('.districts').html(data);
alert(data);
});
});
});
In controller in find methods when I am writing bellow code It's working fine.
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>3)
));
But when I give the value that I have sent by ajax it's not working.I have written like this
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
It showing the query like this
SELECT `MadDistricts`.`id`, `MadDistricts`.`name` FROM `store`.`mad_districts` AS `MadDistricts` WHERE `mad_divisions_id` IS NULL
After select categories nothing change in query.I have tested ajax code there is no problem to send value.
For more specific this is the add action code
public function add() {
if(isset($this->request->query['list'])){
$search = $this->request->query['list'];
echo $search;
}
else{
$search = '';
}
if ($this->request->is('post')) {
$this->UserStoreSelection->create();
if ($this->UserStoreSelection->save($this->request->data)) {
$this->Session->setFlash(__('The user store selection has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user store selection could not be saved. Please, try again.'));
}
}
$madDivisions = $this->UserStoreSelection->MadDivisions->find('list');
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
$madAreas = $this->UserStoreSelection->MadAreas->find('list');
$users = $this->UserStoreSelection->Users->find('list',array('fields' => array('id','username')));
$madStores = $this->UserStoreSelection->MadStores->find('list',array('fields' => array('id','store_name')));
$this->set(compact('madDivisions', 'madDistricts', 'madAreas', 'users','madStores'));
}
You need to change your add.ctp file code like as :
$('document').ready(function () {
$("#division").change(function () {
var value = $(this).val();
$.ajax({
url: '<?php echo Router::url(' / ',true);?>userStoreSelections/subcategories',
type: "POST",
dataType: 'json',
data: 'category=' + id,
success: function (res) {
var html = '<option>Sub Category</option>';
if (res.flage == true) {
html = res.data;
}
$('.districts').html(html);
}
});
});
});
Than create a function in your userStoreSelections for get sub categories as
public function subcategories() {
$response = array('flage' => false);
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list', array(
'conditions' => array('mad_divisions_id' => $this->request->data['category'])
));
$options = "<option>Subcategories</option>";
if ($states) {
$response['flage'] = true;
foreach ($madDistricts as $id => $name) {
$options .= "<option value='" . $id . "'>" . $name . "</option>";
}
$response['data'] = $options;
}
echo json_encode($response);
exit;
}

Calling another view page through ajax in codeigniter view page

I have a view page, from that page I want to call another view page through ajax. This is the code i'm using, but I'm not getting the response.
This is my code
var dataString = 'product_name='+product_name+'&qty='+qty+'&cost='+price;
$.ajax({
url:'myCart.php',
type:"get",
data: dataString,
success:function(data)
{
alert(data);
}
});
This is my myCart.php. In this I have get all the values passed from that page though url.
<?php
session_start();
if (!isset($_SESSION['SHOPPING_CART'])){
$_SESSION['SHOPPING_CART'] = array();
}
$session = $_SESSION['SHOPPING_CART'];
function inMultiArray($name,$session) {
if (array_key_exists($name,$session) or in_array($name,$session)) {
return true;
} else {
$return = false;
foreach (array_values($session) as $value) {
if (is_array($value) and !$return) {
$return = inMultiArray($name,$value);
}
}
return $return;
}
}
$name = 'Test' ;
$result = inMultiArray($name,$session);
if($result){
echo 'Yes';
}
// else, add the item to the array
else{
$ITEM = array(
//Item name
'product_name' => $_GET['product_name'],
//Item Price
'cost' => $_GET['cost'],
//Qty wanted of item
'qty' => $_GET['qty']
);
//Add this item to the shopping cart
$_SESSION['SHOPPING_CART'][] = $ITEM;
$total=0;
foreach ($_SESSION['SHOPPING_CART'] as $itemNumber => $items) {
$total = $total + $items['cost'];
// print $items['cost'];
// print $items['qty'];
}
echo $total;
}
?>
As I now clearly understood your question, it is wrong to call a view. Instead call your controller which will call the model to perform some operation and return the result you want

How to return the current inserted row data in Laravel?

I have inserted a row in db using laravel eloquent method. See the code below,
public function store() {
$language = new languages;
$language -> languages = Input::get('languages');
$language -> created_by = Auth::user()->id;
$language -> updated_by = Auth::user()->id;
if( $language -> save() ) {
$returnData = languages::where("id","=",$language -> id) -> get();
$data = array ("message" => 'Language added successfully',"data" => $returnData );
$response = Response::json($data,200);
return $response;
}
}
I want the last inserted row from the table, but my response contains empty data. Please guide the right method of getting the data?
Almost there: you would need to call first() to get just one row. But, since you're using eloquent, you can call the find() method:
public function store() {
$language = new languages;
$language->languages = Input::get('languages');
$language->created_by = Auth::user()->id;
$language->updated_by = Auth::user()->id;
if($language->save()) {
$returnData = $language->find($language->id);
$data = array ("message" => 'Language added successfully',"data" => $returnData );
$response = Response::json($data,200);
return $response;
}
}

links in pagination in codeigniter

in my view page,in the 1st form i have 2 select drop down...in the 1st drop down i am populating the value default from the controller...when u onchange the value in the 1st drop down,the selected value is passed to controller via javascript..in the controller,i get that 1st drop down value and load model and get value from model for the 2nd drop down and post it to view page...when u select the 2nd drop down value and click submit,the both drop down values are posted to controller after form validation and load model and get user information from the database and post it back again to view page ...this is the scenario for my view page..so,u can change the above both select drop down to get informations in the 2nd form in the same view page..now when i did pagination for my 2nd form user information,i am getting the links and data perfectly according to the limits and offsets..but,i am unable to retrieve the information when i click 2nd,3rd,4th..and rest on links while the informations are being posted from controller..so what can i do now?,,here is my code after i get both drop down values in the controller..
in my controller..
public function get_form_dept()
{
$this->load->helper(array('form', 'url'));
$this->load->library("pagination");
$this->load->library('form_validation');
$this->form_validation->set_rules('formation','Formation','required|required');
if($this->form_validation->run()== false) {
$this->viewstudent();
} else {
$config['base_url'] = base_url() . 'Incite/get_form_dept';
if($this->input->post('formation') == 1 && $this->input->post('department') == 1){
$config['total_rows'] = $this->db->get('user')->num_rows();
} else {
//$this->db->select('list_formation');
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
// echo $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
echo $get_formation ."<br>";
}
$query1 = $this->db->get_where('department',array('id' => $this->input->post('department')));
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
echo $get_dept . "<br>";
}
//$array = array('formation' => $get_formation, 'department' => $get_dept);
//$config['total_rows']=$this->db->get('user',$array)->num_rows();
$query = $this->db->query("SELECT * FROM user where formation='$get_formation' and department='$get_dept'");
echo "SELECT * FROM user where formation='$get_formation' and department='$get_dept'" . "<br>";
$config['total_rows']=$query->num_rows();
//echo $row ."<br>";
//echo $row=$this->db->get('user',$array)->num_rows();
}
$config['per_page'] = 5;
//$config['uri_segment'] = 3;
//$choice = $config['total_rows'] / $config['per_page'];
// $config['num_links'] = round($choice);
$config['num_links'] = 2;
//$config['use_page_numbers'] = TRUE;
$config['suffix']= '?' . http_build_query($_GET, '', "&");
$this->pagination->initialize($config);
if($this->input->post('formation')== 1 && $this->input->post('department') == 1) {
// $this->db->limit($limit, $start);
$query_result = $this->db->get('user',$config['per_page'], $this->uri->segment(3));
$data['result']= $query_result->result();
} else {
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
}
$this->db->where('id', $this->input->post('department'));
$query1 = $this->db->get('department');
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
//echo $get_dept;
}
$array = array('formation' => $get_formation, 'department' => $get_dept);
//$this->db->limit($limit, $start);
//$query = $this->db->get_where('user',$array);
$query_result=$this->db->get_where('user',$array,$config['per_page'], $this->uri->segment(3));
$data['result'] = $query_result->result();
}
$this->load->model('model_select_formation');
$data['formation'] = $this->model_select_formation->modelselectformation();
// query to fetch department
$data['dept']=$this->model_select_formation->get_department($data['formation_id']);
$data['formationid'] = $this->input->post('formation');
$data['departmentid'] = $this->input->post('department');
$this->load->view('viewstudent',$data);
}
}

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Resources