27

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.

12 Answers 12

60

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));
6
  • 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? Feb 20, 2015 at 18:07
  • If I do this return response()->json(array('success' => true, 'html'=>'<div>hello</div>')); it outputs expected. Feb 20, 2015 at 18:12
  • 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. Feb 20, 2015 at 18:35
  • Now I tried it on a fresh installation and it worked perfectly fine. Maybe try updating Laravel (composer update) Feb 20, 2015 at 18:39
  • composer update didnt fix the issue. Im running laravel/framework (v5.0.6) Feb 20, 2015 at 18:51
8

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) );
2
  • Thanks this solution worked for me. You saved my day. Thanks a lot Jun 26, 2017 at 12:58
  • @SanjaySharma You are very welcome. The render method saved me more than once!
    – Maky
    Jun 27, 2017 at 13:07
5

use string function before view file name like as

return (String) view('Company.allUserAjax');
4
$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!

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.

2

If you use AJAX in Laravel then when you want to display view with AJAX response don't use return command instead use echo command.

For example, don't use:

return view('ajax', ['ajax_response'=> $response]);

use:

echo view('ajax', ['ajax_response'=> $response]);

Other example, don't use:

$view = view("job.userjobs",compact($userjobs))->render();
return response()->json(['html'=>$view]);

use:

$view = view("job.userjobs",compact($userjobs))->render();
echo response()->json(['html'=>$view]);
1

Ok - I found by trial and error that you don't include the blade template commands in the view file for this to work.

I had:

@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

and now its working with:

<table class="table table-striped">
    <tbody>
    <?php foreach ($userjobs as $userjob){?>
        <tr>
            <td><strong><?php echo $userjob->title; ?></strong><br />
            <?php echo $userjob->description; ?>
            </td>
        </tr>
    <?php } ?>
</table>

Altho I searched - I never found documentation stating this.

0

remove this if condition and see if it works

if(Request::isMethod('post') && Request::ajax()) {
0
0

idk if you are still looking for answer but i ran into same issue as you, it kept returning blank. the key to success was to remove @section @endsection part in your partial view

0

This helped me:

echo view('ajaxView')->with(['value' => 'some value']);

I have used echo view('ajaxView') instead return view('ajaxView').

0

I got it working without these : @section & @stop

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

either

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

or this

$returnHTML = view('job.userjobs',compact($userjobs))->render();// or method that you prefere to return data + RENDER is the key here`

both worked

0
$view = view("job.userjobs",compact($userjobs))->render();
return response()->json(['html'=>$view]);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.