laravel5.2 convert laravel code to ajax - php

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)

Related

Laravel how to pass data from controller to modal dialogue using ajax

I have items and for every item there are related items, so when I open the homepage it shows all item, when I want to click on any item, ajax will pass this item id to controller to get the related items for this item, the problem is I want to show the related item in a modal dialogue, the modal dialogue now show all related items to all items not to the current item.
I think the problem is because the include of modal in the homepage which has the foreach!, hope you can help me in solving this issue
route
Route::get('/',['as'=>'showItems','uses'=>'HomeController#getItem']);
Route::get('Get_relateditem',['as'=>'Get_relateditem','uses'=>'HomeController#getItem']);
ajax
$(function(){
$('.Item_root').on("click", function () {
var item_id = $(this).data('id');
$.ajax({
type:'get',
url: '/',
data: {
'_token': $('input[name=_token]').val(),
'item_id':item_id,
},
success:function(data){}
});
});
});
controller
public function getItem(Request $request)
{
$currentitemid =$request->item_id;
$ritems = Relateditem::orderBy('id', 'asc')->where('ritemf_id','LIKE','%'.$currentitemid.'%')->with('items')->get()->groupBy('ritemf_id');
$items = Item::orderBy('category_id', 'asc')->with('category')->get()->groupBy('category_id');
$categories = Category::orderBy('category_id', 'asc')->get();
return view('home')->with('items',$items)->with('categories',$categories)->with('ritems',$ritems);
}
}
modal
#foreach($ritems as $item_id => $realtedItems)
#foreach($realtedItems as $ritem)
<div class="SuggestedItem_container">
<label color="red" class="Checker_root Checker_red Checker_left">
<input type="checkbox" class="Checker_input" value="on">
<div class="SuggestedItem_nameContainer">
<div>
<span class="SuggestedItem_name">{{$ritem->riteml_id}}</span>
<span class="SuggestedItem_price styles_small styles_base styles_spacing-base">+$3.95</span></div></div>
<div class="SuggestedItem_description styles_small styles_base styles_spacing-base">
<span class="SuggestedItem_category styles_bold">Appetizers</span>
<span> ยท Edamame soybean pods harvested right before the beans begin to harden are lightly boiled and seasoned with sea salt.</span>
</div>
</label>
</div>
#endforeach
#endforeach
Modify routes:
Route::get('/','HomeController#getItem');
Route::get('/get_related_items/{id}','HomeController#getRelatedItems');
modify getItem to get only the items and categories:
public function getItem(Request $request)
{
$items = Item::orderBy('category_id', 'asc')
->with('category')->get()
->groupBy('category_id');
$categories = Category::orderBy('category_id', 'asc')->get();
return view('home',['items' => $items,'categories' => $categories]);
}
get related items for a single item id:
public function getRelatedItems(Request $request, $id)
{
$ritems = Relateditem::orderBy('id', 'asc')
->where('ritemf_id',$id)
->with('items')
->get()
->groupBy('ritemf_id');
return response()->json($ritems);
}
now for the js part:
$(function(){
$('.Item_root').on("click", function () {
var item_id = $(this).data('id');
$.ajax({
type:'get',
url: '/get_related_items/' + item_id,
data: {
'_token': $('input[name=_token]').val()
},
success:function(data){
if(data && data.length){
var con_el = $('.SuggestedItem_container');
for(var i = 0; i < data.length;i++){
var related_item_el = "<div class='related_item'><p>" + data[i].id + "</p></div>"
con_el.append(related_item_el);
}
}else{
console.log('no related items found');
}
}
});
});
});
this will insert all the related items inside the SuggestedItem_container
i didn't write the view template cuz that part is easy, and note that i only included the related item id as example cuz i don't know what fields the item has.
i hope this helps you

Link to a specific part of a page

I have a div that has lots of posts which is created dynamically from the database. The div has input for comment facility as well. I have no problems in posting the comments and I do it using a POST method. Then I redirect to the page using return redirect('/'); method. But it links to the beginning to the page which doesn't create a good impression on the user. The user might be in the middle of the page and when he/she comments he will go to the beginning of the page and will have to scroll down again. Luckily, I have the divs with class equal to the post_id. So, isn't there any method to go to the post in which the user posted using that class?
attach the id with the url like /#post-id
Inside your contorller where you are processing and saving the comments:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
public function yourCommentSaveFunction()
{
...
//Get the Post ID and store in $postid
return Redirect::to(URL::previous() . '#' .$postid);
}
This should work fine.
But the best way would be to use AJAX to post comments.
Edit (As request by OP)
THE AJAX METHOD
Controller will be something like:
public function saveComment(Request $request)
{
//you do the saving part..
...
$comment = $request->comment;
//after saving the comment return a json response
//you can also send other varibales like username, created at etc..
return Response::json(array(
'success' => true,
'comment' => $comment,
));
}
Route:
Route::post('/save-comment', [
'as' => 'save-comment',
'uses' => 'yourController#saveComment',
]);
And your View:
<form action="{{ route('save-comment') }}" class="comment-form">
<input type="text" name="comment">
<input type="submit" name="submit">
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<div class="comment"></div>
</form>
<script>
$('.comment-form').submit(function(event){
event.preventDefault();
var comment = $this.val();
var token = $('.token').val();
var $url = "{{ route('save-comment') }}";
$.ajax({
url: route,
type: 'POST',
data: {_token: token, comment: comment},
dataType: 'JSON',
success: function (data) {
$(".comment").append('<div class="new-comment">' +data.comment +'</div>');
},
error: function(data) {
console.log("Something went wrong");
}
});
});
</script>
Please note: this is just a sample code.

update another column if another column got post (Codeigniter) PHP

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

I want to click the checkbox to display the database filed values in codeigniter

I want to click checkbox to show the data what i want fetch through ajax call, but it is showing database all data automatically show whats the problem please find out and help me (just i want ajax call)
Controller
//This is my controller
public function laptops()
{
$this->load->model('feature_model');
$filter = array(
'price' => $this->input->get('price'),
'name' =>$this->input->get('name')
);
$data['laptop'] = $this->feature_model->laptops_m($filter);
//echo json_encode($this->feature_model->laptops_m($filter));
$this->load->view('feature/checkbox',$data);
}
//This is my model
function laptops_m($filter = null){
$this->db->select('*')
->from('mobile_phones');
// $query = $this->db->get('laptop_notebook')->result();
// return $query;
if($filter['name']){
$this->db->where('name', $filter['name']);
}
if($filter['price']){
$this->db->where('price', $filter['price']);
}
$query = $this->db->get()->result();
return $query;
}
//This is my view
<input type="checkbox" name="name" value="acer">
<input type="checkbox" name="name" value="lenovo">
<input type="checkbox" name="price" value="1000">
<table>
<tbody>
<?php foreach ($laptop as $laptops_all) { ?>
<tr>
<td><p>Laptop <?php echo $laptops_all->name ?> </p>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Ajax script:
// This is the ajax script function
<script>
$("input[checkbox]").change(function(){
$.ajax({
url: localhost/ci35/feature/laptops,
dataType: 'json',
success: function(data){
$.each(data, function(index, element) {
$("tbody").empty();
$("tbody").append("<tr><td>"+
"Laptop "+element.brand+""+
"</td></tr>");
});
}
});
You try to get data to display from GET array here:
$filter = array(
'price' => $this->input->get('price'),
'name' =>$this->input->get('name')
);
But your GET array is empty because of you don't send any data with your json request. From jQuery documentation:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
So you should iterate over checked checkboxes and add it's values to array. Then send this array via data property of ajax request.
Try this..add class="searchType" to html checkbox element, then in jquery
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
url: localhost/ci35/feature/laptops,
dataType: 'json',
success: function(data){
$.each(data, function(index, element) {
$("tbody").empty();
$("tbody").append("<tr><td>"+
"Laptop "+element.brand+""+
"</td></tr>");
});
}
});
}
});
as you are printing the data through success ajax call, no need to use foreach again in view.
Also in your controller, you have to print json data.
public function laptops()
{
$this->load->model('feature_model');
$filter = array(
'price' => $this->input->get('price'),
'name' =>$this->input->get('name')
);
$data['laptop'] = $this->feature_model->laptops_m($filter);
echo json_encode( $data['laptop'] );
// $this->load->view('feature/checkbox',$data);
}

Laravel5: retrieving post_id from a hidden input returns null

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

Categories