How to use AJAX with Laravel?

I have a select that when I change its value it should reorder a list, e.g. by id, Name, etc. without Laravel I would use a function onchange and pass the sort pattern to a PHP page that would print this ordered list for me...

But how to do this with Laravel? Will I have to generate a view? I tried but couldn't...

I was trying here I think I'm wrong when generating the views..

I have a view of layout that has a @yeld ('content'), in case I would need to update only this content, however, when I do:

$this->layout->content = View::make('usuarios.index', $variaveis);

It duplicates my layout inside the content div

/ / Follow controller

   if(Request::ajax()){
       $usuarios = Usuario::orderBy(Input::get('order'),'ASC')->get();
       $variaveis = array('usuarios' => $usuarios);
       return View::make('usuarios.index', $variaveis);;
   }else{
       $usuarios = Usuario::orderBy('id','ASC')->get();
       $variaveis = array('usuarios' => $usuarios);
       $this->layout->content = View::make('usuarios.index', $variaveis);
   }

However it is never entering the Request::ajax() and I can't figure out why

Author: tissei, 2014-02-06

4 answers

Will only enter Request::ajax() when the request is made via Ajax! :-)

But, attention: this is checked through the HTTP header HTTP_X_REQUESTED_WITH. This header is automatically sent in Ajax requests made by jQuery and other JavaScript libraries, but if you are not using it you need to add it so that Laravel recognizes that the call is Ajax:

XHR.setRequestHeader("X-Requested-With", "XmlHttpRequest");

Another alternative is to use different functions in the Controller: one for Ajax another for requests normal, and leave out the if (Request::ajax())

 2
Author: J. Bruni, 2014-02-06 18:27:58

Your problem is not with laravel. You have to do the same thing, take the events with javascript and mount the result the same way you did before laravel.

In laravel you will take your select function and do something like this

public function getConsulta()
{
   //tua consulta normal...  

   if (Request::ajax()) 
   {
      return Response::json($dados);
   }
}

In javascript you should take this json and treat to do the update in Table

Since you are returning all of your view and rendering all of it, you can do so in your layout

@if (!Request:: ajax ())

   // teu código normal quando não é ajax

@ else

   @yield('content') // isso vai fazer renderizar só a tua view

@endif

It is necessary to do this because you are giving an extends in your view

In your controller you will until you can change it leaving it like this

   $usuarios = Usuario::orderBy(isset(Input::get('order'))?Input::get('order'):'id','ASC')->get();
   $variaveis = array('usuarios' => $usuarios);
   return View::make('usuarios.index', $variaveis);;

Will work for both of your situations, whether or not it's ajax.

 3
Author: Daniel Lemes, 2014-02-06 13:33:39

I do not understand lavarel, i work with zend and imagine that it works basically the same way, in ajax, you will have to make some kind of request to have this return, that is, in your controller it will be necessary to create a action only to meet this request, and a view to mount the content...if I was doing in zend, I would have to give a disable layout so that it uses only the content of the specific view, probably in lavarel this also has to be done...

 2
Author: Kenny Rafael, 2014-02-06 10:42:10

Is basically the same thing, just swap the directories and insert the token into the form submission, follows an example of what I implemented here:

$.ajax({
    headers: {
        'X-CSRF-Token': $('input[name="_token"]').val()
    },
    type: 'GET',
    url: "{{ URL::to(teste/ajax) }}",
    data: 'nome='+$('input[name="nome"]').val(),
    enctype: 'multipart/form-data',
    success: function(data){
        $(location).attr('href', "{{ URL::to(Request::path()) }}");
    },
    error: function(){
        alert('Erro no Ajax !');
    }
});
 0
Author: tiaguinhow, 2014-02-06 11:18:16