0

I'm having a hard time sending a form using POST as well as JS. The reason for this setup is sending a form to DotMailer emailing program as well as Magento through AWS at the same time, with both having different means of sending. I'm thinking it gets sent to AWS before it actually has a chance to POST?

The data is JSON-ified before being sent to AWS which i presume would be an issue for POST for the mailing program?

Help will be much appreciated!

The code form code:

        <form name="signup" id="signup" action="https://example.com/signup.ashx" method="post" autocomplete="off" class="redeye-form loyalty-form" onsubmit="return validate_signup(this, true)" data-form-id="loyalty-form">
<input type="hidden" name="ci_isconsentform" value="true">
<input type="hidden" name="userid" value="230531">
<input type="hidden" name="SIGb7f7109acfe72442f3b9937c47f1c0e7a78f60e9bec1ba7a7084e947eebceef2" value="">
<input type="hidden" name="addressbookid" value="574883" />
<input type="hidden" name="ReturnURL" value="">
<input type="hidden" id="ci_consenturl" name="ci_consenturl" value="">
            <div>
                <label class="wrap" for="FIRSTNAME">Imi&#281;: <span class="requiredfield">*</span></label>
                <input name="cd_FIRSTNAME" id="FIRSTNAME" type="text" data-parameter="firstname" class="text regex"  placeholder=""   data-regex="^.{1,}$" data-regex-message="Wpisz poprawne imie (przynajmniej jeden znak)"aria-required="false" />
            </div>
            <div>
                <label class="wrap" for="LASTNAME">Nazwisko: <span class="requiredfield">*</span></label>
                <input  name="cd_LASTNAME" id="LASTNAME" type="text" data-parameter="lastname" class="text regex" placeholder=""  data-parameter="lastname"aria-required="false" />
            </div>

            <div>
<label class="wrap" for="POSTCODE">Kod pocztowy:</label>
<input type="text" class="text regex" name="cd_POSTCODE" id="POSTCODE" aria-required="false" />
</div>


            <div>
                <label class="wrap" for="email">Adres e-mail: <span class="requiredfield">*</span></label>
                <input type="text" name="email" id="email" required aria-required="true" data-parameter="email" class="text regex">
            </div>

            <div class="newsletter text">

            <p>


            <input type="checkbox" name="ci_userConsentCheckBox" id="ci_userConsentCheckBox" data-parameter="doubleoptin" value="c">Consent text 1</p>

            <input type="checkbox" name="sprawdzanko" id="sprawdzanko" value="1"><span>Consent text 2</span>

            <p>Consent text 3</p>

            <p>Kliknięcie w przycisk "Wyślij" znajdujący się poniżej oznacza akceptację Regulaminu.</p>

            </div>





            <input type="submit" class="c-btn c-btn--secondary" onmousedown="doSubmitEvents();" name="btnsubmit" id="btnsubmit" value="Wyślij" disabled> <p><span class="requiredfield">*</span>Wymagane pola</p>


        </form>

The sending JS:

  <script>
        jQuery( document ).ready(function() {

    const storeCode = "rg_pl";

    var site = {
        "url"       :  "https://reporting.example.com",
        "id"        :  "14555",
        "notify"    :  "examplesingleoptinwelcome"
    };

    var form = document.getElementsByTagName("form")[0];
    var loyaltyForm = form.classList.contains('loyalty-form') == true;

    jQuery("form.redeye-form .c-btn--secondary").click(function(e) {

        e.preventDefault();

        jQuery('.popup').remove();
        var validityErrors = 0;

        jQuery("input.required").each(function( index ) {
            jQuery(this).removeClass("invalid");
            if (!jQuery(this).val()) {
                jQuery(this).after("<div class='popup'>Please enter something here</div>");
                setTimeout(function() {
                    jQuery('.popup').remove();
                }, 7000);
                jQuery(this).addClass("invalid");
                validityErrors++;
            }
        });

        jQuery("select.required").each(function( index ) {
            jQuery(this).removeClass("invalid");
            if (!jQuery(this).val()) {
                jQuery(this).after("<div class='popup'>Please enter something here</div>");
                setTimeout(function() {
                    jQuery('.popup').remove();
                }, 7000);
                jQuery(this).addClass("invalid");
                validityErrors++;
            }
        });

        jQuery("input.regex").each(function( index ) {
            jQuery(this).removeClass("invalid");
            var patt = new RegExp(jQuery(this).data("regex"));
            var result = patt.test(jQuery(this).val());
            if (result !== true) {
                var message = jQuery(this).data("regex-message");
                jQuery(this).after("<div class='popup'>" + message + "</div>");
                setTimeout(function() {
                    jQuery('.popup').remove();
                }, 7000);
                jQuery(this).addClass("invalid");
                validityErrors++;
            }
        });

        if (validityErrors == 0) {

            var result = {};

            var location = (window.location != window.parent.location)
            ? document.referrer
            : document.location.href;

            result["form-location"] = location;

            var url = site.url + "/cgi-bin/rr/blank.gif";

            var formTitle = jQuery("form.redeye-form").data("form-id");

            result["subject"] = formTitle;

            url = url.concat("?nourl=" + encodeURI(formTitle));
            url = url.concat("&" + encodeURI(formTitle) + "=" + encodeURI(formTitle));

            jQuery("form.redeye-form input").each(function( index ) {
                if ( jQuery(this).is("input:text") ){
                    var parameter = jQuery(this).data("parameter");
                    var value = jQuery(this).val();
                }

                if ( jQuery(this).is("input:checkbox") ){
                    var parameter = jQuery(this).data("parameter");
                    var value = jQuery(this).is(':checked');
                }

                if ( jQuery(this).is("input:hidden") ){
                    var parameter = jQuery(this).data("parameter");
                    var value = jQuery(this).val();
                }

                result[parameter] = value;
                url = url.concat("&" + encodeURI(parameter) + "=" + encodeURI(value));
            });

            jQuery("form.redeye-form select").each(function( index ) {
                var parameter = jQuery(this).data("parameter");
                var value = jQuery(this).val();
                url = url.concat("&" + encodeURI(parameter) + "=" + encodeURI(value));
            });

            if (jQuery("input[data-parameter='doubleoptin']").is(":checked") == true) {
                url = url.concat('&notify=' + site.notify);
                url = url.concat("&emailpermit="  + "yes");
                url = url.concat("&newsletter=" + site.id);
            } else {
                url = url.concat("&emailpermit="  + "no");
                url = url.concat("&newsletter=" + site.id);
            }

            url = url.concat("&domain_id=" + site.id);

            var date = new Date();
            result["date"] = date.getFullYear() + '-' + ('0' + date.getDate()).slice(-2) + '-'
             + ('0' + (date.getMonth()+1)).slice(-2);

            result["url"] = window.location.href;

            result["storeCode"] = storeCode;

            var redEyeForm = jQuery( "form.redeye-form" );
            redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );

            // if (result["doubleoptin"] == "c") {
            //     result["doubleoptin"] = 1;
            // } else {
            //     result["doubleoptin"] = 0;
            // }


            if (loyaltyForm == true){
                console.log(result);
                jQuery.ajax({
                    type: "POST",
                    url: 'https://example.execute-api.eu-west-1.amazonaws.com/Deployment',
                    contentType: 'application/json',
                    data: JSON.stringify(result),
                    success: function(res){
                        redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
                    },
                    error: function(){
                        redEyeForm.replaceWith( "<div class='successmessage'>Wystąpił błąd</div>" );
                    }
                });
            }
        }
    });
});

        </script>

EDIT: Could this accomplish what I need?

            if (loyaltyForm == true){
                console.log(result);

                    jQuery.ajax({
                    type: "POST",
                    url: 'https://h3uxa21uxf.execute-api.eu-west-1.amazonaws.com/Deployment',
                    contentType: 'application/json',
                    data: JSON.stringify(result),
                    success: function(res){

    var $form = $(#signup);

    $.ajax({
     type     : "POST",
     cache    : false,
     url      : $form.attr('action'),
     data     : $form.serializeArray(),
     success  : function(data) {

                        redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
                    },

    });
 }

                    error: function(){

                        redEyeForm.replaceWith( "<div class='successmessage'>Wystąpił błąd</div>" );
                    }

                });



            }
        }
    });
});
  • Why cant you have two ajax requests - after the success of one - fire the other? Alternatively you could simply use .submit(). Or am I missing something here? – alpharomeo Mar 09 '20 at 20:10
  • Not good at this, could you suggest how to fire the other one please? – wojciech Swiech Mar 09 '20 at 20:16
  • Not sure if this helps but last week I was struggling with a form and someone told me that the method used on your form will try to handle the submit event. Sometimes before your JavaScript can even execute – KJEK-Code Mar 09 '20 at 20:16

1 Answers1

0

I have a couple of examples you can build on.

Option 1 - You can submit to URL 1 via ajax and then submit the form as if user has clicked the button to URL 2.

Option 2 - Submit to URL 1 and then on success - submit to URL 2 - both via AJAX

// Option 1 - Ajax to submit first and then conduct default submit action for form
function ajaxAndSubmit(e){
e.preventDefault(); // Stop the default action of the submit button
  var formData = $('#sample-form').serialize(); // Serialize the data
  // Start ajax 1
  $.ajax( {
        type: "POST",
        url: 'some url',
        data: formData,
        success: function( response ) {
          console.log( response );
          //Mimic default action
          $('#sample-form').submit();
        }
   } );
}

// Option 2 - handle both in ajax
function ajaxAndSubmitWithAjax(e){
e.preventDefault(); // Stop the default action of the submit button
  var formData = $('#sample-form').serialize(); // Serialize the data
  // Start ajax 1
  $.ajax( {
        type: "POST",
        url: 'some url',
        data: formData,
        success: function( response ) {
          console.log( response );
          // Submit via ajax
          $.get('some-url.php?' + $('#sample-form').serialize()); // Using GET
                    $.post('some-url.php', $('#sample-form').serialize()); // Using POST
        }
   } );
}
alpharomeo
  • 418
  • 5
  • 13