I want to filter products in my category with price desc or asc or newest(id desc). But my ajax filter only action in first page
This is my view and script:
<script type="text/javascript">
function sort(value) {
$.ajax({
type: 'get',
url: '{!!URL::to('cate/update') !!}',
data: {'sort': value, 'id': {{ $id }} },
}).done(function (data) {
$('body').html(data)
}).fail(function (data) {
console.log(data);
});
}
</script>
This is my controller:
if ($request->sort == 1) {
$data['items'] = Product::where('prod_cate', $request->id)->orderby('promotion_price', 'asc')->paginate(3);
} else if ($request->sort == 2) {
$data['items'] = Product::where('prod_cate', $request->id)->orderby('promotion_price', 'desc')->paginate(3);
}else{
$data['items'] = Product::where('prod_cate', $request->id)->orderby('prod_id', 'desc')->paginate(3);
}
return view('frontend.product_type', $data);
Related
Here I have a dropdown menu is like - countryName->CityName->ThanaName (ThanaName depends on CityName and CityName depends on countryName)
First of all I fetch country name from database table.
I passed country name through ajax as like as below.
$(document).on('change', '[name=country]', function() {
var country = $(this).val();
get_city(country);
});
function get_city(country) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-city')}}",
type: 'POST',
data: {
country_name: country
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="city"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
And the route in web.php is like Route::post('/get-city', 'CityController#get_city')->name('get-city');
And in CityController , the get_city method is like
public function get_city(Request $request) {
$country_info = Country::where('status',1)->where('name', $request->country_name)->first();
$cities = City::where('country_id', $country_info->id)->get();
$html = '';
foreach ($cities as $row) {
// $val = $row->id . ' | ' . $row->name;
$html .= '<option value="' . $row->name . '">' . $row->getTranslation('name') . '</option>';
}
echo json_encode($html);
}
And this is working absolutely fine and it returns cityname according to its country name. But the problem is for thanaName that depends on cityName. For this my route is like Route::post('/get-thana', 'ThanaController#get_thana')->name('get-thana');
In ThanaController, the get_thana method is like
public function get_thana(Request $request) {
$city_info = City::where('name', $request->city_name)->first();
$thanas = Thana::where('city_id', $city_info->id)->get();
$html = '';
foreach ($thanas as $row) {
// $val = $row->id . ' | ' . $row->name;
$html .= '<option value="' . $row->name . '">' . $row->getTranslation('name') . '</option>';
}
echo json_encode($html);
}
and the ajax code is like
$(document).on('change', '[name=city]', function() {
var city = $(this).val();
console.log(city);
console.log('Here');
get_thana(city);
});
function get_thana(city) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-thana')}}",
type: 'POST',
data: {
city_name: city
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="thana"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
But it show
POST http://localhost/rul/ecom/get-thana 500 (Internal Server Error)
Here is my ajax full code.
<script type="text/javascript">
$(document).on('change', '[name=country]', function() {
var country = $(this).val();
console.log(country);
console.log('country');
get_city(country);
});
function get_city(country) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-city')}}",
type: 'POST',
data: {
country_name: country
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="city"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
//start another
$(document).on('change', '[name=city]', function() {
var city = $(this).val();
console.log(city);
console.log('Here');
get_thana(city);
});
function get_thana(city) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get-thana')}}",
type: 'POST',
data: {
city_name: city
},
success: function (response) {
var obj = JSON.parse(response);
if(obj != '') {
$('[name="thana"]').html(obj);
AIZ.plugins.bootstrapSelect('refresh');
}
}
});
}
</script>
In browser network tab the error show like the below image when I change city.
enter image description here
Browser console tab: enter image description here
I'm using ajax to implement infinite scroll pagination in laravel but I cannot access the url while I can with the enter the url in the adress bar or via the default pagination page list.
I get GET http://localhost:8888/gest/items?page=2 500 (Internal Server Error)
Scripts
<script type="text/javascript">
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page){
$.ajax(
{
url: '?page=' + page,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
if(data.html == " "){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$(".row-items").append(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
And the controller
public function index(Request $request, $submenu = null){
$items = Item::paginate(5);
if ($request->ajax()) {
$view = view('data',compact('items'))->render();
return response()->json(['html'=>$view]);
}
return view('layouts.gest', compact('items'), ['submenu' => $submenu]);
}
EDIT
I also tested to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The error was that laravel couldn't find the view data
How do I programmatically remove an item from the Woocommerce cart using AJAX? I tried putting a function in my functions.php file and accessing that but nothing gets deleted. I tried hard-coding product 299 but it doesn't delete. Here's what I did:
functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = 299;
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
}
return true;
}
themes/mine/main.js
$.ajax({
type: 'POST',
dataType: 'text',
url: "http://www.../wp/wp-content/themes/mine/functions.php",
data: {
action: 'remove_item_from_cart'
},
success: function( data ) {
console.log(data);
}
});
Use proper ajax method of wordpress like this: This worked fine for me.
//functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
//main.js
$.ajax({
type: "POST",
url: 'http://localhost/your_site/wp-admin/admin-ajax.php',
data: {action : 'remove_item_from_cart','product_id' : '4'},
success: function (res) {
if (res) {
alert('Removed Successfully');
}
}
});
This seems to work.
HTML:
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
?<
<button class="remove-item" data-cart-item-key="<?=$cart_item_key;?>">
remove item
</button>
<?
}
?>
Javascript:
$('.remove-item').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'remove_item_from_cart',
'cart_item_key': String($(this).data('cart-item-key'))
}
});
});
In functions.php, inside the template folder:
function remove_item_from_cart() {
$cart_item_key = $_POST['cart_item_key'];
if($cart_item_key){
WC()->cart->remove_cart_item($cart_item_key);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
For WooCommerce 3.0+ you can do it using the built-in remove_cart_item() function
function findCartItemKey($cartItems, $productId){
foreach($cartItems as $cartKey => $item){
$product = $item['data'];
if($product->get_id() == $productId){
return $cartKey;
}
return false;
}
}
global $woocommerce;
$cartItemKey = findCartItemKey($woocommerce->cart->get_cart())
$woocommerce->cart->remove_cart_item($cartItemKey);
Controller Function Code
public function siteadmin_get_subcategory(Request $request)
{
$product_id = $request->input('product');
$sub_category=array(
'product_id'=>$product_id,
);
$return = Category_model::get_subcategory($sub_category);
//return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
}
Model Function Code (which gets subcategory on product id)
public static get_subcategory($sub_category)
{
return DB::table('le_product')->where('product_id', '=', $sub_category)->get();
}
View JavaScript Code
This is my Ajax concept for Dropdown list based on parent
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo base_url('SiteadminController/siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
You need to call the correct URL in your AJAX:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo action('SiteadminController#siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
Also AJAX is expecting JSON, from what I see, you will return HTML. So you need to make a Controller action to return JSON.
get_subcategory1
public function get_subcategory1()
{
/*$product_id = $request->input('product_id');
$data=array(
'product_id'=>$product_id,
);*/
//$get_subcategory1 = Category_model::get_subcategory1();
return view('siteadmin.get-subcategory1');
}
I can't seem to get my voting system to work in ajax. I'm trying to establish the 'upvote' and have my onclick function call my route and insert a vote accordingly, except nothing happens. I can't see why or where I'm going wrong.
JAVASCRIPT
$( document ).ready(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-up-on.png" />');
$.ajax({
type: "POST",
url: "http://domain.com/knowledgebase/upvote",
dataType: "json",
data: {id : id},
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
if (name=='down')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-down-on.png" />');
$.ajax({
type: "POST",
url: "downvote",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
ROUTE.PHP
Route::get('knowledgebase/upvote/{id}', 'PostController#upvote');
POSTCONTROLLER.PHP
public function upvote($id)
{
if (Auth::user()) {
if (Request::ajax()) {
$vote = "1";
$user = Auth::user()->id;
$post = Post::find($id);
$checkvotes = Vote::where('post_id', $post->id)
->where('user_id', $user)
->first();
if (empty($checkvotes))
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post->id;
$entry->vote ="1";
$entry->save();
}
}
}
else
{
return "Not an AJAX request.";
}
}
You are using post in your jquery, but you are waiting for a GET route.
Use...
Route::post('knowledgebase/upvote/{id}', 'PostController#upvote');
Additionally, the way you are handling your route may not work correctly with the id. It would be expecting the id in the URL so what you can do is append your id to the url when setting up the ajax.
url: "http://domain.com/knowledgebase/upvote/"+id,
Or not use it at all, take the {id} portion out of your route, and grab it using Input::get('id');