0

I am trying to submit woocommerce products fields to cart without page refresh. So I am using jquery serialize() to post the form to the cart. The problem is

  1. It only works for the 1st page.
  2. If I don't put anything in the fields it bypasses the validation error check & submits the products with the information it has.

From the 2nd page if I click add to cart button the page refreshes & submits the product or show error if fields are left empty.

Here's the code:

HTML

        <div id="wh_table_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
            <div class="row">
                <div class="col-sm-12">
                    <table id="wh_table" class="table table-hover dataTable no-footer" role="grid" aria-describedby="wh_table_info" style="width: 100%;" width="100%" cellspacing="0">
                        <thead>
                            <tr role="row">
                                <th></th>
                                <th>PRODUCT</th>
                                <th>Message Box</th>
                                <th>PRICE</th>
                                <th>Product Total Quantity</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="product-178 variations_form odd" data-role="product" role="row">
                                <form action="/testsite/wholesale-product-page-template-custom/?add-to-cart=178" class="cart" method="post" enctype="multipart/form-data"></form>
                                <td class="image">
                                    <img src="https://localhost/testsite/wp-content/uploads/2016/10/1471481461.png" class="attachment-wh_catalog size-wh_catalog wp-post-image" alt="Jewelry Keys" srcset="https://localhost/testsite/wp-content/uploads/2016/10/1471481461.png 500w, https://localhost/testsite/wp-content/uploads/2016/10/1471481461-100x76.png 100w, https://localhost/testsite/wp-content/uploads/2016/10/1471481461-350x266.png 350w" sizes="(max-width: 500px) 100vw, 500px" width="500" height="380">                        
                                </td>
                                <td class="title">
                                    <h3>Gothic Key</h3>
                                    <b>Silver</b>
                                </td>
                                <td class="note">
                                    <label>Front</label><input class="msg-note wh-input" name="_message_front" value="" maxlength="15" placeholder="Up to 15 Letters or Numbers">
                                    <label>Back</label><input class="msg-note wh-input" name="_message_back" value="" maxlength="15" placeholder="Up to 15 Letters or Numbers">             
                                </td>
                                <td class="wh-price">
                                    <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>2,500.00</span>                          
                                </td>
                                <td class="quantity-field">
                                    <div class="quantity">
                                        <input step="1" min="" max="" name="quantity" value="1" title="Qty" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric" placeholder="Type Your Keyway " type="number">
                                    </div>
                                </td>
                                <td class="button">
                                    <input name="add-to-cart" value="178" type="hidden">
                                    <input name="product_id" value="178" id="product_id" type="hidden">
                                    <input value="1" id="product_quantity" type="hidden">
                                    <button type="submit" class="single_add_to_cart_button btn btn-primary button alt ajax_add_to_cart add_to_cart_button product_type_simple"><span class="glyphicon glyphicon-tag"></span> ADD TO CART</button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-5">
                    <div class="dataTables_info" id="wh_table_info" role="status" aria-live="polite">Showing page 1 of 6</div>
                </div>
                <div class="col-sm-7">
                    <div class="dataTables_paginate paging_full_numbers" id="wh_table_paginate">
                        <ul class="pagination">
                            <li class="paginate_button first disabled" id="wh_table_first"><a href="#" aria-controls="wh_table" data-dt-idx="0" tabindex="0">«</a></li>
                            <li class="paginate_button previous disabled" id="wh_table_previous"><a href="#" aria-controls="wh_table" data-dt-idx="1" tabindex="0">‹</a></li>
                            <li class="paginate_button active"><a href="#" aria-controls="wh_table" data-dt-idx="2" tabindex="0">1</a></li>
                            <li class="paginate_button "><a href="#" aria-controls="wh_table" data-dt-idx="3" tabindex="0">2</a></li>
                            <li class="paginate_button "><a href="#" aria-controls="wh_table" data-dt-idx="4" tabindex="0">3</a></li>
                            <li class="paginate_button "><a href="#" aria-controls="wh_table" data-dt-idx="5" tabindex="0">4</a></li>
                            <li class="paginate_button "><a href="#" aria-controls="wh_table" data-dt-idx="6" tabindex="0">5</a></li>
                            <li class="paginate_button "><a href="#" aria-controls="wh_table" data-dt-idx="7" tabindex="0">6</a></li>
                            <li class="paginate_button next" id="wh_table_next"><a href="#" aria-controls="wh_table" data-dt-idx="8" tabindex="0">›</a></li>
                            <li class="paginate_button last" id="wh_table_last"><a href="#" aria-controls="wh_table" data-dt-idx="9" tabindex="0">»</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

In functions.php

function enqueue_scripts_styles_init() {
        wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/test.js', array('jquery'), 1.0 ); 
        //wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
    }
    add_action('init', 'enqueue_scripts_styles_init');

And in test.js

    jQuery(document).ready(function($) {

        $( 'form' ).on( 'submit', function( evt ) {

            evt.preventDefault();

            $theForm = $(this).closest('form');
            //var $inputs = $theForm.find('input');
            //var serializedData = $inputs.serialize();

            url = $theForm.attr('action');

            // send xhr request
            $.ajax({
                type: $theForm.attr('method'),
                url: $theForm.attr('action'),
                data: $theForm.serialize(),
                success: function(data) {
                    //console.log('Yay! Form sent.');
                    //console.log(data);
                    console.log( $theForm.serialize() );
                }

            });

            // prevent submitting again
            return false;

        });

    });

I am currently using a jquery plugin dataTables for AJAX base pagination and to show products in a table row.

Here's the console log on success:

// input with text filled
_message_front=abc&_message_back=def&quantity=2&add-to-cart=178&product_id=178

// input without text filled. No error message thrown.
_message_front=&_message_back=&quantity=1&add-to-cart=178&product_id=178
Shan404
  • 78
  • 1
  • 12

2 Answers2

1

Okay I found a solution. Posting it here in case it helps anyone.

It seems datatable plugins only serialize the tr nodes it see at first. So when I go to next page the nodes remain hidden & thus serialize don't work.

The reason dataTables plugin code was not working due to legacy code. I was using DataTable with fnGetNodes() which isn't compatible.

    /*
        // DataTable = row().node()  // newSchool after 1.10
        // dataTable = fnGetNodes()  // oldSchool
        var table = $('#example').DataTable();

        table
            .rows( '.ready' )
            .nodes()
            .to$()      // Convert to a jQuery object
            .removeClass( 'ready' );
        );

    */

You can read more about dataTable vs DataTable Here. Here's from official forum

        $(document).ready(function(){   

        //$( 'form' ).on( 'submit', function( evt ) {
        $( 'form' ).submit( function( evt ) {

            evt.preventDefault();
            var oTable = $('#wh_table').dataTable();
            var sData = $('input', oTable.fnGetNodes()).serialize();
            $theForm = $(this).closest('form');

            url = $theForm.attr('action');

            // send xhr request
            $.ajax({
                type: $theForm.attr('method'),
                url: $theForm.attr('action'),
                //data: $theForm.serialize(),
                data: $theForm.sData,

                success: function(data) {
                    //console.log('It's Working....');
                    console.log(sData);
                }

            });

            // prevent submitting again
            return false;

        });

    });
Shan404
  • 78
  • 1
  • 12
0

If you just use this, it will solve your issue.

$("#TableID").on("submit", "#FormID", function(e){
// Your Ajax Codes Here
}

This is very easy to use method for datatables.