Form submit via ajax

I just started using mautic and I’m trying to setup a form with an ajax submit via mauticjs api, is this possible?.

Code:
MauticJS.makeCORSRequest('POST', 'http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1', $email.val(), function (response, xhr) { console.log(xhr); console.log(response); });

I get a 302 redirection and a CORS error

Code:
XMLHttpRequest cannot load http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1. Redirect from 'http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1' to 'http://ortodontiasakima.com/?mauticError=Este%20formul%C3%A1rio%20n%C3%A3o%20est%C3%A1%20mais%20dispon%C3%ADvel.' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

It says that the form isn't accessible anymore.

Header/Request:

Code:
Request URL:http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1 Request Method:OPTIONS Status Code:204 No Content Remote Address:192.155.95.225:80 Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:http://ortodontiasakima.com Access-Control-Max-Age:60000 Cache-Control:no-cache Connection:close Content-Length:0 Content-Type:text/html; charset=UTF-8 Date:Sat, 11 Mar 2017 03:06:39 GMT Server:Apache/2.4.18 (Ubuntu) Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Access-Control-Request-Headers:x-requested-with Access-Control-Request-Method:POST Connection:keep-alive Host:mkt.ortodontiasakima.com Origin:http://ortodontiasakima.com Referer:http://ortodontiasakima.com/ User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Query String Parameters view source view URL encoded formId:1
Code:
Request URL:http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1 Request Method:GET Status Code:302 Found Remote Address:192.155.95.225:80 Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:http://ortodontiasakima.com Access-Control-Max-Age:60000 Cache-Control:no-cache Connection:Keep-Alive Content-Length:692 Content-Type:text/html; charset=UTF-8 Date:Sat, 11 Mar 2017 03:06:39 GMT Keep-Alive:timeout=5, max=100 Location:http://ortodontiasakima.com/?mauticError=Este%20formul%C3%A1rio%20n%C3%A3o%20est%C3%A1%20mais%20dispon%C3%ADvel. Server:Apache/2.4.18 (Ubuntu) Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Content-Length:26 Content-Type:application/x-www-form-urlencoded Cookie:e68f1c2b2e8be0b3bba4f5084ac01834=us3cp68e2gm89opquaufgrcd95; mautic_session_name=e68f1c2b2e8be0b3bba4f5084ac01834; mautic_session_id=d01b67f6702a98f7545933d19f0e4df39bfbad7e; d01b67f6702a98f7545933d19f0e4df39bfbad7e=3; mautic_referer_id=11 Host:mkt.ortodontiasakima.com Origin:http://ortodontiasakima.com Referer:http://ortodontiasakima.com/ User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 X-Requested-With:XMLHttpRequest Query String Parameters view source view URL encoded formId:1
Code:
Request URL:http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1 Request Method:POST Status Code:302 Found Remote Address:192.155.95.225:80 Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:http://ortodontiasakima.com Access-Control-Max-Age:60000 Cache-Control:no-cache Connection:Keep-Alive Content-Length:692 Content-Type:text/html; charset=UTF-8 Date:Sat, 11 Mar 2017 03:06:39 GMT Keep-Alive:timeout=5, max=100 Location:http://ortodontiasakima.com/?mauticError=Este%20formul%C3%A1rio%20n%C3%A3o%20est%C3%A1%20mais%20dispon%C3%ADvel. Server:Apache/2.4.18 (Ubuntu) Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Content-Length:26 Content-Type:application/x-www-form-urlencoded Cookie:e68f1c2b2e8be0b3bba4f5084ac01834=us3cp68e2gm89opquaufgrcd95; mautic_session_name=e68f1c2b2e8be0b3bba4f5084ac01834; mautic_session_id=d01b67f6702a98f7545933d19f0e4df39bfbad7e; d01b67f6702a98f7545933d19f0e4df39bfbad7e=3; mautic_referer_id=11 Host:mkt.ortodontiasakima.com Origin:http://ortodontiasakima.com Referer:http://ortodontiasakima.com/ User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 X-Requested-With:XMLHttpRequest Query String Parameters view source view URL encoded formId:1 Form Data view source view URL encoded fernandocandiani@gmail.com:

I just started using mautic and I’m trying to setup a form with an ajax submit via mauticjs api, is this possible?.

MauticJS.makeCORSRequest('POST', 'http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1', $email.val(), function (response, xhr) { console.log(xhr); console.log(response); });

I get a 302 redirection and a CORS error

XMLHttpRequest cannot load http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1. Redirect from 'http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1' to 'http://ortodontiasakima.com/?mauticError=Este%20formul%C3%A1rio%20n%C3%A3o%20est%C3%A1%20mais%20dispon%C3%ADvel.' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

It says that the form isn’t accessible anymore.

Header/Request:

Request URL:http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1 Request Method:OPTIONS Status Code:204 No Content Remote Address:192.155.95.225:80 Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:http://ortodontiasakima.com Access-Control-Max-Age:60000 Cache-Control:no-cache Connection:close Content-Length:0 Content-Type:text/html; charset=UTF-8 Date:Sat, 11 Mar 2017 03:06:39 GMT Server:Apache/2.4.18 (Ubuntu) Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Access-Control-Request-Headers:x-requested-with Access-Control-Request-Method:POST Connection:keep-alive Host:mkt.ortodontiasakima.com Origin:http://ortodontiasakima.com Referer:http://ortodontiasakima.com/ User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Query String Parameters view source view URL encoded formId:1

Request URL:http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1 Request Method:GET Status Code:302 Found Remote Address:192.155.95.225:80 Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:http://ortodontiasakima.com Access-Control-Max-Age:60000 Cache-Control:no-cache Connection:Keep-Alive Content-Length:692 Content-Type:text/html; charset=UTF-8 Date:Sat, 11 Mar 2017 03:06:39 GMT Keep-Alive:timeout=5, max=100 Location:http://ortodontiasakima.com/?mauticError=Este%20formul%C3%A1rio%20n%C3%A3o%20est%C3%A1%20mais%20dispon%C3%ADvel. Server:Apache/2.4.18 (Ubuntu) Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Content-Length:26 Content-Type:application/x-www-form-urlencoded Cookie:e68f1c2b2e8be0b3bba4f5084ac01834=us3cp68e2gm89opquaufgrcd95; mautic_session_name=e68f1c2b2e8be0b3bba4f5084ac01834; mautic_session_id=d01b67f6702a98f7545933d19f0e4df39bfbad7e; d01b67f6702a98f7545933d19f0e4df39bfbad7e=3; mautic_referer_id=11 Host:mkt.ortodontiasakima.com Origin:http://ortodontiasakima.com Referer:http://ortodontiasakima.com/ User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 X-Requested-With:XMLHttpRequest Query String Parameters view source view URL encoded formId:1

Request URL:http://mkt.ortodontiasakima.com/index.php/form/submit?formId=1 Request Method:POST Status Code:302 Found Remote Address:192.155.95.225:80 Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:http://ortodontiasakima.com Access-Control-Max-Age:60000 Cache-Control:no-cache Connection:Keep-Alive Content-Length:692 Content-Type:text/html; charset=UTF-8 Date:Sat, 11 Mar 2017 03:06:39 GMT Keep-Alive:timeout=5, max=100 Location:http://ortodontiasakima.com/?mauticError=Este%20formul%C3%A1rio%20n%C3%A3o%20est%C3%A1%20mais%20dispon%C3%ADvel. Server:Apache/2.4.18 (Ubuntu) Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Content-Length:26 Content-Type:application/x-www-form-urlencoded Cookie:e68f1c2b2e8be0b3bba4f5084ac01834=us3cp68e2gm89opquaufgrcd95; mautic_session_name=e68f1c2b2e8be0b3bba4f5084ac01834; mautic_session_id=d01b67f6702a98f7545933d19f0e4df39bfbad7e; d01b67f6702a98f7545933d19f0e4df39bfbad7e=3; mautic_referer_id=11 Host:mkt.ortodontiasakima.com Origin:http://ortodontiasakima.com Referer:http://ortodontiasakima.com/ User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 X-Requested-With:XMLHttpRequest Query String Parameters view source view URL encoded formId:1 Form Data view source view URL encoded fernandocandiani@gmail.com:

To submit a form via AJAX , we will need to do certain things in our JavaScript file.

  1. Capture the form submit button so that the default action doesn’t take place.
  2. Get all of the data from our form using jQuery.
  3. Submit using AJAX (we’ll go through a few ways)
  4. Show errors if there are any.

I hope this helps,
Best regards

Can you point me, how can a simulated ajax POST request to /form/submit containt mautic contact ID?
Even if I pass correct IP address of user using X-Forwarded-For header, after form is submitted, a new contact with form data is created, but the same user with the same IP is still considered anonymous contact browsing the web… thank you

1 Like

I’m facing with the same issue … unfortunately with no luck.

Ok, I’ve found very ugly, strange workaround for this.

In my case I have a form that currently sends submission data to Mailchimp but I wanted to also send the same piece of information to Mautic (I am in the middle of migration everything to Mautic). I’ve tried with AJAX request to /form/submit?formId=X location but because of CORS it did not work.

Workaround:
I hid both my Mautic’s form structure and JS SDK snippet below the main visible form. When user submit the form I collect the data and put them to the hidden form and trigger the submit event. This way Mautic recognizes anonymous contact and merge with the data from form.

I still get console error: “Uncaught DOMException: Blocked a frame with origin “https://my-mautic-instance.url” from accessing a cross-origin frame.” because Mautic uses an iframe while sending form but … at least it works.

If anyone has a better idea I would love to hear about it. I am aware that my solution is actually not a solution.

Thanks for this idea. I’m having the same problem. Have you found out a different way since this post or are you still doing this?

I don’t have an issue with using ajax to submit the form but Mautic isn’t associating it with the user and I lose all of the page hits that would be associated with the user which makes any segmentation impossible.

We are still doing this, mostly successfully. We do use ajax to post the form data, but post it directly to the form itself using the MauticJS api’s makeCorsRequest function

It correctly associates the mtc_id every time it works, though we set it to time out after about 500ms so we don’t interrupt the user too much, and every so often their connection or device is too slow and we miss the form submit.

Here’s a relevant chunk of our code:

function urlEncodeParameters(formId, parameters) {
  let urlEncodedDataPairs = [];

  urlEncodedDataPairs.push(
    "mauticform%5BformId%5D=" + encodeURIComponent(formId)
  );

  urlEncodedDataPairs.push("mauticform%5Breturn%5D=");

  // loop through parameters and append them to the data array to send
  if (typeof parameters === "object") {
    Object.entries(parameters).forEach(([key, val]) => {
      if (Array.isArray(val)) {
        val.forEach((valPart) => {
          urlEncodedDataPairs.push(
            `mauticform%5B${encodeURIComponent(
              key
            )}%5D%5B%5D=${encodeURIComponent(valPart)}`
          );
        });
      } else {
        urlEncodedDataPairs.push(
          `mauticform%5B${encodeURIComponent(key)}%5D=${encodeURIComponent(
            val
          )}`
        );
      }
    });
  }

  // Combine the pairs into a single string and replace all %-encoded spaces to
  // the '+' character; matches the behaviour of browser form submissions.
  return urlEncodedDataPairs.join("&").replace(/%20/g, "+");
}

function sendFormData(formId, parameters, callback) {
  if ("undefined" === typeof MauticJS) {
    console.log("Unable to send form data. MauticJS is undefined.");
    return false;
  }

  MauticJS.makeCORSRequest(
    "POST",
    env.endpoint + "/form/submit?formId=" + encodeURIComponent(formId),
    urlEncodeParameters(formId, parameters),
    function (response, xhr) {
      if (typeof callback === "function") {
        callback(response, xhr);
      }
    }
  );

  return true;
}