Appending to a div will need to be done in javascript. Assuming you are using jquery, on the success handler of your .ajax call do something like
$('#yourdiv').append(data)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi. I have a working site that's doesn't use Ajax yet. I wan't to change that. So being able to render views and return them works perfectly for me. I'm using this code:
$returnHTML = view('urls.myUrls')->with('url_database', $url_database)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
The example above works perfectly to return some html and append it on a div. However, if a user types in the url: www.mySite.com/urls/myurls with the code above, the user just get some json - it's not appended to a div.
What can i do to change this?I hope won't have to make 2 views. .. 1 for Ajax call, and 1 for accessing the page directly..
Thank you so much.
@renec112 , if you want your controller action to respond to both AJAX and HTTP requests, you have to code it explicitly like so:
public function index(Request $request)
{
if($request->ajax()){
$returnHTML = view('urls.myUrls')->with('url_database', $url_database)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
return view('my_partial_page_with_layout')->with('url_database', $url_database)
}
Note how you return the whole page (including layout) for a direct HTTP request, and just the partial (excluding layout) for an AJAX request.
Organize your view file such that you include the ajax partial within it like so:
@extends('layout.master')
@section('content')
@include('urls.myUrls')
@endsection
Hope this helps!
Please or to participate in this conversation.