How can I return a view from an AJAX call in Laravel 5?

84,027

Solution 1

The view() function just creates an instance of the View class. Not just an HTML string. For that you should call render():

$returnHTML = view('job.userjobs')->with('userjobs', $userjobs)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));

Solution 2

if your ajax is correct and you are getting results from your DB

 $returnHTML = view('job.userjobs',[' userjobs'=> $userjobs])->render();// or method that you prefere to return data + RENDER is the key here
            return response()->json( array('success' => true, 'html'=>$returnHTML) );

Solution 3

use string function before view file name like as

return (String) view('Company.allUserAjax');

Solution 4

Don't return your view as JSON, just return the view from your controller For example:

$view = view("<your url>",compact('data'))->render();
return $view;

This will work for sure.

Solution 5

$returnHTML = view('job.userjobs')->with('userjobs', $userjobs)->renderSections()['content'];

So this question is old and the most upvoted answer did not solve the problem for the asker and for me neither. I ran into the same problem and it took me two days to find the solution. Everywhere I came looking for answers the said use ->render(). But nothing returned. I have a partial view which I wanted to include. I had not extended my partial view or given it a section name. Since this is not necessary when including it inside a blade file with the include directive.

So the solution is, enclose your html inside a section and instead of render(), use renderSections()['sectionname']. Just using render() will not work.

I hope this will safe somebody some time and frustration!

Share:
84,027

Related videos on Youtube

Chris Jackson
Author by

Chris Jackson

PHP programmer in Oklahoma City Oklahoma.

Updated on March 04, 2020

Comments

  • Chris Jackson
    Chris Jackson about 4 years

    I'm trying to get an html table to return on an ajax call.

    route:

    Route::post('job/userjobs', 'JobController@userjobs');  
    

    ajax on calling page:

    function getUserJobs(userid) {
        $_token = "{{ csrf_token() }}";
        var userid = userid;
        $.ajax({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
            url: "{{ url('/job/userjobs') }}",
            type: 'POST',
            cache: false,
            data: { 'userid': userid, '_token': $_token }, //see the $_token
            datatype: 'html',
            beforeSend: function() {
                //something before send
            },
            success: function(data) {
                console.log('success');
                console.log(data);
                //success
                //var data = $.parseJSON(data);
                if(data.success == true) {
                  //user_jobs div defined on page
                  $('#user_jobs').html(data.html);
                } else {
                  $('#user_jobs').html(data.html + '{{ $user->username }}');
                }
            },
            error: function(xhr,textStatus,thrownError) {
                alert(xhr + "\n" + textStatus + "\n" + thrownError);
            }
        });
    }
    
    
    
    //on page load
    getUserJobs("{{ $user->id }}");
    

    controller:

    public function userjobs() {
        $input = Request::all();
        if(Request::isMethod('post') && Request::ajax()) {
            if($input['userid']) {
                $userjobs = Userjob::select('select * from user_jobs where user_id = ?', array($input['userid']));
                if(! $userjobs) {
                    return response()->json( array('success' => false, 'html'=>'No Jobs assigned to ') );
                }
                $returnHTML = view('job.userjobs')->with('userjobs', $userjobs);
                return response()->json( array('success' => true, 'html'=>$returnHTML) );
    
            }
        }   
    }
    

    view:

    @section('content')
    <table class="table table-striped">
        <tbody>
    @foreach ($userjobs as $userjob)
            <tr>
                <td><strong>{{ $userjob->title }}</strong><br />
                {{ $userjob->description }}
                </td>
            </tr>
    @endforeach
    </table>
    @stop
    

    Im not getting anything in the json.html data. nothing. If in the controller I say:

    return response()->json( array('success' => true, 'html'=>'<span>html here</html>') );
    

    This works just fine.

    How can I return a view from an ajax call in Laravel 5.

  • Chris Jackson
    Chris Jackson about 9 years
    ok - a added the ->render() to the view like stated above. But Im still not getting any html in the output. Here is the console output: Object {success: true, html: ""}. any more ideas?
  • Chris Jackson
    Chris Jackson about 9 years
    If I do this return response()->json(array('success' => true, 'html'=>'<div>hello</div>')); it outputs expected.
  • lukasgeiter
    lukasgeiter about 9 years
    Hmm ye I can't get it working either... It seems that calling render() automatically outputs the content and doesn't just return it as string. This was different in Laravel 4 and I'm not sure if this is a feature or a bug.
  • lukasgeiter
    lukasgeiter about 9 years
    Now I tried it on a fresh installation and it worked perfectly fine. Maybe try updating Laravel (composer update)
  • Chris Jackson
    Chris Jackson about 9 years
    composer update didnt fix the issue. Im running laravel/framework (v5.0.6)
  • lukasgeiter
    lukasgeiter about 9 years
    what do you get when you do dd($returnHTML)?
  • Sanjay Sharma
    Sanjay Sharma almost 7 years
    Thanks this solution worked for me. You saved my day. Thanks a lot
  • Maky
    Maky almost 7 years
    @SanjaySharma You are very welcome. The render method saved me more than once!