pavelpie
4/17/2015 - 7:21 AM

laravel.js

/*
<a href="posts/2" data-method="delete"> <---- We want to send an HTTP DELETE request

- Or, request confirmation in the process -

<a href="posts/2" data-method="delete" data-confirmation="Are you sure?">
*/

(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 form;

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

      // Allow user to optionally provide data-confirm="Are you sure?"
      if ( link.data('confirmation') ) {
        if ( ! laravel.verifyConfirm(link) ) {
          return false;
        }
      }

      form = laravel.createForm(link);
      form.submit();

      e.preventDefault();
    },

    verifyConfirm: function(link) {
      return confirm(link.data('confirmation'));
    },

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

      var token = 
      $('<input>', {
        'type': 'hidden',
        'name': 'csrf_token',
          'value': '<?php echo csrf_token(); ?>' // hmmmm...
        });

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

      return form.append(token, hiddenInput)
                 .appendTo('body');
    }
  };

  laravel.initialize();

})();

//Minified:
/*

!function(){var a={initialize:function(){this.methodLinks=$("a[data-method]"),this.registerEvents()},registerEvents:function(){this.methodLinks.on("click",this.handleMethod)},handleMethod:function(b){var e,c=$(this),d=c.data("method").toUpperCase();if(-1!==$.inArray(d,["PUT","DELETE"])){if(c.data("confirmation")&&!a.verifyConfirm(c))return!1;e=a.createForm(c),e.submit(),b.preventDefault()}},verifyConfirm:function(a){return confirm(a.data("confirmation"))},createForm:function(a){var b=$("<form>",{method:"POST",action:a.attr("href")}),c=$("<input>",{type:"hidden",name:"csrf_token",value:"<?php echo csrf_token(); ?>"}),d=$("<input>",{name:"_method",type:"hidden",value:a.data("method")});return b.append(c,d).appendTo("body")}};a.initialize()}();






/*