Skip to content

Instantly share code, notes, and snippets.

@stevemo
Forked from JeffreyWay/laravel.js
Created March 7, 2013 22:29

Revisions

  1. @JeffreyWay JeffreyWay revised this gist Mar 7, 2013. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions laravel.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,7 @@
    /*
    <a href="posts/2" data-method="delete"> <---- We want to send an HTTP DELETE request
    */

    (function() {

    var laravel = {
  2. @JeffreyWay JeffreyWay created this gist Mar 7, 2013.
    49 changes: 49 additions & 0 deletions laravel.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    (function() {

    var laravel = {
    initialize: function() {
    this.methodLinks = $('a[data-method]');

    this.registerEvents();
    },

    registerEvents: function() {
    this.methodLinks.on('click', this.handleMethod);
    },

    handleMethod: function(e) {
    var link = $(this);

    var httpMethod = link.data('method').toUpperCase();
    var allowedMethods = ['PUT', 'DELETE'];

    // If the data-method attribute is not PUT or DELETE,
    // then we don't know what to do. Just ignore.
    if ( $.inArray(httpMethod, allowedMethods) === - 1 ) {
    return;
    }

    var form =
    $('<form>', {
    'method': 'POST',
    'action': link.attr('href')
    });

    var hiddenInput =
    $('<input>', {
    'name': '_method',
    'type': 'hidden',
    'value': link.data('method')
    });

    form.append(hiddenInput)
    .appendTo('body')
    .submit();

    e.preventDefault();
    }
    };

    laravel.initialize();

    })();