Thursday, January 30, 2020

Submit all pages form data



Submit form:
$(document).ready(function (){
   var table = $('#example1').DataTable({
      pageLength: 4
   });

   // Handle form submission event
   $('#frm-example1').on('submit', function(e){
      var form = this;

      // Encode a set of form elements from all pages as an array of names and values
      var params = table.$('input,select,textarea').serializeArray();

      // Iterate over all form elements
      $.each(params, function(){
         // If element doesn't exist in DOM
         if(!$.contains(document, form[this.name])){
            // Create a hidden element
            $(form).append(
               $('<input>')
                  .attr('type', 'hidden')
                  .attr('name', this.name)
                  .val(this.value)
            );
         }
      });
   });
});

Submit through ajax:
$(document).ready(function (){
   var table = $('#example2').DataTable({
      pageLength: 4
   });

   // Handle form submission event
   $('#frm-example2').on('submit', function(e){
      // Prevent actual form submission
      e.preventDefault();

      // Serialize form data
      var data = table.$('input,select,textarea').serializeArray();

      // Include extra data if necessary
      // data.push({'name': 'extra_param', 'value': 'extra_value'});

      // Submit form data via Ajax
      $.post({
         url: 'echo_request.php',
         data: data
      });
   });
});
* Credit to https://www.gyrocode.com/articles/jquery-datatables-how-to-submit-all-pages-form-data/

No comments:

Post a Comment