Submit data to database using Ajax and jQuery - codeigniter submission - php

I am creating a codeigniter project where i get number of items from my database and each item has a submit button clicking on which the data are stored into the database using AJAX and jQuery.
Now, the problem is that when i submit any item only the data of 1st form is sent to the method that inserts data to the database please provide some solution regarding the same. my code is as under:
Model:
<?php
class Products_model extends CI_Model{
function get_all(){
$results = $this->db->get('tblUtensils')->result();
return $results;
}
function get($id){
$results = $this->db->get_where('tblUtensils', array('pkItemID' => $id))->result();
$result = $results[0];
return $result;
}
}
?>
View:
<body>
<div id="products">
<?php foreach ($products as $product):
$id=$product->pkItemID;
?>
<li>
<?php echo form_open('shop/add', 'id="form"'); ?>
<div><?php echo form_input('name_' . $id, $product->fldName , 'id='.'"'.'name_' . $id.'"');?></div>
<div><?php echo form_input('desc_' . $id, $product->fldDescription , 'id='.'"'.'desc_' . $id.'"');?></div>
<div><?php echo form_input('rate_' . $id, $product->fldRateMB1 , 'id='.'"'.'rate_' . $id.'"');?></div>
<div><?php echo form_input('Qty_' . $id, 0, 'id='.'"'.'qty_' . $id.'"');?></div>
<?php echo form_hidden('id', $product->pkItemID, 'id="ID"'); ?>
<?php echo form_submit('action', 'Add','id="submit"');?>
<?php echo form_close(); ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<!-- try 2 -->
<script type = "text/javascript">
$(function(){
$('form').submit(function(e){
e.preventDefault(); // <------this will restrict the page refresh
var form_data = {
id: $('#id').val(),
name: $('#name_' + id).val(),
rate: $('#rate_' + id).val(),
qty: $('#qty_' + id).val()
};
$.ajax({
url: "<?php echo site_url('shop/add'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert("success");
}
});
return false;
});
});
</script>
</body>
</html>
Controller:
<?php
class Shop extends CI_Controller{
function index(){
$this->load->model('Products_model');
$data['products'] = $this->Products_model->get_all();
$this->load->view('products',$data);
}
function add(){
//$this->load->model('Products_model');
//$product = $this->Products_model->get($this->input->post('id'));
$insert = array(
'id' => $this->input->post('id'),//<-- also not able to get this id from ajax post request
'qty' => $this->input->post('qty'),
'price' => $this->input->post('rate'),
'name' => $this->input->post('name'),
);
$this->cart->insert($insert);//<--insert item into cart
$query// to insert into database
//redirect('shop');
}
}
?>
Many questions have been posted before regarding codeigniter and ajax but none did provide solution to my problem so i am posting this question, appreciate your help.

Change
<?php echo form_open('shop/add', 'id="form"'); ?>
To
<?php echo form_open('shop/add', 'id="form_' . $id . '"'); ?>
This gives different id's for each forms.

I tried many ways of dealing with this and finally the thing that worked for me was as under:
<script type = "text/javascript">
$('.submit').click(function(){
var id = (this.id);
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
rate: $('#rate_' + id).val(),
qty: $('#qty_' + id).val()
};
$.ajax({
url: "<?php echo site_url('shop/add'); ?>",//repair
type: 'POST',
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! or any stupid msg");
}
});
return false;
});
</script>

Related

codeigniter ajax not setting sessions asynchronously

I am new to codeigniter ajax and i have a problem with sessions.My sessions are not being set and unset
asynchronously and i have to refresh the page just to see the changes.
view/header:
<?php
if(!empty($product)){
$pid=$product[0]['product_id'];
}
?>
<script>
$(document).ready(function(){
if($('.add_to_basket').find('img')){
$('.add_to_basket').click(function(){
var message=$('#badgemessage');
$('#msgcart').append(message);
message.show('slow');
var trigger=$(this);
var param=trigger.attr("rel");
var item=param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url()."cart_c/myfunk/".$pid?>',
data: { id: item[0], job: item[1] },
dataType:'json',
success: function(data) {
console.log(data);
},
error:function(){
alert("error");
}
});
return false;
});
}
});
</script>
model/basket_model:
<?php
class Basket_model extends CI_Model{
function activeButton($sess_id){
$e=$this->session->userdata('basket');
if(isset($e[$sess_id])){
$id=0;
$label="<img src='".base_url()."images/remove.png' />";
}else{
$id=1;
$label="<img src='".base_url()."images/add.png' />";
}
$out="<a href='#' class='add_to_basket' rel='".$sess_id."_".$id."'>".$label."</a>";
return $out;
}
function setItem($pide,$qty=1){
$e=$this->session->userdata('basket');
if(isset($e)){
$e[$pide]['qty']=$qty;
$this->session->set_userdata('basket',$e);
}else{
$arr=array($pide=>array('qty'=>$qty));
$this->session->set_userdata('basket',$arr);
}
}
function removeItem($pide,$qty=null){
$e= $this->session->userdata('basket');
if($qty != null && $qty < $e[$pide]['qty']){
$e[$pide]['qty']=($e[$pide]['qty']-$qty);
$this->session->set_userdata('basket',$e);
}else{
$e[$pide]=null;
unset($e[$pide]);
$this->session->set_userdata('basket',$e);
}
}
}
?>
controller/cart_c:
<?php
class Cart_c extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function myfunk($id){
if(isset($_POST['id']) && isset($_POST['job']))
$out=array();
$pid=$_POST['id'];
$job=$_POST['job'];
if(!empty($id)){
switch($job){
case 0:
$this->basket_model->removeItem($pid);
$out['job']=1;
break;
case 1:
$this->basket_model->setItem($pid);
$out['job']=0;
break;
}
echo json_encode($out);
}
}
}
?>
controller/products:
<?php
class Products extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function product($id){
$kitties['cats']=$this->catalogue_model->get_categories();
$data['product']=$this->products_model->get_product($id);
$data['active_button']=$this->basket_model->activeButton($id);
$this->load->view('header',$data);
$this->load->view('sidebar',$kitties);
$this->load->view('product',$data);
$this->load->view('footer');
}
}
?>
view/product:
<div class="contentwrap">
<div id="content_area">
<?php
$e=$this->session->userdata('basket');
print_r($e);
if(!empty($product)){
foreach($product as $p){
?>
<h1><?=$p['product_name']?></h1>
<div id="product_image">
<img src="<?=base_url()?>/images/<?=$p['image']?>" width="400" height="300" />
</div>
<div id="product_desc">
<?=$p['description']?>
<br><br>
<?=$active_button?>
</div>
<?php
}
}else{
echo "Product unavailable";
}?>
</div>
</div>
The problem is my $active_button in the product view is not changing asynchronously but the sessions are being set and unset
i can see items being pushed into and out of the session array when i refresh the page.When i hit the button my chrome console displays: object{job:0}
ok after looking and studying youre code. you can implement what you want by retrieving the button again when making your AJAX call. The way to retrieve it is by calling that model again, then using jquery to replace the current button. Try the following:
Controller - Cart_c
function myfunk($id) {
if (isset($_POST['id']) && isset($_POST['job'])) {
$out = array();
$pid = $_POST['id'];
$job = $_POST['job'];
if (!empty($id)) {
switch ($job) {
case 0:
$this->basket_model->removeItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
case 1:
$this->basket_model->setItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
}
echo json_encode($out);
}
}
}
JS in header view:
<script>
$(document).ready(function() {
function add_to_basket($this) {
var param = $this.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url() . "cart_c/myfunk/" . $pid ?>',
data: {id: item[0], job: item[1]},
dataType: 'json',
success: function(data) {
console.log(data);
$this.replaceWith(data.active_button);
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
},
error: function() {
alert("error");
}
});
return false;
}
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
});
</script>
Ok I think perhaps we should start by discussing the proper flow of your app. Assuming that your URL looks something like this Products/product/10 and you intially load the page, your function runs providing you with right button and products as expected.. Lets say in this case product 10 does not exist in the session/cart so you see the ADD image button come up.. All good.. Now, when you click add, and from what you are saying, it adds the product to the session/cart, and you get a return JSON of ‘job:0’. So far it works as expected from the code I am seeing. A return of job:0 means that you ran the setItem function. Now the problem you are saying is that the view “is not changing asynchronously”. By this, do you mean that you expect the page to reload and run the function again so that the image can now say “remove”?

Codeigniter Ajax - Help Needed with Error

Hey I'm new to CI and have scoured the internet for a tutorial that will work but for some reason it won't work. Can someone help me with the code please:
What's the right edit to the code to submit an entry to the database via ajax without reloading the page?
Controller:
public function index(){
$this->load->helper('url');
$this->load->view('template');
}
function create()
{
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->model('dbmodel');
$response = array();
$this->load->model('dbmodel');
$result = $this->dbmodel->addnew_row();
}
Model:
public function addnew_row() {
$data = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
);
$result = $this->db->insert('books', $data);
return $result;
}
View Form:
<h2>Create</h2>
<?php echo form_open('welcome/create', array('id'=>'form'));?>
<p>Title: <?php echo form_input('title') ?></p>
<p>Description: <?php echo form_input('description') ?></p>
<?php echo form_submit('btn_submit','Save'); ?>
<?php echo form_close();?>
View AJAX:
// $.POST Example Request
$('#form').submit(function(eve){
eve.preventDefault();
var title = $('#title').val();
var description = $('#description').val();
url = '<?php echo site_url('welcome/create');?>'
$.ajax({
url: url,
type: 'POST',
data:{title:title, description:description
}
$(#dynamic_container).html(response.output);
});
});
Ok,At first you need to briefly go through the syntax of jQuery.ajax() before using it.
Now going though the AJAX code you mentioned in the question , this block of code is not suppose to be there
$(#dynamic_container).html(response.output);
AJAX provides Callback Function Queues to manipulate response before/after an AJAX call has been successfully completed , and in your case using success will resolve the issue :
$.ajax({
url: url,
type: 'POST',
data:{title:title, description:description
},
success : function(response){
$(#dynamic_container).html(response.output);
}
});
And you might be interested in using jQuery.post().

How to pass data to controller to view using json in php?

I using codeigniter.I need to pass data to my controller to view somehow.I manage to pass view to controller(in view when drop-down selected value pass to controller using ajax)
this is my HTML code
<div class="form-group">
<label for="lastname" class="control-label">Your Packages</label>
<?php if(isset($tourbuddy_packages)){?>
<select id="itemType_id" class="form-control input-sm" name="tripbuddy_PackageTitle" onChange="disp_text()">
<?php
foreach ($tourbuddy_packages as $packages) {?>
<option value="<?php echo $packages['PackageID'] ?>"><?php echo $packages['PackageTitle']?></option>
<?php } ?>
</select>
<input type="hidden" name="PackageID" id="country_hidden">
<?php } else { ?>
<select class="form-control input-sm" name="tripbuddy_PackageTitle">
<option>Add Packages</option>
</select>
<?php } ?>
</div>
when drop-down selected a vale i pass data to controller by using ajax and java Script
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
Selected vale pass to tea method in controller
public function tea()
{
$this->session->set_userdata(array('tripbuddy_PackageID'=>$_POST['id']));
$package_data = $this->ci->package_model->get_package($_POST['id']);
$package_cat = $this->ci->package_model->get_package_categories();
$data = array();
$data['tourbuddy_selected_package'] = $package_data[0];
$data['tourbuddy_selected_package_cat'] = $package_cat;
//echo $data['package']['AlbumID'];
$data['tourbuddy_selected_photos'] = $this->photo->get_package_photo_stream($data['tourbuddy_selected_package']['AlbumID']);
//echo var_dump($data['photos']);
echo json_encode($data);
}
now I need to pass $data array to my view without refreshing view page how can i do this ? need a quick help
First you need to add the correct header to your tea() function as it will be returning json
public function tea()
{
header('Content-Type: application/json');
//...
}
Then you will need to add the dataType parameter to your ajax call
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
dataType: 'json', //Added this
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
In your success function you will then be able to access the data like
success: function(response) {
response.tourbuddy_selected_photos.data
}
Controller
class Feature extends CI_Controller
{
public function tea()
{
$post = $this->input->post(); //do some form validation here
$model = Model::get($post); // do all business logic in the model
if(!$model){
//return a Response header rather than a 404View
return $this->output->set_status_header(404);
}
$responce = array(
'something' => $model->something
);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($responce))
->set_status_header(200);
}
}
Untested Javascript
var URL = <?php echo site_url(); ?>// Global URL variable
(function($){
var Form = {
init : function(){
this.Form = $("form#formId"),
this.ItemType = this.Form.find("#itemtype_id");
this.ItemType.on('change', $.proxy(this.change, this));
},
/**
* -----------------------------------------------------------------
* Bind the ItemTypeId change event to this function using $.proxy
* Ajax return's a deffered(promise) so capture it, and do stuff
* -----------------------------------------------------------------
**/
change : function(event){
this.doAjax(event.target).then(
function( data ) // success
{
$(this).html('Success'); // $(this) -> context
},
function( reason ) //fail
{
switch(reason.code)
{
case 404:
default:
$(this).html('no results found');
break;
}
}
);
},
/**
* -----------------------------------------------------------------
* Make the ajax request a wait for it to return a promise
* -----------------------------------------------------------------
**/
doAjax : function( target ){
var data = {
id : target.id
}
return $.ajax({
cache: false,
url : URL + 'feature/tea/',
context : target,
method: "POST",
data : data,
dataType : 'json',
}).promise();
}
}
Form.init();
}(jQuery));

jqgrid with cakephp --- Call to a member function url() on a non-object

This is my controller,
<?php
class PostsController extends AppController
{
var $name='Posts';
var $helpers=array('Html','Form');
var $components = array('Session','Paginator');
function beforeFilter()
{
parent::beforeFilter();
// $this->Auth->allow('index');
}
function index()
{
}
function getsites()
{
$this->layout= false;
$this->autoRender=false;
configure::write('debug',0);
// get no of rows
$limit= $this->params['url']['rows'];
//get the index row for sorting
$sidx= $this->params['url']['sidx'];
//get the sort order
$sord= $this->params['url']['sord'];
$page= $this->params['url']['page'];
//if sort collumn index not found then set it to 1
if(empty($sidx)) $sidx=1;
//calculate no of rows from query
$row=$this->Post->find('count');
$count=$row;
//if count is >0 then set total no of pages as per give limit
//else set total pages to 0
if($count>0)
$total_pages=ceil($count/$limit);
else
$total_pages=0;
//set start position of records
$start=$limit*$page-$limit;
if($start<0) $start=0;
//set range for data from database
$limitRange=$start.",".$limit;
$sortRange=$sidx.",".$sord;
//fetch only pure data avoiding unnecessay loading of related/associated data
$this->Post->recursive=-1;
$result=$this->Post->find('all',array('fields'=>array('id','title'),'order'=>$sortRange,'limit'=>$limitRange));
//setting the response object
$i=0;
$response->page=$page;
$response->total_pages=$total_pages;
$response->records=$count;
foreach($result as $row)
{
$response->rows[$i]['id']=$row['Post']['id'];
$response->rows[$i]['cell']=array($row['Post']['id'],$row['Post']['title'],$row['Post']['id']);
$i++;
}
echo json_encode($response);
exit;
}
}
this is the index.ctp
<h1>Blog posts</h1>
<script type="text/javascript">
$(document).ready(function(){
/* #id === id of the table */
$("#list").jqGid({
url:'<?php echo $html->url(array("controller"=>"Posts","action"=>"getsites")); ?>',
datatype:"json",
colNames:['Id','Title','IdHidden','Edit'],
colModel:[
{name:'id',index:'id',width:10},
{name:'title',index:'title',width:90},
{name:'idHidden',index:'idHidden',width:10,hidden:true},
{name:'Edit',index:'Edit',width:10,formatter : function(cellvalue,options,rowObject){return '<span class="editButtonSite ui-icon ui-icon-pencil" title="click to edit"></span>';}},
],
rowNum:2,
rowList:[2,4,6],
pager:jQuery("#pager"),
caption:'View Posts',
sortname:'id',
sortorder:'asc',
autowidth:true,
viewrecords:true,
loadcomplete:function(){
$("#content table tr td .editButtonSite").click(function(){
/*var ids = $(this).parent().prev().attr('title');
var editPage = '<?php echo $html->url(array("controller" => "sites", "action" => "edit"))?>';
editPage = editPage + "/" + ids;
window.location.href = editPage;*/
});
}
});
});
</script>
<table id="list" style="height:auto;"></table>
<div id="pager" style="height:auto;"></div>
default.ctp goes here
<?php
echo $this->Html->css('ui.jqgrid');
echo $this->fetch('css');
echo $this->Html->script('jquery');
echo $this->Html->script('jquery.jqgrid');
?>
The above is my code for using jqgrid in cake 2.x
I'm getting the following error....
Fatal Error
Error: Call to a member function url() on a non-object
File: /var/www/html/jqgridtry.local/app/View/Posts/index.ctp Line: 6
help me get out of this..
correct your code using Cake 2.x HtmlHelper .
url:'<?php echo $this->Html->url(array("controller"=>"Posts","action"=>"getsites")); ?>',
On /app/View/Posts/index.ctp file line 6, you shouldn't use $html->url, instead use this Router::url for better understand ind, please see this link http://book.cakephp.org/2.0/en/development/routing.html

Not able to get inputs in controller or model for an ajax call submit form

I have an ajax call for a form submit; it works fine if I pass my sql arguments when I hard code them, however if I want to pass my sql query arguments with inputs (from View) in my model it says: Message: Undefined index: startDate and endDate.
Here is my View:
<?PHP
$formData2 = array(
'class' => 'form-horizontal',
'id' => 'frm2',
);
echo form_open('gallery/fetchAssociates', $formData2);
?>
<input id="startDate" class="span2" size="16" type="text" />
<input id="endDate" class="span2" size="16" type="text" />
<input type="submit" class="btn btn-primary"
value="Submit" id="querystartEnd" name="querystartEnd" />
<?PHP
echo form_close();
?>
and my javascript for AJAX call is as following:
$.ajax({
type: "POST",
async: false,
dataType: "json",
?>",
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success: function(data) {
html = "<table id='myTable'><thead><tr id='test'><th>ID</th><th>Start Date</th><th> LName</th></tr></thead><tbody id='contentTable'>";
for (var i = 0; i < data.length; i++)
{
html = html + "<tr id='trResponses' ><td><div >" + data[i]['id']
+ " </div></td><td><div >" + data[i]['start'] +
"</div> </td><td><div >" + data[i]['username'] +
"</div></td></tr>";
}
html = html + "</tbody></table>";
$("#resultFrm2").html(html);
},
error: function()
{
alert('error');
}
});
and here is my controller:
public function fetchAssociates() {
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
//die();
$this->load->model('user_model');
echo json_encode($this->user_model->getAll());
}
and my Model method is as following:
public function getAll()
{
$wtc = $this->load->database('wtc', TRUE);
$sql = "SELECT username, MIN(timeIn) as start
FROM tc_timecard
GROUP BY userid having MIN(timeIn) > ? and MIN(timeIN) < ?
order by MiN(timeIN);";
//$q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
$q = $wtc->query($sql, array($this->input->post('startDate'),
$this->input->post('endDate')));
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
As you see my comments in my code: if I have
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
uncommented in firebug in response it says "Message: Undefined index: startDate and endDate."
Also in my controller if I have
// $q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
un-commented it works but once I want to pass the inputs by the following line of code it does not work :
$q = $wtc->query($sql, array($this->input->post('startDate'), $this->input->post('endDate')));
What can be the reason that I cannot access my inputs in my controller or Model?
If it is not clear for you, please let me know which part you need more clarification.
EDITED:
It is worth mentioning that my ajax call is inside the following block:
$('#frm2').submit(function(e)
{
e.preventDefault();
//My AJAX call here
});
Many thanks in advance,
You are not passing any data through ajax
// Collect data from form which will be passed to controller
var data = {
start_data : $('#startDate').val(),
start_data : $('#endDate').val(),
}
$.ajax({
type: "POST",
async: false,
dataType: "json",
data : data // data here
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success : function(data){
// Success code here
},
error: function(data){
// error code here
}
})

Categories