Success/Error messages and Pardot Form Handlers with Webflow

So this is a pain in the ass, but I can give you an overview of how I did it. Pardot does not allow AJAX posts, it throws a CORS error at you. What it will allow is jsonp, so I used the information found in this post: How to: Use Ajax to submit forms with default actions after submit

And combined it with a few things I found on Stack Overflow.

Here is the result:

  window.logResult= function(json) {
    if(json.result === "success"){
      formSuccess();
    } else if(json.result === "error") {
      formError();
    }
  };
  
  makeWebflowFormAjax = function(forms, successCallback, errorCallback) {
    forms.each(function(){
      var form = $(this);
      form.on("submit", function(){
        var container =   form.parent();
        var doneBlock  =  $(".w-form-done", container);
        var failBlock  =  $(".w-form-fail", container);

        var action =    form.attr("action");
        var method =    form.attr("method");
        var data =      form.serialize();
        var dataURI =   {};


        form.find("input, textarea, select").each(function() {
          var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase();
          if (inputType !== "BUTTON" && inputType !== "SUBMIT") {
            dataURI[this.name] = $(this).val();
          }
        });

        dataURI = $.param(dataURI);

        // console.log(dataURI);
        
        if($('#newsletter-requests').length !== 0) {
          if($('#newsletter-requests').val().length == 0) {

            // call via ajax
            $.ajax({
              type: method,
              url: action + '?' + dataURI,
              dataType: "jsonp",
              jsonpCallback: 'logResult'
            });

          }
        } else {

          $.ajax({
            type: method,
            url: action + '?' + dataURI,
            dataType: "jsonp",
            jsonpCallback: 'logResult'
          });

        }
        
        formSuccess = function() {
          form.hide();
          doneBlock.fadeIn();
          failBlock.hide();          
        }
        formError = function() {
          form.show();
          doneBlock.hide();
          failBlock.fadeIn();         
        }       
        // prevent default webflow action
        return false;
      });
    });
  }

makeWebflowFormAjax($('#newsletter-form'));

Essentially you need to host two .js files elsewhere since Webflow won’t let you (I used RawGit, but you could probably use Github pages) for a response that you place in your Pardot success and error location fields that contains this script. So one page simply has the success response and the other has the error response (below) and you just insert the url to those pages in Pardot.

logResult({ 'result' : 'success’ });

logResult({ 'result' : 'error' });