skip to Main Content

So I have this code that I want to run when someone changes an input or select field, obviously this is running twice because when I change the value of an input field then the select fields will change too. How can I make this code to not run twice but to work with both the selectors? I tried using an e.originalEvent statement for running only on human change but this will not work good cause I have some styled dropdowns that will change the values of the selected input through code so the code will not run..

//refresh form ajax.
jQuery('#BookingForm input, #BookingForm select').change(function(e){
    //jQuery('option:first-child', this).removeAttr('selected disabled'); //resetto il campo al change
    var dati = jQuery('#BookingForm').serialize();
    jQuery.ajax({
    type: "POST",
    url: "https://justfunviaggievento.it/wp-admin/admin-ajax.php",
    data: { action: 'booking_data_fetch', data: dati },
    success: function(data) {   
        //refresh dropdown sistemazioni
        if( !jQuery(e.target).hasClass('sistemazione')) {       
            var sistemazione = jQuery(data).find('#BookingForm select[name="sistemazione"]').html();
            jQuery('#BookingForm select[name="sistemazione"] option:not(:first-child)').remove();
            jQuery('#BookingForm select[name="sistemazione"]').append(sistemazione);    
            jQuery('select').niceSelect('update');
        }
        //refresh prezzo
        var prezzo = jQuery(data).find('#preventivo-prezzo p:first-child').html();
        jQuery('#preventivo-prezzo p:first-child').html( prezzo );
        jQuery('#preventivo-prezzo').removeClass("price-animation");
        setTimeout(function(){ jQuery('#preventivo-prezzo').addClass("price-animation") }, 100);
        //refresh supplementi
        var currentSupplemento = jQuery('#BookingForm .supplemento-monolocale').val();
        var maxSupplementi = jQuery(data).find('#BookingForm .supplemento-monolocale').html();
        jQuery('#BookingForm select.supplemento-monolocale').html( maxSupplementi ).val( currentSupplemento ).niceSelect('update');
        //refresh intestazione e immagine
        if( jQuery(e.target).hasClass('destinazione')) {
        var intestazione = jQuery(data).find('.box-preventivo h2 span').html();
        jQuery('.box-preventivo h2 span').html( intestazione );
        setTimeout(function(){ jQuery('.box-preventivo h2 span').addClass("price-animation") }, 100);
        setTimeout(function(){ jQuery('.box-preventivo h2 span').removeClass("price-animation") }, 1000);
        jQuery('.pagina-preventivo .box-preventivo:first-child').animate({ opacity: 0 }, 100, function() {
            // Animation complete.
            jQuery(this).css('background','url(/wp-content/uploads/media/justfun-viaggi-evento-preventivo-' + intestazione + '-3.jpg) no-repeat center').animate({ opacity: 1 }, 50);
        });
        }
    },
    error: function() {
        console.log('errore JS');
    }
    });
});

3

Answers


  1. Chosen as BEST ANSWER

    Ok I fixed this using bind and unbind inside and outside the function in this way:

    //refresh form ajax.
    function ajax(e){
        //UNBIND AFTER CHANGE
        jQuery('#BookingForm input, #BookingForm select').unbind('change');
        var dati = jQuery('#BookingForm').serialize();
        jQuery.ajax({
        type: "POST",
        url: "https://justfunviaggievento.it/wp-admin/admin-ajax.php",
        data: { action: 'booking_data_fetch', data: dati },
        success: function(data) {
            //refresh dropdown sistemazioni
            if( !jQuery(e.target).hasClass('sistemazione') && !jQuery(e.target).hasClass('numero-passeggeri') ) {       
                var sistemazione = jQuery(data).find('#BookingForm select[name="sistemazione"]').html();
                jQuery('#BookingForm select[name="sistemazione"] option').remove();
                jQuery('#BookingForm select[name="sistemazione"]').append(sistemazione);    
                jQuery('select').niceSelect('update');
            }
            //refresh supplementi
            var currentSupplemento = jQuery('#BookingForm .supplemento-monolocale').val();
            var maxSupplementi = jQuery(data).find('#BookingForm .supplemento-monolocale').html();
            jQuery('#BookingForm select.supplemento-monolocale').html( maxSupplementi ).val( currentSupplemento ).niceSelect('update');
            //refresh prezzo
            var prezzo = jQuery(data).find('#preventivo-prezzo p:first-child').html();
            jQuery('#preventivo-prezzo p:first-child').html( prezzo );
            jQuery('#preventivo-prezzo').removeClass("price-animation");
            setTimeout(function(){ jQuery('#preventivo-prezzo').addClass("price-animation") }, 100);
            //REBIND AFTER DOING STUFFS
            jQuery('#BookingForm input, #BookingForm select').bind('change', function(e){
                ajax(e);
            });
        },
        error: function() {
            console.log('errore JS');
        }
        });
    }
    //INITIAL BIND TO CHANGE
    jQuery('#BookingForm input, #BookingForm select').bind('change', function(e){
        ajax(e);
    });
    

  2. send2 = false;
    
    //refresh form ajax.
    jQuery('#BookingForm input').change(function(e){    
      sendQuery(e);
      send2 = true;
    });
    
    jQuery('#BookingForm select').change(function(e){
      if(!send2){ sendQuery(e);}  
      send2 = false;
    });
    
    function sendQuery(e){  
      //jQuery('option:first-child', this).removeAttr('selected disabled'); //resetto il campo al change
      var dati = jQuery('#BookingForm').serialize();
      jQuery.ajax({
      type: "POST",
      url: "https://justfunviaggievento.it/wp-admin/admin-ajax.php",
      data: { action: 'booking_data_fetch', data: dati },
      success: function(data) {   
          //refresh dropdown sistemazioni
          if( !jQuery(e.target).hasClass('sistemazione')) {       
              var sistemazione = jQuery(data).find('#BookingForm select[name="sistemazione"]').html();
              jQuery('#BookingForm select[name="sistemazione"] option:not(:first-child)').remove();
              jQuery('#BookingForm select[name="sistemazione"]').append(sistemazione);    
              jQuery('select').niceSelect('update');
          }
          //refresh prezzo
          var prezzo = jQuery(data).find('#preventivo-prezzo p:first-child').html();
          jQuery('#preventivo-prezzo p:first-child').html( prezzo );
          jQuery('#preventivo-prezzo').removeClass("price-animation");
          setTimeout(function(){ jQuery('#preventivo-prezzo').addClass("price-animation") }, 100);
          //refresh supplementi
          var currentSupplemento = jQuery('#BookingForm .supplemento-monolocale').val();
          var maxSupplementi = jQuery(data).find('#BookingForm .supplemento-monolocale').html();
          jQuery('#BookingForm select.supplemento-monolocale').html( maxSupplementi ).val( currentSupplemento ).niceSelect('update');
          //refresh intestazione e immagine
          if( jQuery(e.target).hasClass('destinazione')) {
          var intestazione = jQuery(data).find('.box-preventivo h2 span').html();
          jQuery('.box-preventivo h2 span').html( intestazione );
          setTimeout(function(){ jQuery('.box-preventivo h2 span').addClass("price-animation") }, 100);
          setTimeout(function(){ jQuery('.box-preventivo h2 span').removeClass("price-animation") }, 1000);
          jQuery('.pagina-preventivo .box-preventivo:first-child').animate({ opacity: 0 }, 100, function() {
              // Animation complete.
              jQuery(this).css('background','url(/wp-content/uploads/media/justfun-viaggi-evento-preventivo-' + intestazione + '-3.jpg) no-repeat center').animate({ opacity: 1 }, 50);
          });
          }
      },
      error: function() {
          console.log('errore JS');
        }
      });
    }
    
    Login or Signup to reply.
  3. what you have to do is maintain some state for when a request is in progress. Make sure to make this context specific – so if you only want to limit multiple requests for a specific use-case, name and manage this state accordingly. This means you will need multiple state variables (like requestInProgress) for different form fields and pages of your app; this is not meant to be a global request limiter

    var requestInProgress = false;
    
    function sendRequest() {
      if (requestInProgress) return; // no action
      
      // otherwise, run request logic
      requestInProgress = true;
      // ... your code
    
      jQuery.ajax({
        // make sure to set the boolean to false in both the 
        // success and error cases
    
        success: function(data) {
          requestInProgress = false;
          // ... your code
        },
        error: function(data) {
          requestInProgress = false;
          // ... your code
        },
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search