ahmad almasri
ahmad almasri

Reputation: 59

Laravel 7 export value from ajax to blade to for loop through json

I have an ajax call from DB in JSON response like

0: {id: 1, name: "nancy", cost: 100, quantity: 4, barcode: 12345, category_id: 1,…}
1: {id: 3, name: "elissa", cost: 60, quantity: 3, barcode: 98987, category_id: 1,…}
2: {id: 4, name: "nancy", cost: 100, quantity: 32, barcode: 99999, category_id: 1,…}
3: {id: 7, name: "new one", cost: 200, quantity: 12, barcode: 66778, category_id: 1,…}
4: {id: 10, name: "new begama", cost: 70, quantity: 6, barcode: 10001, category_id: 1,…}

and I got the length

success: function (result) {//alert(typeof (result)); alert(result.length);) }),

how can I forloop on them in Blade.php

Upvotes: 0

Views: 285

Answers (1)

Ballard
Ballard

Reputation: 899

If you want to loop over these strictly in blade you will need to pass HTML back in the response instead of JSON. Otherwise you will have no choice but to loop over them in JS.

For example you'd need to create a view file which has something like this:

Make the a view with the following html in it, then put the path of this new file in the controller method below.

    @foreach($data as $item)
        {{$item->name}}
    @endforeach

Then in your controller you'd do something like this:

    public function salesHiddenCoffee(Request $request)
    {
        $category_id = $request->get('category_id');
        $products = Product::where('category_id', $category_id)->get();

        $view = view('make.a.view.the.html.above.in.it.then.put.the.path.here', ['products' => $products]);
        $html = $view->render();

        return ['success' => true, 'html' => $html];
    }

You would of course need to change your JS to digest the HTML response.

success: function (result) {
    if(result.html != undefined) {
        $(container_you_want_the_html_to_go).html(result.html);
    }
}),

Alternatively

let container = $('#ID_of_your_container');
$.each(result, function (i, item) {
    $(container).append('<div>' + item.name + '</div>');
});

Upvotes: 1

Related Questions