Tuesday 18 August 2015

JQuery serialize() function with $.ajax() post for bigger HTML forms

JQuery provides a very useful function jQuery.serialize() which encodes a set of form elements as a string for submission, and is very useful while we are dealing with huge HTML forms. Basically it will combine your values of form element and then you can post it on any server side scripting page.

For example, suppose you have a very long form with many fields and you want to post it with the help of $.ajax() function, you need to add just few lines of code for jquery from with ajax, no need to add id attribute to any form elements, just have to give id to form itself as follows:

<form name="frm_details" id="frm_details" method="post">
<input type="text" name="name" value="jems">
<input type="submit" name="submit" value="submit">
</form>

The above form will have all the fields like text boxes, text areas, select boxes, radios etc. having only name attribute, just as our usual html form. Now the JQuery code will be as follows:
<script>
 $(function() {
   $("#product_details").on("submit", function(event) {
      event.preventDefault();

      $.ajax({
         url: "somefile.php",
         type: "post",
         data: $(this).serialize(),
         success: function(d) {
           alert(d);
         }
      });
    });
  });
</script>

No comments:

Post a Comment