Laravel Ajax Render View With Data Example

By Hardik Savani April 16, 2024 Category : Laravel

Hello Artisan,

In this example, I will show you laravel render view with data example. we will help you to give an example of laravel render partial view. you can see laravel render view to variable. We will look at an example of laravel ajax render html view.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Sometimes, we use get html view layout from ajax request. At that you have to first render view file and then you need to store view in varibale and then we can return that varibale. In bellow example i render view with pass data you can see how i did:

You can see the below example steps:

Call Ajax from Blade File:

we will call ajax request from here and getting html view from here:

Blade File:

<!DOCTYPE html>

<html>

<head>

<title>Laravel Ajax Render View With Data Example - ItSolutionStuff.com</title>

<meta name="_token" content="{{ csrf_token() }}">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

</head>

<body>

<div class="container">

<div id="messages">

</div>

<button class="loadData">Load Data</button>

</div>

<script type="text/javascript">

$(document).ready(function() {

$('body').on('click', '.loadData', function(event) {

event.preventDefault();

$.ajax({

type: "POST",

url: "{{ route('messages.list') }}",

headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

success: function (data) {

$("#messages").html(data.html);

},

});

});

});

</script>

</body>

</html>

Controller Code:

we will get html response for ajax.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Message;

class MessageController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function getMessages(Request $request)

{

$messages = Message::get();

$html = view('messages', compact('messages'))->render();

return response()->json([

'status' => true,

'html' => $html,

'message' => 'Getting messages successfully.',

]);

}

}

now, we will load messages blade file:

Blade File:

@foreach($messages as $message)

<p>{{ $message->message }}</p>

@endforeach

I hope it can help you...

Tags :
Shares