T
T
trenton2021-07-30 22:06:20
AJAX
trenton, 2021-07-30 22:06:20

How to "friend" two ajax requests so that one acts after the other?

Add to cart button and filtering. No, not plugins - snippets. Separately, they work, and when the page is loaded, the button adds products to the cart, and the filtering filters, but the button does not work in the filtered products. I thought after success immediately insert the second request, as it turned out with the slider. but it didn't work. Where is it correct to put it so that it can be added to the cart in the filtered products without going to the card?
First

jQuery(function($)
{
    $('.categories.side-nav.log>#st-accordion>ul>li input, .sortby>.price-slider input, select.orderby').on('change',function(e){ 
        e.preventDefault();    
        themename_get_posts();
        jQuery('html, body').animate({scrollTop:0}, 1);
    });
    $('.orderby').on('change', function(e){
        e.preventDefault();
        themename_get_posts();
    });
    
    $(document).on("click",".ajax-page-numbers .page-numbers",function(e){
        e.preventDefault();

        var url = $(this).attr('href'); //Grab the URL destination as a string
        var paged = url.split('&paged='); //Split the string at the occurance of &paged=

        if(~url.indexOf('&paged=')){
            paged = url.split('&paged=');
        } else {
            paged = url.split('/page/');
        }
        themename_get_posts(paged[1]); //Load Posts (feed in paged value)
    });

    //Получают данные
    function getCats()
    {
        var cats = []; //Setup empty array

        $(".themename_filter_check input:checked").each(function() {
            var val = $(this).val();
            cats.push(val); //Push value onto array
        });

        return cats; //Return all of the selected genres in an array
    }
    function getColor()
    {
        var cats = []; //Setup empty array

        $(".themename_filter_pa_color_check input:checked").each(function() {
            var val = $(this).val();
            cats.push(val); //Push value onto array
        });

        return cats; //Return all of the selected genres in an array
    }
    function getSize()
    {
        var cats = []; //Setup empty array

        $(".themename_filter_pa_size_check input:checked").each(function() {
            var val = $(this).val();
            cats.push(val); //Push value onto array
        });

        return cats; //Return all of the selected genres in an array
    }
    function getPricesMin(){
       return $('#priceMin').val();
    }
    function getPriceMax(){
       return $('#priceMax').val();
    }
    function themename_order(){
        return $('.orderby option:selected').val();
    }
    function themename_get_posts(paged)
    {
        var paged_value = paged; //Store the paged value if it's being sent through when the function is called
        var ajax_url = woocommerce_params.ajax_url; //Get ajax url (added through wp_localize_script)

        $.ajax({
            type: 'GET',
            url: ajax_url,
            data: {
                action: 'themename_filter',
                category: getCats,
                pa_color: getColor,
                pa_size: getSize,
                min: getPricesMin,
                max: getPriceMax,
                order: themename_order,
                paged: paged_value //If paged value is being sent through with function call, store here
            },
            beforeSend: function ()
            {
                $('.main-product-content').html('<div class="text-center" style="height:50vh;">Waiting</div>');
            },
            success: function(data)
            {
                //Hide loader here
                $('.main-product-content').html(data);
                $('.main-product-content ul.products').addClass('row');
                jQuery('.slider-archive').each(function() {
                  var slider = jQuery(this);
                  slider.slick({
                  infinite: true,
                  slidesToShow: 1,
                  slidesToScroll: 1,
                  driggable:false, 
                  dots: true,
                  arrows:true,  
                  focusOnSelect: true,
                });
                var sLightbox = jQuery(this);
                  sLightbox.slickLightbox({
                    src: 'src',
                    itemSelector: 'img.attachment-woocommerce_single.size-woocommerce_single',   
                  });
                }); 
                jQuery('.var-wrapper-pa_color .radio-span').click(function() {
                  jQuery('.var-wrapper-pa_color .radio-span').removeClass('attr-selected');
                  jQuery(this).addClass('attr-selected');
                });
                 // Add new slide
                
            },
            error: function()
            {
                //If an ajax error has occured, do something here...
                $(".main-product-content").html('<div class="text-center" style="height:50vh;">There has been an error</div>');
            }
        });
    }    
});


Second
jQuery(function($) {

      $('form.cart').on('submit', function(e) {
        e.preventDefault();

        var form = $(this);
        form.block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 } });

        var formData = new FormData(form[0]);
        formData.append('add-to-cart', form.find('[name=add-to-cart]').val() );

        // Ajax action.
        $.ajax({
          url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'ace_add_to_cart' ),
          data: formData,
          type: 'POST',
          processData: false,
          contentType: false,
          complete: function( response ) {
            response = response.responseJSON;
            if ( ! response ) {
              return;
            }
            if ( response.error && response.product_url ) {
              window.location = response.product_url;
              return;
            }

            // Redirect to cart option
            if ( wc_add_to_cart_params.cart_redirect_after_add === 'yes' ) {
              window.location = wc_add_to_cart_params.cart_url;
              return;
            }

            var $thisbutton = form.find('.single_add_to_cart_button'); //
//            var $thisbutton = null; // uncomment this if you don't want the 'View cart' button

            // Trigger event so themes can refresh other areas.
            $( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );

            // Remove existing notices
            $( '.woocommerce-error, .woocommerce-message, .woocommerce-info' ).remove();

            // Add new notices
            form.closest('.product').before(response.fragments.notices_html)
            form.unblock();
          }
        });
      });
    });


I want to understand how to make things like this work together, often necessary.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2021-07-31
@cyber-jet

I suppose that after filtering, objects are rewritten in the DOM, so everything that was previously wiretapped is erased. There are several ways to fix this:
1. Move the form submit event listener to a separate function, and call it every time after filtering. So-so variant, shitcode :) 2. Listen to an event on an object that is definitely not being erased from the DOM, for example: 3. For old school lovers, write a send to trash function at the root of window. And call it directly on the element:$('form.cart').on( 'submit' ...
$( 'body' ).on( 'submit', 'form.cart', ...
<form onsubmit="addToCart();return false">...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question