Home > database >  Filter product list using Ajax in Laravel
Filter product list using Ajax in Laravel

Time:04-29

I am implementing product filtering for my project. It works properly in product.main.blade. But when doing it in product.list.blade with the same code structure, the system gives the error "SyntaxError: Unexpected token < in JSON at position 0". As far as I know the cause is the data is not of type JSON. I think the problem lies in the routings causing the data not to be sent. So can anyone help me fix it? Thanks very much!

My Controller:

function ajax_sort(Request $request)
{
    $cat_id = $request->cat_id;
    $select = $request->sort;
    $data=array(
        'cat_id'=>$cat_id,
        'select'=>$select
    );
           
    echo json_encode($data);

    
    
}

Jquery code:

$("form select").change(function() {

    var cat_id = $("#cat-tilte").attr('data-id');
    var sort = $(this).val();
    var data = { cat_id, sort: sort };
    $.ajax({
        url: "ajax_sort",
        method: 'GET',
        data: data,
        dataType: 'json',
        success: function(data) {
            console.log(data);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }

    });
});

And the routes I set up:

Route::get('product/list/{cat_id}',[ProductController::class,'list']);
Route::get('product/main',[ProductController::class,'main']);
Route::get('product/ajax_sort',[ProductController::class,'ajax_sort']);

Edit: The reason is that the URL and Route are incorrect, I have fixed it.

CodePudding user response:

It seems like you have missed this part in your code:

var data = { cat_id:cat_id, sort: sort };

CodePudding user response:

I found the mistake in the url:

$("form select").change(function() {

    var cat_id = $("#cat-tilte").attr('data-id');
    var sort = $(this).val();
    var url = route('product.ajax_sort', cat_id);
    var data = { sort: sort };
    console.log(url);
    $.ajax({
        url: url,
        method: 'GET',
        data: data,
        dataType: 'json',
        success: function(data) {
      
            $(".result-sort").html(data.result);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }

    });
});
  • Related