Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

renec112's avatar

Ajax returns json. Doesn't append it.

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.

0 likes
4 replies
gator's avatar

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)
renec112's avatar

@gator you are right and that works perfectly when i run this code:

<script type="text/javascript">
$('select').change(function(){
var data = $(this).children('option:selected').data('id');

$.ajax({
    type    :"POST",
    url     :"urls/myurls",
    dataType:"html",
    data    :{ data1:data },

    success :function(response)
    $('#yourdiv').append(html);
    }),
});
</script>

But this only works if the div is already loaded with the scripts and all that. But if a user opens the browser and types www.mySite.com/urls/myurls, the layout doesn't get rendered, and the html doesn't get appneded. Instead, the user just see some json /:

gator's avatar
gator
Best Answer
Level 16

@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!

renec112's avatar

Thank you so much! Runs like a charm ! :)

Please or to participate in this conversation.