I have this simple code that display only 2 column (step and feedback)
so whenever the "feedback" has submited or post like in my controller below and the "step" column would count like $step+=1 or update with query update my_table set step = step + 1 where id = $user_id ,,which is if "feedback" has submited the "step" column always increment ++ .
controllers/Person.php
public function ajax_update()
{
$data = array(
//'step' => $this->input->post('step'),
'feedback' => $this->input->post('feedback'),
);
$this->person->update(array('user_id' => $this->input->post('user_id')), $data);
echo json_encode(["status" => TRUE]);
}
Model/Person_model.php
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
Views/person_view.php
<div class="form-group">
<label class="control-label col-md-3">kcp naem</label>
<div class="col-md-9">
<input name="feedback" placeholder="status" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
plus jquery ajax for button save()
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
url = "<?php echo site_url('person/ajax_update')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
});
}
maybe we should just focus on the controller and model .
Some assistance would be great on how to setup the update.
Thankyou
You can do this in qb using the following method:
$this->db->set('step', 'step+1', FALSE);
$this->db->where('user_id', $user_id);
$this->db->update('tablename');
https://www.codeigniter.com/userguide3/database/query_builder.html#updating-data
// controller
public function ajax_update() {
$feedback = $this->input->post('feedback');
$uid = $this->input->post('user_id');
if (!is_null($feedback) && !is_null($uid)) {
// only increment: "whenever the "feedback" has submited or post"
$this->person->update_feedback($uid, $feedback);
echo json_encode(["status" => TRUE]);
} else {
echo json_encode(['status' => FALSE]); //?
}
}
// model
public function update_feedback($user_id, $feedback) {
$this->db->set('step', 'step+1', FALSE);
$this->db->set('feedback', $feedback);
$this->db->where('user_id', $user_id);
$this->db->update($this->table);
return $this->db->affected_rows();
}
Related
I'm building a function in Laravel along with the datatables and ajax. I have a fully working page with multiple functions that return data into the databale however one of the functions doesn't like to search properly and doesn't return any data into the table.
I have a datapicker with the following code:
<div class=" input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-clock"></i></span>
</div>
<input class="form-control" type="text" data-plugin-datepicker id="lastLogged" name="lastLogged" placeholder="Owner has not logged in since:">
</div>
My search button is called: search_data
My ajax call is as followed:
<script>
$(document).on("click", "#search_data", function (e) {
e.preventDefault();
$(this).html("<i class='fa fa-circle-o-notch fa-spin'></i>");
})
$.ajax({
url: "/search/user",
type: "POST",
dataType: "json",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: {
loginUser : $('#lastLogged').val()
}
})
.done(function(data) {
console.log(data);
table.ajax.reload();
$('#search_data').html('<i class="fas fa-search"></i>');
})
.fail(function(data) {
console.log(data);
$('#search_data').html('<i class="fas fa-search"></i>');
});
});
My PHP controller:
public function Building(Request $request)
{
if ($request->ajax())
{
$buildings = building::with('ownerinfo');
$data = array();
$totalData = building::count();
$totalFiltered = $totalData;
$start = $request->input('start');
$order = 'id';
$dir = $request->input('order.0.dir');
// Other if statements here with functions
if(isset($request->login))
{
$date = date("Y-m-d H:i:s",strtotime($request->login));
$users = Users::where('last_login_in', '<=', $date)->get();
foreach($users as $user) {
$buildings = $buildings->where('owner', $user->id);
}
}
$buildings = $buildings->get();
if(!empty($buildings))
{
foreach ($building as $building)
{
$nestedData['id'] = $building->id;
$nestedData['name'] = $building->buildingName;
$nestedData['view'] = '<a class="button is-small full-width is-hovered" href="/view/building/' . $building->id . '">View</a>';
$data[] = $nestedData;
}
$json_data = array(
"data" => $data,
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered)
);
return json_encode($json_data);
}
}
}
This keeps on returning no data at all. I am using 1 January 2019 from the datepicker to search, it has the value: 2019-01-01 00:00:00 and the data of one of the users in the database has 2018-08-20 07:11:34. I checked the queries with var_dumps and it returns the correct users, however it doesn't show any results in the buildings datatable.
The idea behind this is to let an administrator select a specific date, the database runs the search and returns buildings of users that have not logged in since the selected date.
What am I doing wrong?
The $users return the correct users but the $buildings are empty?
Try to use a hasMany relation between the User and Building it will be a better solution than this:
foreach($users as $user) {
$buildings = $buildings->where('owner', $user->id);
}
I'm now self-practicing Codeigniter with the help of internet. I'm able to create almost all operations now , but today I'm tried to fetch data using ajax call. Nothing is retrieving from database, but while debugging with Chrome's debugger, no error is showing. I'm hitting my head for six hours for this problem.I tried everything and reached finally here.
This is my Model
public function member_id($postData)
{
$response = array();
if($postData['member_id'] ){
$this->db->select('*');
$this->db->where('member_id', $postData['member_id']);
$q = $this->db->get('tbl_test');
$response = $q->result_array();
}
return $response;
}
Controller
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->_init();
}
private function _init()
{
$this->output->set_template('default');
$this->load->css('assets/themes/default/css/my.css');
$this->load->css('assets/themes/default/css/bootstrap.css');
$this->load->css('assets/themes/default/css/bootstrap-theme.css');
}
public function index()
{
$data['title'] = "My Real Title";
$this->load->view('pages/home',$data);
}
public function feeDetails()
{
$postData = $this->input->post();
$this->load->model('Model');
$data = $this->Model->member_id($postData);
echo json_encode($data);
}
View
<input class="form-control in2" id="txtmemid" placeholder="Member id " name="txtmemid" value="" style="text-transform:uppercase" type="text">
<button type="submit" id="btnmemfeeview" class="btn btn-default ho showser fl ">Search</button>
Bill No: <span id='bno'></span><br/>
Bill date: <span id='bdate'></span><br/>
Member id: <span id='mid'></span><br/>
and finally this is my ajax
<script type='text/javascript'>
$(document).ready(function(){
$("#btnmemfeeview").click(function(){
var member_id = $('#txtmemid').val();
$.ajax({
url:'<?=base_url()?>index.php/Pages/feeDetails',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
var len = response.length;
if(len > 0){
// Read values
var bno = response.BILL_NO;
var bdate = response.BILL_DATE;
var mid = response.MEMBER_ID ;
$('#bno').text(bno);
$('#bdate').text(bdate);
$('#mid').text(mid);
}else{
$('#bno').text('');
$('#bdate').text('');
$('#mid').text('');
}
}
});
});
});
</script>
I developed this shape with laravel code
When I click on + the quantity of this product increase by 1.
When I click - the quantity of this product decrease by 1.
cart.blade.php (view):
<div class="cart_quantity_button">
<a class="cart_quantity_up" href='{{url("cart?product_id=$item->id&increment=1")}}'> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href='{{url("cart?product_id=$item->id&decrease=1")}}'> - </a>
</div>
Cart function in controller:
public function cart()
{
if (Request::isMethod('POST')) {
$product_id = Request::get('product_id');
$product = Product::find($product_id);
Cart::add(array('id' => $product_id,'name' => $product->name, 'qty' => 1, 'price' => $product->price,'options'=>array('image'=>$product->image)));
}
$id = Request::get('product_id');
//increment the quantity
if ($id && (Request::get('increment')) == 1) {
$p = Request::get('increment');
$rowId = Cart::search(array('id' => $id));
// echo "row id".$rowId."and the p=".$p;
$item = Cart::get($rowId[0]);
// echo "row id".$rowId;
$add = $item->qty + 1;
Cart::update($rowId[0], $add);
}
//decrease the quantity
if ($id && (Request::get('decrease')) == 1) {
$rowId = Cart::search(array('id' => $id));
$item = Cart::get($rowId[0]);
$sub = $item->qty - 1;
echo "item" . $sub;
Cart::update($rowId[0], $sub);
}
if ($id && (Request::get('remove')) == 1) {
$rowId = Cart::search(array('id' => $id));
Cart::remove($rowId[0]);
}
$cart = Cart::content();
return view('cart', array('cart' => $cart,'title' => 'Welcome', 'description' => '', 'page' => 'home','subscribe'=>"",'brands' => $this->brands));
}
public function cart_remove()
{
Cart::destroy();
return Redirect::away('cart');
}
public function checkout()
{
$cart = Cart::content();
return view('checkout', array('cart' => $cart,'title' => 'Welcome', 'description' => '', 'page' => 'home','subscribe'=>"",'brands' => $this->brands));
}
I want to convert this with ajax code, I do simple code for this
<script>
function getMessage($id)
{
$.ajax({
type: 'POST',
url: 'getmsg',
dataType: 'json',
data: {
valu_id: $id
},
success: function(data) {
$("#msg").html(data.msg);
}
});
}
</script>
<?php
$item_id = 3;
echo Form::button('+',['onClick'=>'getMessage($item_id)']);
?>
<div id='msg'>
<input id="msg" type="text" name="quantity" autocomplete="off" size="2">
</div>
Controller function:
public function ajax()
{
$value= $_POST['valu_id']+1;
return response()->json(array('msg'=>$value), 200);
}
I don't know how to complete this code .I have many question about this code.
like
How to get the product id from cart.blade.php view and put it in getmessage() to use it in ajax function?
How to put getmessage() in <div class="cart_quantity_button"> instead of button onclick to respect of the shape above?
How to return the quantity in the input field as the shape above?
Note: This answer doesn't simply giving you a working solution but an idea on how to handle ajax request/response.
Firstly, even tough event.preventDefault() would prevent default action which is following the URL, I'd rather store the URL to data- attribute.
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-route="{{url('cart?product_id=$item->id&increment=1')}}"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-route="{{url('cart?product_id=$item->id&decrease=1')}}"> - </a>
</div>
How to get the product id from cart.blade.php view and put it in getmessage() to use it in ajax function?
It's always better to listen to an event, which is click in this case.
$('.cart_quantity_up').on('click', function(e) {
//an ajax call here
});
Same code applies for the other one
$('.cart_quantity_down').on('click', function(e) {
//an ajax call here
});
Now, two click events has been attached to each corresponding element. Then, it's time to wrap the ajax function up.
function updateQty(url){
var $qty = $('.cart_quantity_input');
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
cart_qty: $qty.val()
},
success:function(data){
$qty.val(data.qty);
}
});
}
The function above is simply
takes a parameter which is URL for ajax to call to,
does a post request with uri param key 'cart_qty'
returns response which is a value of 'qty' from controller to cart_quantity_input input element
And then, put the ajax function to the first snippets (click event)
$('.cart_quantity_up').on('click', function(e) {
e.preventDefault();
//get the data-route
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
$('.cart_quantity_down').on('click', function(e) {
e.preventDefault();
//get the data-route
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
Actually to make things simpler, you can attach the event from multiple selectors at one go.
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
//get the data-route for the 'up'
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
Now, you get the idea on how to create ajax post and retrieve its response to attach it to the input element afterward.
At this point, I'm going to refactor your code. And oh, all of your questions should have been answered at this stage.
Your controller looks a bit messy as you handle both post and get requests for such simple situation. I would rather do just post. Instead of having bunch of conditions, I'll put the footprint inside the data- attribute (again). In the end, I wrap them inside a form, because CSRF token gives more security on your end.
<form name="cart_form">
{{ csrf_field() }}
<input type="hidden" class="item_id" value="{{ $item->id }}">
<div class="cart_quantity_button">
<button type="button" class="cart_quantity_up" data-route="{{url('cart')}}" data-increase="1"> + </button>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<button class="cart_quantity_down" data-route="{{url('cart')}}" data-increase="0"> - </button>
</div>
</form>
You're free to design your own view as long as you're going to do a post request (as I'm doing on it). I'll explain a bit above the logic I'm going to make.
Hold the $item->id on hidden field
Going to make ajax request to url('cart') route and store it to data-route
Add data-increase to differentiate each request should increase or decrease
Now listen up on click event
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var $this = $(this),
url = $this.data('route'),
increase = $this.data('increase');
updateQty(url, increase);
});
Below updateQty function is a bit different from the first one I made. It accepts the second parameter increase as (pseudo-)boolean value. Also notice I'm posting the token as request header rather than body.
function updateQty(url, increase){
var $qty = $('.cart_quantity_input'),
itemId = $('.item_id').val();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
headers: {
'X-CSRF-Token' : $('input[name="_token"]').val()
},
data: {
'cart_qty': $qty.val(),
'item_id': itemId,
'increase': increase
},
success:function(data){
$qty.val(data.qty);
}
});
}
Your controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cart;
use App\Http\Requests;
class YourController extends Controller
{
public function cart(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
$cart = Cart::search(['id' => $id]);
//Note: This code may not working as what you expect
// but it should give you the idea that laravel
// actually has increment and decrement methods
// and else.
if ($request->increase) {
$cart->increment('qty');
} else {
$cart->decrement('qty');
}
$qty = $cart->first(['qty']);
return response()->json(['qty' => $qty]);
}
//rest is your code
//...
}
}
In the above code, I'm trying to
treat ajax request separately from your code,
update qty column based on $_POST['increase']
If 1, do increment. If 0, decrements it
grab the value of qty column (though Im not sure it's going to work)
return the value keyed 'qty' as json
it will then update your input element based on $qty.val(data.qty)
So I am loading data into a form and the user should be able to change it and save it. The data loads fine and when the user clicks on the save button, jQuery grabs that data and should send it to my codeignighter controller, but it does not. The weird thing is that codeignighter is saying that the call was successful.
Here is my jQuery (it is in a seperate .js file):
$(document).ready(function(){
$("#checkin").submit(function(e){
e.preventDefault();
var ConditionID = [];
$('input[name^="ConditionID"]').each(function() {
ConditionID.push($(this).val());
});
var Field = [];
$('div[name^="Field"]').each(function() {
Field.push($(this).val());
});
var Status = [];
$('select[name^="Status"]').each(function() {
Status.push($(this).val());
});
var Description = [];
$('textarea[name^="Description"]').each(function() {
Description.push($(this).val());
});
$.ajax({
url: "/index.php/ConditionReports/saveCheckin",
type: "POST",
data: {'ConditionID':ConditionID,'Field':Field,'Status':Status,'Description':Description},
success:function(data)
{
alert('SUCCESS!!');
},
error:function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
}
});
});
});
My view:
<form action='' method='post' id='checkin' accept-charset='ytf-8'>
<?php
$i=0;
foreach($Conditions as $c) {
echo("
<input type='hidden' id='ConditionID' name='ConditionID[]' value='$c->ConditionID' />
<div id='Field' name='Field[]' value='$c->Field'>$c->Field</div>
<select id='Status' name='Status[]'>");
$e=($c->Status=="E"?"selected":"");
$g=($c->Status=="G"?"selected":"");
$s=($c->Status=="S"?"selected":"");
$b=($c->Status=="B"?"selected":"");
$m=($c->Status=="M"?"selected":"");
echo("
<option $e value='E'>Excellent/New</option>
<option $g value='G'>Good</option>
<option $s value='S'>Satisfactory</option>
<option $b value='B'>Poor/Needs Repair</option>
<option $m value='M'>Missing</option>
</select>
<textarea class='form-control' name='Description[]' id='Description'>$c->Description</textarea>
");
$i++;
}
?>
<button type="button" class="btn btn-info">Print</button>
<input type="submit" id="saveCheckin" value='Save' class="btn btn-success save">
<button type="button" class="btn btn-success">Check-In</button>
</form>
My controller:
class ConditionReports extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('ConditionReportsVM');
$header_data['js'] = array('jquery-2.2.1.min','checkin');
$this->load->view('header', $header_data);
}
public function saveCheckin()
{
$data = array(
'ConditionID' => $this->input->post('ConditionID'),
'Field' => $this->input->post('Field'),
'Status' => $this->input->post('Status'),
'Description' => $this->input->post('Description'),
);
$this->ConditionReportsVM->UpdateReport($data);
}
}
And lastly my model:
public function UpdateReport($data)
{
$this->db->where('ConditionID',$data['ConditionID']);
$this->db->update('Conditions',$data);
}
I have been stuck on this for quite a bit of time now and any help I can get is most appreciated. I have debugged jQuery and found out that the appropriate data is being called. There are no console errors. I have tried to echo something from the controller and I have also tried to redirect the page from the controller but the controller just seems like it is not being hit.
Thank you in advance.
Note: Currently the response I get after I click save is an alert with this in it: "SUCCESS!!"
SOLUTION
Thanks to Goose (in the comments) I was able to find my issue. I did not know this, but you can see the response from the server if you go to the developer tools, and go to the Network tab. As soon as I went there I noticed that codeigniter was throwing an Array to string conversion error in my model.
Here is what my model looks like now (the data is saving and everything):
public function UpdateReport($data)
{
for($i=0;$i<count($data['ConditionID']);$i++) {
$this->db->where('ConditionID',$data['ConditionID'][$i]);
$this->db->update('Conditions', array('Status' => $data['Status'][$i], 'Description' => $data['Description'][$i]));
}
}
I have a working comment form with $post->id that submits data via ajax, notice there isn't any form tags.
<div class="comment-fields">
<div class="row commenter-comment">
<div class="form-group col-md-12">
<textarea id="commenter_comment" name="commenter_comment" class="form-control comment-field" title="User's comment" placeholder="Comment Text"></textarea>
</div>
</div>
<div class="row commenter-name-email">
<input type="hidden" id="commenter_parent" name="commenter_parent" class="commenter-parent" value="0">
<input type="hidden" id="commenter_post" name="commenter_post" class="commenter-post" value="{{ $post->id }}">
</div>
<div class="row commenter-captcha">
<div class="col-md-3">
Comment
</div>
</div>
</div>
And this is the javascript handler
$(document).on('click', 'a.post-this-comment', function(){
var form_data = {
'per_page': $('.comments_per_page').val(),
'commenter_parent': $('#commenter_parent').val(),
'commenter_post': $('#commenter_post').val(),
'commenter_comment': $('#commenter_comment').val(),
};
var arr = [
'commenter_parent',
'commenter_post',
'commenter_comment'
];
for (var i in arr, i < arr.length, i++) {
var elem = arr[i];
form_data[elem] = $('#' + elem).val();
}
// console.log(form_data); // something like => Object {per_page: "some_value", commenter_parent: "some_value", commenter_user_id: "some_value", commenter_comment: "some_value"}
var request = $.ajax({
type: 'POST',
url: 'post_this_comment',
data: form_data,
dataType: 'json'
});
request.done(comment_done_handler);
request.fail(comment_fail_handler);
});
All I want to do is get the post id of the current post so I can tell the comment_list() to get me only the comments of that post.
I cannot even get the value of commenter_post from comment_list() method, I get null. But I am able to retrieve the values from other methods just fine.
so I have added a hidden field (without form tags) to a partial that retrieves the post_id
<input type="hidden" id="post_id" name="post_id" class="post-id" value="{{ $post->id }}">
However, when I try to get the value of that field, I always get null
Comment Model
public static function root_comments($postId) { // setting $postId
return self::child_comments(0, 'desc')->where('post_id', $postId);
}
CommentController
protected function comment_list($per_page, Request $request) {
$post = Input::get('post_id');
dd($post); // returns null
$root_comments = Comment::root_comments(1); // I am setting the postId manually here
$root_with_replies = $this->include_replies_for($root_comments);
$paginated_comments = $this->paginate($root_with_replies, $per_page, $request);
return $paginated_comments;
}
Index() method on CommentController
public function index(Request $request) {
$view_data = self::view_data($request);
return view('eastgate.comment.leave_a_comment', $view_data);
}
Try dumping the whole request object and look over the parameters in the POST or GET request, make sure your field is there, if not something might be wrong with the form.
Is that hidden field, inside an actual form that is submitted before the comments_list function is called?
You've tagged Laravel-5 for the question, but are using the Laravel 4 method of retrieving input. For Laravel 5 input retrieval, try:
$post = $request->input('post_id');
Additionally, per the Controller help page, your route arguments should come after your other dependancies.
CommentController
protected function comment_list(Request $request, $per_page) {
$post = $request->input('post_id');
dd($post);
$root_comments = Comment::root_comments(1);
$root_with_replies = $this->include_replies_for($root_comments);
$paginated_comments = $this->paginate($root_with_replies, $per_page, $request);
return $paginated_comments;
}