Laravel PHP foreach中的Ajax成功数据使用

时间:2019-06-19 08:51:29

标签: php ajax laravel

我得到了ajax数据,现在我想在PHP中为每个函数使用数据,我需要再次对MySQL查询和每个函数使用数据

我的ajaxcode:

<script>
filter_data();

function filter_data()
{
    $('.filter_data').html('<div id="loading" style="" ></div>');
    var action = 'fetch_data';
    var minimum_price = $('#hidden_minimum_price').val();
    var maximum_price = $('#hidden_maximum_price').val();
    var brand = get_filter('brand');
    var category = get_filter('category');
    var discount = get_filter('discount');

    $.ajax({
        url: "{{ url('/ajaxFilterProduct') }}",
        method: "POST",
        data: {
            action: action, 
            minimum_price: minimum_price, 
            maximum_price: maximum_price, 
            brand: brand, 
            category: category, 
            discount: discount
        },
        success: function (data) {
            $('.filter_data').html(data);
        }
    });
}
</script>

我想要的laravel刀片式服务器:

@foreach($data as $data)
    echo $data->id;
@endforeach

我的laravel控制器:

<?php
public function Product_filterBy_Ajax(Request $request) {
    $query = DB::table('products')->where('available', '=', "Yes");

    $minPrice = $request->minimum_price;
    $maxPrice = $request->maximum_price;
    //$query->where([  ['p_price', '>=', $minPrice],  ['p_price', '<=', $maxPrice], ]);

    $query->whereBetween('p_price', [$minPrice, $maxPrice]);

    $brand = $request->brand;

    if (!empty($brand)) {
        $collection = collect($brand);
        $query->whereIn('p_com_name_dis', $collection);
    }

    $category = $request->category;

    if (!empty($category)) {
        $collection = collect($category);
        $query->whereIn('p_sub_type', $collection);
    }

    $discount = $request->discount;

    if (!empty($discount)) {
        $collection = collect($discount);
        $query->whereIn('p_discount', $collection);
    }

    $result = $query->get();
    $count_result = $result->count();

    return $result;
    // if ($count_result > 0) {

    //  //return View::make("wecommerce/products_filter", ["jobs" => $generatedData]);
    //   return view('wecommerce/products_filter', compact('result'));

    // } //==end if

    //dd($result);

}  //==END FILTER PRODUCT==//
?>

1 个答案:

答案 0 :(得分:0)

您可以将jQuery中的每个函数用作

   success: function(result) {
     $.each(data, function(v) {
                    var val = data[v];
                    formoption += "<option value='" + val['id'] + "'>" + val[
                        'name'] + "</option>";
                });