mboeckle mboeckle - 1 month ago 8
PHP Question

Update Laravel View dynamically

I am loading data from an API through JS send the data to the Laravel Controller and save them into the Database. After loading all the Ajax I want to display the data in a subview/section of the master.blade - Is it possible to render a View dynamically after the page finish loading, - also for later I want to update database rows and display the new data in the view dynamically.

//afater Ajax loading - update / display the data in the view
public function loadcomments() {
$comments = Comment::all();
$childcomment = Childcomment::all();
return View::make('partial')
->with(compact('comments'))
->with(compact('childcomments'));
}


in user.blade.php (main site) I am defining

@section('comments')
@include('partial')
@stop


and in the master.blade.php I am defining the yields:



@yield('content')

@yield('comments')




any idea how to render the site with the updated content?

Answer

Once the page has finished loading, with out making further AJAX calls to the Laravel app its self it will have no further part in the request.

You could just update the front end markup with JS or you can make a call back to your Laravel application using AJAX/jQuery to pull the data back out after it has added it to the database.

Use a resource controller or similar implementation to allow insertion and reading of the comments (CRUD) so you can pull data when you need using AJAX.

Edit

There are different ways to make a page dynamic on the front end all of these will usually include Javascript or another front end scripting language.

In the past I have used jQuery to handle updates of the page content using either JSON or XML/HTML but lately I have started to use AngularJS. Another library is EmberJS which I am currently learning to use but I feel front end languages are out of scope for the question.

There are many tutorials on updating the HTML after a page has loaded by making a call back to a controller or other resourceful route.

Say the posts have been saved to the database, if this is done AFTER the view has been returned to the browser you WILL have to use javascript to pull out the data and most likely have a piece of js code to tick over that "polls" your resource controller for new comments.

If a new comment has been detected a second request is made to pull the comments out OR the comments are returned from the polling requests using AJAX.

On the laravel side, a partial view could be returned or JSON, for simplicity we'll replace the view. You would make a jQuery selector for the current existing partial on the browser and then replace it with the one pulled from Laravel with AJAX.

$('#some-page .my-view-to-update').html(somedata);

My jQuery is VERY rusty so read up on the relevant documentation to update the HTML correctly.

Comments