Nitish Kumar Nitish Kumar - 4 months ago 7
Ajax Question

How to add/include views in Laravel using Ajax

I'm bit stuck at a place. I've got some views of small

HTML sections
which when combined gives the complete HTML page. I'm trying to build a
website builder
with
Jquery
, where I'm having a
drop event
which adds those particular
views
:

For example I've got
HTML
for
slideshow
:

<div id="slideshow" data-nitsid="2">
<div class="revolution-slider">
<ul>
<!-- SLIDE -->
@foreach($contents->slider as $sliders)
<li data-transition="{{ $sliders->transition }}" data-slotamount="{{ $sliders->slotamount }}" data-masterspeed="{{ $sliders->masterspeed }}">
<!-- MAIN IMAGE -->
<img src="{{ URL::asset($sliders->url) }}" alt="">
</li>
@endforeach
</ul>
</div>
</div>


In my
JQuery
code:

nitsbuilder.dropeventhandler = function ($item, $position) {
var nits_id = $item.data('nitsid');
$.ajax({
method: 'POST',
url: dropurl,
data: { nits_id: nits_id, _token: token},
dataType: 'json',
success: function (data) {
nitsbuilder.adder($item, $position, data);
}
});

}


Before I was having
html codes
in the
database
so it was easier to pull out the html and add to the HTML page, now I'm having
html in views
, how can I
push/include
this
HTML code
or
view
to
ajax request
so that my nitsbuilder.adder function executes placing the view through my controller.

My present
Controller
is:

class DropeventController extends Controller
{
public function htmlcode(Request $request)
{
$pluginid = $request['nits_id'];
$code = Plugins::findOrFail($pluginid);
$htmlcode = $code->code;
return response()->json(['htmlcode' => $htmlcode]);
}

}


Please guide me. Thanks

Answer

You can easily create html strings from blade views using \View::make

e.g. let's assume you have the following folder strucutre

  • project
    • ...
    • ressources
    • views
      • snippets
      • snippetA
      • snippetB

You could now create a route / controller accepting a "name" parameter and then do the following

$name = "snippetA"; // get this from parameters

$html = \View::make("snippets.$name")->render();

You might need to also add variables depending on your views

$name = "snippetA"; // get this from parameters
$errors = []; // error variable might be needed

$html = \View::make("snippets.$name", compact('errors'))->render();

You can then return this html string

return ['html' => $html];

And access it from your ajax done function.

I hope this helps

Comments