简体   繁体   中英

Can't get data in laravel controller that sent from ajax

I have a route,

Route::post('/shop', 'ShopController@index');
Route::resource('/shop', 'ShopController')->parameters(['shop' => 'slug']);

I want to filter products via price range.

this is my:

filter_data();
        var sliderrange = $('#slider-range');
        var amountprice = $('#amount');
        function filter_data() {
            var  min_price = $("#min_price").val();
            var  max_price = $("#max_price").val();
            console.log(min_price);
            $.ajax({ url:"/shop", method:"GET",
                data:{ min_price:min_price, max_price:max_price,},
                success:function (data) { },
            });
        };

and this is the controller:

    public function index(Request $request)
{
    $min = $request->input('min_price');
    $max = $request->input('max_price');

    return view('front.pages.shop', ['products' => Product::where('status', 1)->whereBetween('price', ['min', 'max'])->latest()->paginate(15)]);
}

Apparently the problem is that the controller isnt returning the correct data (As far as i can tell.)

The first step in debugging such a issue is checking if the parameter youre using to query are actually filled.

This can be done like this: dd($min, $max)

If the output of the dd function shows empty values the issue is withtin the ajax request. If they are set you want to do the following:

public function index(Request $request)
{
    $min = $request->input('min_price');
    $max = $request->input('max_price');

    $products = Product::where('status', 1)->whereBetween('price', ['min', 'max'])->latest()->paginate(15);
    dd($products);

    return view('front.pages.shop', ['products' => $products]);
}

Place your products in a variable and run the dd() function with the variable to see if you have data. When done debugging remove the dd() function.

If you have data the problem might be somewhere else.

Note: If you want to get data you should actually use the GET method for the route instead of using the POST method.

Example:

Route::get('/shop', 'ShopController@index');

I hope this is a little push in the right direction, try debugging step by step to find the exact point where there might be a issue.

What exactly is the error message you're receiving in the browser?

If the problem is related to CORS and you're using Laravel 7 you should update the config/cors.php file so that it works with your project. (eg setting 'allowed_origins' => ['*'] ).

See documentation for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM