简体   繁体   中英

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

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.

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));

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) );

在查看文件名之前使用字符串函数,如

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

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.

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]);

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.

删除这个 if 条件,看看它是否有效

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

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

This helped me:

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM