sebastian.virlan's avatar

Html block or JSON from ajax response?

Hi guys, how is best practice to return data from a controller through ajax?

  • html block
  • JSON

If html block is easy, because you only append the response to a container, but if JSON how do I build the html? Also I have and pagination.

There must be somehow to get the html from a partial because I don't think is a good idea to have html in js variables.

0 likes
5 replies
willvincent's avatar

I think the best answer is "it depends"

If you're using something like angular, ember, vue, etc.. then a json response probably makes the most sense as those would (most likely) define their own templates and have the logic in place to loop through results and build the new elements.

If you're just added on something fairly basic with vanilla javascript or jquery -- returning a block of html is pretty easy to work with and just inject into the dom in the correct place.

1 like
jekinney's avatar

In order to use plugins like Ckeditor you save the text as HTML and output unescaped data.

So same may apply, as as always depends too.

With out more info and code you can loop through the Ajax results in JavaScript and if a parameter applies set a className on the element which will replace the default className you have in your HTML if it's just CSS your looking to change. You can also set inline styles too if that's what you need.

1 like
matthallett's avatar
Level 2

Advantage of passing HTML is that you can use a view, just like if it were an actual page, and can use all the advantages of blade etc. Except you'd only return the necessary HTML rather than an entire page.

As part of your AJAX response, you can then pass...

$html = view('foo.bar', compact('foobar'))->render();

The render bit is the important part, which isn't normally used when returning views.

And then in the JS/Jquery you can inject that HTML into the appropriate div.

2 likes
Reached's avatar

Hi @matthallett ,

That's great advice for cleaning up your javascript! I had one really messy javascript file, that was handling some JSON from my server, now I extracted it to it's own seperate file that I return when the request is successful instead, that's working perfectly, thank you very much :)!

Please or to participate in this conversation.