How to use AJAX with Laravel?

Asked

Viewed 7,584 times

6

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 sorting pattern to a PHP page that would print out this sorted list for me...

But how do I do that with Laravel? I’ll have to generate one view? I tried but I couldn’t...

I was trying here I think I’m missing the time to generate the views..

I have a layout view 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 within 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’s never entering Request::ajax() and I can’t figure out why

  • 1

    put part of your code there.

  • 1

    I edited my answer to explain how Ttu does it based on your code.

4 answers

3

You don’t have a problem with Laravel. You have to do the same thing, take the events with javascript and assemble the result the same way you did before Laravel.

In the Laravel you will take your function that makes the select and do something more or less like this

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

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

In the javascript you should take this json and treat to update the table

As you are returning all 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 a extends in your view

in your controller you will until you can change leaving it so

   $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 your two situations, when it is or not ajax.

  • So I’m trying to return a view the problem is that it’s returning the layout together where it wasn’t meant to return.. I will edit with the controller code for you to take a look at

  • then the problem is that Return View::make('usuarios.index', $variables); I can’t return only that it doesn’t show up and if I do so $this->layout->content = View::make('usuarios.index', $variables); it duplicates the layout, There’s something else he’s not ordering...

  • my Input::get() is always coming null, how do I get the data via post?

  • only being able to pick up the data when sending via get

  • You’ve seen the part you have to change in your layout?

  • yes I changed it look how it turned out http://pastebin.com/VTVSqdV2

  • I think that’s what J. Bruni commented must be missing the header

  • however I cannot do the Identifiable as ajax

  • thanks a lot for the help daniel managed to do the way you said was missing only the header to clarify that it was an ajax request

  • Blz, that bvom that managed

Show 5 more comments

2


It’s just gonna get into Request::ajax() when the request is made via Ajax! :-)

But, attention: this is checked through the HTTP header HTTP_X_REQUESTED_WITH. That one header is automatically sent in Ajax requests made by jQuery and other Javascript libraries, but if you are not using 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 normal requests, and leave out the if (Request::ajax())

  • this XHR would be the xmlhhtp object?

  • put right after the open plus the Standard does not yet identify as ajax

  • got face vlw ai actually the header needed is that OBJECT.setRequestHeader("X-Requested-With", "Xmlhttprequest");

2

I don’t understand of lavarel, work with the zend and I imagine that it works basically the same way, in ajax, you’re going to have to make some kind of request to have that return, ie in your controller will be necessary to create a action just to meet this request, and a view to assemble the content...if I were doing in zend, I would have to give one disable layout so that it uses only the specific view content, probably in lavarel this also has to be done...

0

It’s basically the same thing, just swap the directories and insert the token in the form submission, follow 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 !');
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.