1

I am trying fetch data on-click on a button.

This is how I return data in my controller:

public function fetch()
    {
        $channels = Channel::where('channel', \Auth::user()->username)
            ->orderBy('created_at','desc')->take(3)->get();

        View::share ('channels', $channels);
    }

And this is the jQuery file:

$( document ).ready(function() {
     $('#dropdownMenu').click(function() {
          $.ajax({
              type: "GET",
              dataType: "html",
              url: "channels/fetch",
              beforeSend: function() {
                    $('.testdropdown').html('loading please wait...');
              },
              success: function(htmldata) {
                  console.log(htmldata);
              }
          });
      });
 });

'loading please wait' part is working but on success, I couldn't make it prompt. What I am missing?

6
  • you have your dataType set to html and your are returning a php object in a view. You should just return $messages->toJson(); and set your ajax dataType: 'json', then parse the json with your javascript to populate your dropdown $.each(data,function(i,obj){ .. Commented Oct 17, 2015 at 19:45
  • like return response()->json(['channels' => $channels ], 200; ? Commented Oct 17, 2015 at 19:50
  • 1
    no first you should not load a view from the controller as you are just sending back data from your ajax request into the existing view thats the whole point of an ajax request. So drop view(.. for return $messages->toJson(); and then change your ajax dataType to 'json', and use the jquery $.each function to populate the values and labels of your dropdown Commented Oct 17, 2015 at 19:51
  • So I should change the View::share ('channels', $channels); to $messages->toJson(); return $messages and change dataType to 'json'? Commented Oct 17, 2015 at 19:54
  • 2
    to return $messages->toJson(); and dataType: "json" Commented Oct 17, 2015 at 19:56

1 Answer 1

3

Your Laravel method:

public function fetch()
{
  $username = \Auth::user()->username;

  $channels = Channel::where('channel', $username)->orderBy('created_at', 'desc')->take(3)->get();

  // Return as json
  return Response::json($channels);
}

And your javascript.

$(document).ready(function() {

  $('#dropdownMenu').on('click', function() {

    // Add loading state
    $('.testdropdown').html('Loading please wait ...');

    // Set request
    var request = $.get('/channels/fetch');

    // When it's done
    request.done(function(response) {
      console.log(response);
    });


  });

});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.