How to use AJAX with Laravel?

5

I have a select that when I change the value it should reorder a list, eg by id, name, etc. without Laravel I would use a onchange function and pass the sort order to a PHP page that would print this list sorted for me ...

But how to do this with Laravel? Will I have to generate a view ? I tried but could not ...

I was trying here and I think I'm wrong to generate the views ..

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

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

It duplicates my layout within the div content

// Follow the 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);
   }

But he is never entering Request :: ajax () and I can not figure out why

    
asked by anonymous 06.02.2014 / 11:35

4 answers

2

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

But, be aware: this is checked using the HTTP_X_REQUESTED_WITH HTTP header. 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 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 normal requests, and leave out if (Request::ajax())

    
06.02.2014 / 17:51
2

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

    
06.02.2014 / 11:42
2

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

In laravel you will get your function that does select and do something like this

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

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

In javascript you should get this json and try to do the update in the table

As you are returning all your view and rendering it all, 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

You need to do this because you are giving an extends in your view

In your controller you will even be able to change leaving it thus

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

It will work for both of your situations, whether or not it is ajax.

    
06.02.2014 / 12:22
0

It's basically the same thing, just change the directories and insert the token in the form submission, here's an example of what I've 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 !');
    }
});
    
06.02.2014 / 12:18