Calling another view page through ajax in codeigniter view page - codeigniter

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

Related

Getting data by ajax in Codeigniter

I am adding record to database by ajax in CI , so i was trying to return the id of the new record but it's not working , the record has been added but no id is returned .(in ajax code am trying to alert the new record id but it's alerting undefined)
Below is the ajax code:
$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
success:function(data){
alert(data[0].id);
$('#register_form')[0].reset();
} });
This is the controller,
notice that am returning id from create_product method and put it in get_by_id method, and then return result
if($id=$this->Products_model->create_product($data)){
$result = $this->Products_model->get_product_by_id($id);
return $result;
}
This is my model methods
public function create_product($data){
$query = $this->db->insert('products',$data);
if($query){
$id = $this->db->insert_id();
return $id;
}else{
return false;
}
}
//////////get_by_id_method
public function get_product_by_id($id){
$this->db->where($id,'id');
$query = $this->db->get('products');
if($query){
return $query->result();
}
}
Hope this will help You :
Your ajax should be like this :
$.ajax({
type:'post',
url: baseURL + "admin/Products/add_product",
data:postData,
success:function(data)
{
var response = JSON.parse(data);
alert(response.id);
$('#register_form')[0].reset();
}
});
Your controller should be like this :
$id = $this->Products_model->create_product($data);
if($id)
{
$result = $this->Products_model->get_product_by_id($id);
echo json_encode($result);
exit;
}
Your model method get_product_by_id should be like this :
public function get_product_by_id($id)
{
$this->db->where($id,'id');
$query = $this->db->get('products');
if($query->num_rows() > 0)
{
return $query->row();
}
}
You may need to echo a JSON with a proper Content-type in your Controller:
$result = [];
$id = $this->Products_model->create_product($data);
if ($id) {
$result = $this->Products_model->get_product_by_id($id);
}
header("Content-type: application/json");
echo json_encode($result);
So that the response can be an empty object or the query result.

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

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

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

How to add "route action" into response content with Ajax Zend2?

I am new to zend framework and trying to test my first app about ajax with zend2.
I want to show a link when I return a response from my controller ! I try anyways but cann't view !
I try this:
Here my HTML:
<select id="my_list" onChange="showlist(this.value);" name="my_list">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here my Ajax Script:
function showlist(id){
$.post("user/list", {
content: id
},function(data){
if(data.response == true){
$('#div_show').html(data['html']);
}
}, 'json');
}
And my controller:
public function listAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost()) {
$post_data = $request->getPost();
$id = $post_data['content'];
if($id){
/* $html = $group; It's Ok ! I can view group value !*/
$html = 'Test !';
$response->setContent(\Zend\Json\Json::encode(array('response' => true,'html'=>$html)));
}
else{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
I can view group value when I select listbox, but I cann't see the link when I want to view its detail !
It's my first question ! Please help me.
var url = '<?php echo $this->url('user', array('action' => 'list')); ?>';
function showlist(id){
$.post(url, {
content: id
},function(data){
if(data.response == true){
$('#div_show').html(data['html']);
}
}, 'json');
}

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

Resources