Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

How to serialize the current form?

I am using jQuery to serialize the form of the submit button. But when I use the code, it removes the effect of return false and the page refreshes. And when I remove the serialization code, it works good!

I am using this:

$('input[value=Save]').click(function () {
   $.ajax({
      url: '/ajax_requests/update_info',
      data: $(this).form.serialize(),
      success: function (data) {

      }
   });
   return false;
});

I am sure I am making a mistake while using $(this).form.serialize() but I can't figure out and neither can I search it on Internet.

Upvotes: 3

Views: 2595

Answers (2)

Ram
Ram

Reputation: 144659

jQuery object doesn't have form property, you could get the form using .prop('form') but as the returned object is a DOM Element object, for using serialize() you should wrap it with jQuery, so why not:

$(this.form).serialize(),

Upvotes: 2

user229044
user229044

Reputation: 239240

Don't bind to the click event of a specific button, use the submit event of the form itself, and then your form will be this.

$('form').submit(function (event) {
  event.preventDefault()
  $.ajax({
    data: $(this).serialize()
    ...
  });
});

If you want to use the button to reach the form, as in your example, you'd use $(this).closest('form').serialize().

Upvotes: 3

Related Questions