Sto cercando di ottenere una tabella html da restituire in una chiamata Ajax.Come posso restituire una vista da una chiamata Ajax in Laravel 5
percorso:
Route::post('job/userjobs', '[email protected]');
ajax a pagina chiamando:
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 }}");
regolatore:
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));
}
}
}
vista:
@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 non ottenere nulla nei dati json.html. Niente. Se nel controller dico:
return response()->json(array('success' => true, 'html'=>'<span>html here</html>'));
Questo funziona bene.
Come posso restituire una vista da una chiamata AJAX in laravel 5.
ok - a aggiunto il -> render() alla vista come detto sopra. Ma non riesco ancora a ottenere alcun html nell'output. Ecco l'output della console: 'Object {success: true, html:" "}'. altre idee? –
Se faccio questo 'risposta di ritorno() -> JSON (array ('successo' => true, 'html' => '
Hmm ye non riesco a farlo funzionare ... Sembra che chiamare 'render()' restituisca automaticamente il contenuto e non lo restituisca semplicemente come stringa. Questo è stato diverso in Laravel 4 e non sono sicuro che questa sia una caratteristica o un bug. – lukasgeiter