JQuery Send Ajax Request With ‘delete’ Method (Two Approaches)

Knowledge point:

$.post( url [, data ] [, success ] [, dataType ] ) is a shorthand Ajax function, which is equivalent to:
$.ajax({
type: ‘POST’,
url: url,
data: data,
success: success,
dataType: dataType
});

Two approaches:

1. a form with a hidden field ‘_method’ set to ‘delete’ and use JQuery $.post method:

1.1 form code:

<form action=”test url” accept-charset=”UTF-8″ method=”post” class=”form_example”>
  <input type=”hidden” name=”_method” value=”delete” />
  <label for=”Please_enter_the_username_that_you_want_to_delete:”>Please enter the username that you want to delete:   </label>
  <input type=”text” name=”name” id=”name” />
  <input type=”submit” name=”commit” value=”Send delete request” />
</form>

1.2 JQuery code:

$(‘.form_example’).submit(function(e) {
  var $this = $(this);
  var form = $this;
  var data = form.serialize();

  // Prevent form form submit normally
  e.preventDefault();

  // Use ajax to submit the form
  $.post(form.attr(‘action’), data).done(function(data) {
  // If ajax request succeed, code goes here
  });
});

2. a form without ‘_method’ hidden field and use JQuery $.ajax method with ‘type’ set to ‘delete’:

2.1 form code:

<form action=”test url” accept-charset=”UTF-8″ method=”post” class=”form_example”>
  <label for=”Please_enter_the_username_that_you_want_to_delete:”>Please enter the username that you want to delete:  </label> 
  <input type=”text” name=”name” id=”name” /> 
  <input type=”submit” name=”commit” value=”Send delete request” />
</form>

2.2 JQuery code:

$(‘.form_example’).submit(function(e) {
  var $this = $(this);
  var form = $this;
  var data = form.serialize();

  // Prevent form form submit normally
  e.preventDefault();

  // Use ajax to submit the form
  $.ajax({
    type: ‘delete’,
    url: url,
    data: data,
    success: success,
    dataType: dataType
  });
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s