shahr's avatar
Level 10

How to import json for display products?

My problem is when changing the slider of the range price, I see [] and an error in my console.

error

web.php

Route::get('/category/{categorySlug}', [App\Http\Controllers\CategoryController::class, 'single']);
Route::get('priceFilter', [App\Http\Controllers\CategoryController::class, 'priceFilter'])->name('priceFilter');

CategoryController.php

public function single(Category $category)
{
    $min_price = Product::min('price');
    $max_price = Product::max('price');
    $brands = Brand::query()->select('id', 'title')->get();
    $colors = Color::all();
    $categories = Category::all();
    return view('Home.contents.category', compact('min_price','max_price', 'category', 'colors', 'categories', 'brands'));
}

public function priceFilter(Category $category, Request $request)
{
    $categories = Category::all();
    $colors = Color::all();
    $brands  = Brand::all();
    $min_price = Product::min('price');
    $max_price = Product::max('price');
    $filter_min_price = $request->min_price;
    $filter_max_price = $request->max_price;
    $range = [$filter_min_price, $filter_max_price];
    $products = Product::query()->whereBetween('price', $range)->get();

    if($filter_min_price && $filter_max_price){
        if($filter_min_price > 0 && $filter_max_price > 0)
        {
            $products = Product::all()->whereBetween('price', [$filter_min_price, $filter_max_price]);
        }
    } else {
        $products = Product::all();
    }
    return response()->json($category);
    //return view('Home.contents.category',compact('products','categories','min_price','max_price','filter_min_price','filter_max_price', 'category', 'colors', 'brands'));
}

category.blade.php

@extends('Home.master')

@push('style')

	<link rel="stylesheet" href="{{ asset('themes/css/jquery-ui.css') }}">

@endpush

@section('content')

	<div class="container pb-5 pt-2">
		@include('Home.layouts.header')
		<div class="bg-title text-center">
			<span class="display-1 text-white">{{ $category->title }}</span>
		</div>
		<div class="row mt-5">
			<div class="col-lg-3">
				<div class="card mb-3">
					<div class="card-body">
						<p>
							<label for="amount">amount:</label>
							<input type="text" name="amount" id="amount" readonly class="border-0 fw-bold text-warning">
						</p>
						<div id="slider-range"></div>
					</div>
				</div>
				<div class="card mb-3">
					<div class="card-body">
						<label for="color_id" class="form-label">color </label>
						@foreach($colors as $color)
							<p class="mb-1">
								<label for="color_{{ $color->id }}" class="checkbox" data-bs-toggle="tooltip" data-bs-placement="top" title="{{ $color->name }}">
									<input type="checkbox" id="color_{{ $color->id }}" name="color_id"  value="{{ $color->id }}" onclick="colorCheckBox({{ $category->id }},this)">
									<span class="checkmark" style="background-color: {{ $color->code }}"></span>
								</label>
							</p>
						@endforeach
					</div>
				</div>
				<div class="card mb-3">
					<div class="card-body">
						<label for="brand_id" class="form-label">brand </label>
						@foreach($brands as $brand)
							<div class="form-check">
								<input class="form-check-input" type="checkbox" value="{{ $brand->id }}" id="category{{ $brand->id }}" onclick="({{ $brand->id }}, this)">
								<label class="form-check-label" for="category{{ $brand->id }}">
									{{ $brand->title }}
								</label>
							</div>
						@endforeach
					</div>
				</div>
			</div>
			<div class="col-lg-9">
				<div class="row" id="productFilters">
					@foreach($category->products as $product)
						<div class="col-lg-4 mb-3">
							<div class="card">
								<img src="{{ asset('storage/'.$product->gallery->image) }}" class="card-img-top" alt="{{ $product->title }}">
								<div class="card-body">
									<h5 class="card-title">{{ $product->title }}</h5>
									<p class="card-text">{{ \Illuminate\Support\Str::limit($product->body, 20) }}</p>
									<a href="{{ $product->path() }}" class="btn btn-primary">more info</a>
								</div>
							</div>
						</div>
					@endforeach
				</div>
			</div>
		</div>
	</div>

@endsection

@push('script')
	<script src="{{ asset('themes/js/jquery-ui.js') }}"></script>
	<script>
		$( function() {
			$( "#slider-range" ).slider({
				range: true,
				min: {{ $min_price }},
				max: {{ $max_price }},
				values: [ 0, {{ $max_price }} ],
				slide: function( event, ui ) {
					var amount = $( "#amount" ).val( " $ " + ui.values[ 0 ] + " -  $ " + ui.values[ 1 ] );
					$.ajax({
						type: 'get',
						dataType: 'html',
						url: '{{ route('priceFilter') }}',
						data: 'amount',
						success: function (response) {
							console.log(response);
							response.forEach(element => {
								$('.courseFilters').append(`<div class="col-lg-4 mb-3">
									<div class="card">
										<img src="storage/${element.galley.image}" class="card-img-top" alt="${element.title}">
										<div class="card-body">
											<h5 class="card-title">${element.title}</h5>
											<p class="card-text">${element.body}</p>
											<a href="${element.path()}" class="btn btn-primary">more info</a>
										</div>
									</div>
								</div>`);
							});
						}
					});
				}
			});
			$( "#amount" ).val( " $ " + $( "#slider-range" ).slider( "values", 0 ) + " -  $ " + $( "#slider-range" ).slider( "values", 1 ) );
		});
	</script>
@endpush
0 likes
9 replies
shahr's avatar
Level 10

@Niush I replaced this code

success: function (response) {
    $.each(response, function(index, element) {
        console.log(element);
    });
}

I see this error

err

Niush's avatar

@kerman You need to replace dataType: 'html' with dataType: 'json' , so that the response is parsed into json array. Or manually perform JSON.parse() .

shahr's avatar
Level 10

@Niush

I replace this code

success: function (response) {
    var data = JSON.parse($("#productFilters").html());
    $.each(JSON.parse, function (index, element) {
        console.log(element);
    });
}

But I see this error

error

Niush's avatar

@kerman Isn't it supposed to be JSON.parse(response). The response variable is coming in as html string from ajax, and it needs to be parsed.

success: function (response) {
    var data = JSON.parse(response);
    $.each(data, function (index, element) {
        console.log(element);
    });
}

Learn More: https://api.jquery.com/jquery.ajax/

shahr's avatar
Level 10

@Niush I see this error

Uncaught SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

Snapey's avatar

only oxbir struggling with jquery in 2022

it's like the last 5 years never happened

1 like
shahr's avatar
Level 10

Answer my question.

1 like

Please or to participate in this conversation.