2015-02-20 11 views
7

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.

risposta

21

La funzione view() solo crea un'istanza della classe View. Non solo una stringa HTML. Per questo si dovrebbe chiamare render():

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

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? –

+0

Se faccio questo 'risposta di ritorno() -> JSON (array ('successo' => true, 'html' => '

hello
'));' esso risultati attesi. –

+0

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

0

sopprimere questa se la condizione e vedere se funziona

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

Ok - ho trovato per tentativi ed errori che non si include i comandi del modello lama nella guarda il file per farlo funzionare.

ho avuto:

@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 

e ora il suo lavoro con:

<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 Ho cercato - non ho mai trovato affermando questa documentazione. funzione di stringa

4

uso prima del nome del file vista come come

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

se l'ajax è corretto e si stanno ottenendo i risultati dal vostro 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)); 
+0

Grazie a questa soluzione ha funzionato per me. Mi hai salvato la giornata. Grazie mille –

+0

@SanjaySharma Siete i benvenuti. Il metodo di rendering mi ha salvato più di una volta! – Maky

0

idk se siete ancora alla ricerca di risposte, ma i ha avuto lo stesso problema di te, ha continuato a restituire vuoto. la chiave del successo è stata la rimozione della parte @section @endsection nella vista parziale

Problemi correlati