Getting data by ajax in Codeigniter - ajax

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.

Related

Set bootstrap selected option with ajax value

I try to display data on the bootstrap select option with ajax, but after I run the data do not want to appear what is wrong?
function get_value() {
$id = 5;
$q = $this->db->select('*')
->from('tbl_v')
->where('id', $id)
->order_by('id', 'ASC')
->get();
$result = $q->result();
echo json_encode($result );
}
$(".change").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
url: base_url+"get_value",
type:"POST",
dataType: 'json',
cache: false,
data:{id:value},
success: function(respond){
$(".get-change").html(respond).selectpicker('refresh');
}
})
}
});
Try this...
function OnChangeValue()
{
var pdrp = document.getElementById("yourControlIDHere");
getvalue= pdrp.options[pdrp.selectedIndex].value;
alert(getvalue);
}
The Control
<select id="yourControlIDHere" onchange="OnChangeValue(this)" name="companyname" style="width:100%">
Jquery Code
$(".change").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
url: base_url+"get_value",
type:"POST",
cache: false,
data:{id:value},
success: function(respond){
$(".get-change").html(respond);
}
})
}
});
Modal Code:
function get_records() {
$id = 5;
$q = $this->db->select('*')
->from('tbl_v')
->where('id', $id)
->order_by('id', 'ASC')
->get();
$result = $q->result();
}
Controller Code:
function get_value(){
$ido = $this->input->post('id');
$data = $this->your-model-name->get_records($ido);
$option = "";
foreach($data as $row){
$option .= "<option value='".$value['ID']."'>".$row[0]->name."</option>";
}
echo $option;
}
You need not have to use JSON encoding. Records will be directly appended to the select box. Hope this can help you.

Codeigniter: Display an image stored in DB

How do I get an image stored in a field of my database, and put it into a variable for using it in an email message like a signature?
Here is my code:
//Model user_model
function getImage(){
$this->db->select("image");
$this->db->where("$id", user_id);
$query = $this->db->get("users");
if($query->num_rows()>0){
return result();
}else{
return false;
}
}
//Controller user_controller
function image(){
this->load->model("user_model");
$id = $this->session->userdata('id');
$image = $this->user_model->getImage($id);
echo $image;
}
Here is a example
Model user_model
// Pass the id function
function getImage($id){
$this->db->where($id, 'user_id');
$query = $this->db->get("users");
if($query->num_rows()>0){
return $query->row_array();
}else{
return false;
}
}
Controller user_controller
function image(){
$this->load->model("user_model");
$somedata = $this->user_model->getImage($this->session->userdata('id'));
$data['image'] = $somedata['image'];
$this->load->view('someview', $data);
}
On view
<?php echo $image;?>

How to send value as parameter to model in codeigniter to get data?

I am new in codeigniter.
Currently working in e-commerce site I want to send the category_id as parameter to bring product data.
I want to know the steps to detail and Thanks
This is my model:
( function get_category(){ $query = $this->db->query("SELECT a.category_id,a.category_name from ci_intro.categories a order by a.category_id"); return $query->result(); } function get_product($id){ $q = $this->db->query('select * from products where category_id = $id'); if($q->num_rows() > 0){ foreach ($q->result() as $row) { $data[] = $row; } return $data; } } )
and this is my controller
( public function services() { $this->load->model("get_db"); $data['results'] = $this->get_db->get_category(); $id=$this->input->post('id'); $data['cat_id'] = $this->get_db->get_product($id); $this->load->view("view_header"); $this->load->view("view_nav"); $this->load->view("content_portfolio",$data); $this->load->view("site_footer"); } )
You get category_id in model as $_GET['category_id'] or $_REQUEST['category_id'] in model also .
class Pages extends CI_Controller {
public function view($page = 'home')
{
$this->load->model('services_model');
$id=$this->input->post('id');
$data['records']= $this->services_model->getData($id);
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
this is your controller example
and this is mlodel for you
class Services_model extends CI_Model {
function getUser($id) {
$q = $this->db->query('YOUR QUERY HERE');
if($q->num_rows() > 0){
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
}
you can see various crud example and their website for further details
Your category should be the drop downlist. on change event the id will be pass through ajax like below
$(document).ready(function() {
$("#category").change(function(){
/*dropdown post */
$.ajax({
url:"<?php echo base_url(); ?>index.php/services/getproducts",
data: {catid: $(this).val()},
type: "POST",
success: function(data){
$("#product").html(data);
}
});
});
}
get prducts will be the function in services controller class you can get the category id using the
$this->input->post('catid');

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

Resources