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.

Geoffrey
  • 5,407
  • 10
  • 43
  • 78
Chris Jackson
  • 718
  • 1
  • 6
  • 14

12 Answers12

59

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));
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • 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 Feb 20 '15 at 18:07
  • If I do this `return response()->json(array('success' => true, 'html'=>'
    hello
    '));` it outputs expected.
    – Chris Jackson Feb 20 '15 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. – lukasgeiter Feb 20 '15 at 18:35
  • Now I tried it on a fresh installation and it worked perfectly fine. Maybe try updating Laravel (`composer update`) – lukasgeiter Feb 20 '15 at 18:39
  • `composer update` didnt fix the issue. Im running laravel/framework (v5.0.6) – Chris Jackson Feb 20 '15 at 18:51
  • what do you get when you do `dd($returnHTML)`? – lukasgeiter Feb 20 '15 at 18:53
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) );
Maky
  • 521
  • 5
  • 21
5

use string function before view file name like as

return (String) view('Company.allUserAjax');
Imtiaz Pabel
  • 5,307
  • 1
  • 19
  • 24
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!

Jorn
  • 457
  • 7
  • 11
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.

Devil10
  • 1,853
  • 1
  • 18
  • 22
Reva
  • 41
  • 1
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]);
Nole
  • 796
  • 7
  • 11
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.

Chris Jackson
  • 718
  • 1
  • 6
  • 14
0

remove this if condition and see if it works

if(Request::isMethod('post') && Request::ajax()) {
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

Vishal Desai
  • 191
  • 3
  • 15
0

This helped me:

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

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

Nole
  • 796
  • 7
  • 11
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

Wahsei
  • 289
  • 2
  • 6
  • 16
0
$view = view("job.userjobs",compact($userjobs))->render();
return response()->json(['html'=>$view]);
Dharman
  • 30,962
  • 25
  • 85
  • 135
mohamed
  • 11
  • 1