Skip to content

Magento2 Jquery Post Form via Ajax

I have a basic html form and what I want is when clicking the submit button to use Jquery and Ajax to post the contents to an external url instead of reloading the entire page. However whats happening is clicking submit makes the entire page reload and nothing gets posted to the external url

<form id="newsletter-validate-detail" class="form subscribe" action="" method="post">
<input type="hidden" name="api_key" id="api_key" value="12345" readonly>
<input type="hidden" id="hp" name="hp" value="">
<input type="hidden" name="list" id="list" value="56789" readonly>
<input type="hidden" name="boolean" value="false" readonly>
<input type="hidden" name="country" id="country" value="US" readonly>
<input type="hidden" name="gdpr" value="true" readonly>
<div class="newsletter-inner d-flex">
 <input type="email" id="email" name="email" class="form-control"/>
 <button type="submit" title="Subscribe" class="btn btn-primary action subscribe">Subscribe</button>
 </div>
 <div for="newsletter" generated="true" class="mage-error error p-2" id="newsletter-error"></div>
 </form> 

My JS code

  <script>
  require(['jquery'],function(){
  jQuery(document).ready(function() {

      jQuery("#newsletter-validate-detail").submit(function(){
          var formData = {
            email $("#email").val(),
            api_key: $("#api_key").val(),
            list: $("#list").val(),
            hp: $("#hp").val(),
            country: $("#country").val(),
            gdpr: $("#gdpr").val(),
          };

          jQuery.ajax({
            type: "POST",
            url: "https://sendyco.cross.com/subscribe",
            data: formData,
            dataType: "json",
            success: function(response){
               console.log(response.output);
            }
          });
          return false;
      });
    });
});
</script>