Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lat4732's avatar
Level 12

Assigning blade.php file to a JS variable

Hey, @everyone!

Can I assign a blade file to a JS variable somehow? I'm trying to display content that is loaded by AJAX request:

            function searchUrl(page) {
                return '{{ url("/get/" . $website->web_seo_url . "/reviews") }}?&page=' + page;
            }

            function showResult(page = 1) {
                return $.get(searchUrl(page)).done(function (result) {
                    
                    result.data.forEach(function (review) {
                        
                        reviews = "";

                        reviews = reviews + "review" + review.id;
                        

                        $("#reviews-box").append(reviews);

                    });

                    }

                }).fail(function(xhr, status, thrownError) {
                    console.error(xhr.status, thrownError);
                });
            }

but If I need to paste my review template inside the reviews variable will be insane. Its a lot of code containing blade directives and stuff. How can I assign the review template directly to the JS reviews variable in this case? Last time doing this was literally painful... I did it like this:

var = "";
var = var + "<div class='resultbox'>";
var = var + "<span>{{ $var->name }}</span>";
// ..... A LOT OF CODE
var = var + "</div>";

Any ideas?

0 likes
27 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You can just return html code directly from the ajax request, instead of json data :) So make a route that returns a view like you would do for a normal page (except there should be no layout) and then pass that to the reviews box

$("#reviews-box").append(htmlResponse);
lat4732's avatar
Level 12

@Sinnbeck So I just create a route which returns pure HTML with my data and create an AJAX request to this route but how do I specify that the AJAX request should return pure HTML?

Sinnbeck's avatar

@Laralex Just try this

return $.get('/').done(function (result) {
                   console.log(result)

                    });
lat4732's avatar
Level 12

@Sinnbeck lawl, amazing! But how I will be able to paginate these results when it's pure html? (Hopefully you understand my question)

Sinnbeck's avatar

@Laralex Well you could perhaps send back json then, where just a key is the html

return response()->json([
       'pagination' => $paginationData,
      'html' => view('someview', compact('paginationData'))->render(),
]);
lat4732's avatar
Level 12

@Sinnbeck Also the jQuery on('click', ..) events doesn't work when I load the reviews like this. Any ideas why?

EDIT:

but I have no idea how to retrieve the paginationData

Sinnbeck's avatar

@Laralex Yeah it is just html, so it isnt "dynamic". You will need to run your "activation" on it. I assume you have some jquery to activate the click event.

Sinnbeck's avatar

@Laralex Then I assume you have a function to "active" them. Just run that after appending to the DOM

lat4732's avatar
Level 12

@Sinnbeck Yep, activated them with chaining .ready after .append(reviews)

 $("#reviews-box").append(reviews).ready(function() {
	// ....
};

And still, how do I get the $paginationData ?

Sinnbeck's avatar

@Laralex I think I already showed you? Updated example

return response()->json([
       'pagination_links' => $paginationData->links,
      'html' => view('someview', compact('paginationData'))->render(),
]);
lat4732's avatar
Level 12

@Sinnbeck Oh, I'm so dummy.. I was trying to simplify the code:

        return response()->json([
            // 'pagination' => $paginationData,
            'html' => view('ajaxViews.reviews', [
                'website' => $website,
                'reviews' => $website->reviews()->where('report_status', '!=', 3)->orderBy('created_at', 'DESC')->with('reply', 'reports')->paginate(20)
            ])->render()
        ]);

and didn't even realized that I can move everything to a variable:

        $reviews = $website->reviews()->where('report_status', '!=', 3)->orderBy('created_at', 'DESC')->with('reply', 'reports')->paginate(20);

        return response()->json([
            'pagination' => $reviews->links(),
            'html' => view('ajaxViews.reviews', [
                'website' => $website,
                'reviews' => $reviews
            ])->render()
        ]);

but this is returning me a

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$links 
Sinnbeck's avatar

@Laralex Yeah my code would give that error as I was missing (). Seems yours is correct (unless you are doing something with ->links in blade?

lat4732's avatar
Level 12

@Sinnbeck No, I'm not. The error is on this line:

  'pagination' => $reviews->links,

EDIT:

Wow, wait! My code didn't updated and I can see that it's "saved"? Ok, your suggestion to work locally and then upload is absolutely reasonable.

Sinnbeck's avatar

@Laralex Yeah as I said, my code was wrong, but you fixed it yourself in the code you posted..

 'pagination' => $reviews->links(),
lat4732's avatar
Level 12

@Sinnbeck Okay, after uploading it manually we lost the error but there is nothing inside pagination in the json returned. Maybe because there are no other pages than just 1? I'll give it a try with adding some more reviews, sec.

EDIT:

Tried adding more reviews so I can trigger second page but still nothing in pagination.

The code looks like this now:

        $reviews = $website->reviews()->where('report_status', '!=', 3)->orderBy('created_at', 'DESC')->with('reply', 'reports')->paginate(1);

        return response()->json([
            'pagination' => $reviews->links(),
            'html' => view('ajaxViews.reviews', [
                'website' => $website,
                'reviews' => $reviews
            ])->render()
        ]);
Sinnbeck's avatar

@Laralex Hmm yeah is seems it isnt possible. You can pass all pagination data, and that will work. I am just testing for a better idea

 'pagination' => $reviews,

Sinnbeck's avatar

Ah I found it in the source..

 'pagination' => $reviews->linkCollection(),
1 like
lat4732's avatar
Level 12

@Sinnbeck Well that might work. That's what I'm using to display the pagination and use its functionality:

                    var paginat = "";
                    paginat = paginat + '<nav role="navigation" aria-label="Pagination Navigation" class="pagination__wrapper add_bottom_15 flex items-center justify-between"><div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between"><div class="pagination"><span class="d-flex">';
                    // paginat = paginat + '<span class="next text-muted" aria-hidden="true">❮</span>';
                    for (let p = 1; p <= result.data.last_page; p++) {
                        if (p === result.data.current_page) {
                            paginat = paginat + '<span class="d-inline" aria-current="page"><a class="active">' + p + '</a></span>';
                        } else { 
                            paginat = paginat + '<a class="d-inline" onclick="showResult('+p+')">' + p + '</a>';
                        }
                    }

                    // if(result.data.data.next_page_url != undefined) {
                    //     paginat = paginat + '<a href="'+record.next_page_url+'"class="next">❯</a>';
                    // } else {
                    //     paginat = paginat + '<span class="next text-muted" aria-hidden="true">❯</span>';
                    // }

                    paginat = paginat + '</span></div></div></nav>';
                    
                    $(paginat).appendTo("#companies-pages");

which is unreadable at some point. But just sharing :)

lat4732's avatar
Level 12

@sinnbeck

'pagination' => $reviews->linkCollection(),

Yep, that's outputting the pagination data.

Sinnbeck's avatar

Or

 'pagination' => collect($reviews->toArray())->except('data'),
lat4732's avatar
Level 12

@Sinnbeck Yes, all of those will work in my case. What do you think about my way of using the pagination? I know its kinda unreadable but you might suggest something better

Sinnbeck's avatar

@Laralex If it works then that is fine. It can always be cleaned up a bit later :)

lat4732's avatar
Level 12

One last question - what type of route should it be? GET or POST? Also I added

if(!$request->ajax()) return back();

just for some more security. Is that ok? Its a GET route now. I know the answer is obvious, but there might be another logic behind it.

Please or to participate in this conversation.