When request is ajax, i am rendering content section and inserting it to DOM. It is working as expected.
However.. i can't find out the way, how to render multiple sections, like content and title and more in the same time.
Controller:
public function awesome(Request $request) {
if($request->ajax()){
return view('awesome')->renderSections()['content'];
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data);
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
layouts.app
<title>@yield('title')</title>
<meta name="description" content="@yield('desc')"/>
<a data-request="push" title="AWESOME" href="<?= url('/'); ?>/awesome">Awesome</a>
<a data-request="push" title="RANDOM" href="<?= url('/'); ?>/random">Random</a>
<div id="content">
@yield('content')
</div>
Blade:
@extends('layouts.app')
@section('title', 'Awesome')
@section('desc', 'About awesome')
@section('content')
some text from awesome page
@endsection
Question:
How to render both or more of them in same time? Should i use an array or something else? Please give example or full explanation.
Thanks for any answers.
You can just send a json object of title and content, and then use JS to parse the array and extract both sections. Like so:
Controller
public function awesome(Request $request) {
if($request->ajax()){
$view = view('awesome')->renderSections();
return response()->json([
'content' => $view['content'],
'title' => $view['title'],
]);
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data.content);
document.title = data.title;
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});