Skip to content

Instantly share code, notes, and snippets.

@davestewart
Created April 29, 2015 23:00
Show Gist options
  • Save davestewart/1db1c4b56a85fc46e1f8 to your computer and use it in GitHub Desktop.
Save davestewart/1db1c4b56a85fc46e1f8 to your computer and use it in GitHub Desktop.

Revisions

  1. davestewart created this gist Apr 29, 2015.
    82 changes: 82 additions & 0 deletions laravel-ajax.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,82 @@
    /**
    * Laravel / jQuery AJAX code example
    * See conversation here: http://laravel.io/forum/04-29-2015-people-asking-about-jquery-ajax
    *
    * Drop this code into your App/Http/routes.php file, and go to /ajax/view in your browser
    * Be sure to bring up the JavaScript console by pressing F12.
    */

    // This is your View AJAX route - load this in your browser
    Route::get('/ajax/view', function () {

    // really all this should be set up as a view, but I'm showing it here as
    // inline html just to be easy to drop into your routes file and test
    ?>

    <!-- jquery library -->
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

    <!-- pass through the CSRF (cross-site request forgery) token -->
    <meta name="csrf-token" content="<?php echo csrf_token() ?>" />

    <!-- some test buttons -->
    <button id="get">Get data</button>
    <button id="post">Post data</button>

    <!-- your custom code -->
    <script>

    // set up jQuery with the CSRF token, or else post routes will fail
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

    // handlers
    function onGetClick(event)
    {
    // we're not passing any data with the get route, though you can if you want
    $.get('/ajax/get', onSuccess);
    }

    function onPostClick(event)
    {
    // we're passing data with the post route, as this is more normal
    $.post('/ajax/post', {payload:'hello'}, onSuccess);
    }

    function onSuccess(data, status, xhr)
    {
    // with our success handler, we're just logging the data...
    console.log(data, status, xhr);

    // but you can do something with it if you like - the JSON is deserialised into an object
    console.log(String(data.value).toUpperCase())
    }

    // listeners
    $('button#get').on('click', onGetClick);
    $('button#post').on('click', onPostClick);

    </script>

    <?php
    });

    // this is your GET AJAX route
    Route::get('/ajax/get', function () {

    // pass back some data
    $data = array('value' => 'some data');

    // return a JSON response
    return Response::json($data);

    });

    // this is your POST AJAX route
    Route::post('/ajax/post', function () {

    // pass back some data, along with the original data, just to prove it was received
    $data = array('value' => 'some data', 'input' => Request::input());

    // return a JSON response
    return Response::json($data);
    });