user10074403
user10074403

Reputation:

How to return the view in ajax in Laravel

We are using ajax to call the controller in Laravel. Like:

$.ajax({
  type: 'POST',
  url: "url/url/",
  data: {
    _token: '{{ csrf_token() }}',
    action: 'get-some-view',
    data: {}
  },
  success: function(data) {
    $("#container").html(data.html);
  }
});

We are hoping to do something like this on the controller:

return response()->json( [ 'code' => 0, 'data' => view('viewname')->with('foo ', $foo ), 'msg' => 'YEH!' ] , 200);

But the response we are getting is

Object { code: 0, data: {}, msg: "YEH" }

Our expected output is the HTML generated on view. Is this possible?

Upvotes: 0

Views: 96

Answers (3)

Mohammad Saiful
Mohammad Saiful

Reputation: 386

view() function just creates an instance of the View class. For rendering HTML string use render() function.

$data = view('viewname')->with('foo', $foo)->render();
return response()->json( [ 'code' => 0, 'data' => $data, 'msg' => 'YEH!' ] , 200);

Upvotes: 1

rajathans
rajathans

Reputation: 197

The render() method will give you the raw HTML.

Check out the method here View

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

You need to render the view to get the HTML. Should be -

view('viewname')->with('foo ', $foo )->render()

SO render() description

Upvotes: 2

Related Questions