Skip to content

Instantly share code, notes, and snippets.

@escopecz
Last active April 23, 2024 17:29
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save escopecz/136f62b66d526bc32006f0d2358a8e15 to your computer and use it in GitHub Desktop.
Save escopecz/136f62b66d526bc32006f0d2358a8e15 to your computer and use it in GitHub Desktop.
An example of how to send a form submission to a Mautic form with jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mautic Form Test</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" type="text/css" />
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h2>Mautic Test</h2>
<form id="mautic" method="post" action="http://mautic.test/form/submit">
<input type="hidden" name="formId" value="284" />
<input type="hidden" name="return" value="this-must-exist" />
<input type="hidden" name="formName" value="" />
<input type="hidden" name="messenger" value="1" />
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" value="John">
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" required value="Linhart">
</div>
<div class="form-group">
<label for="company">Company Name</label>
<input type="text" class="form-control" id="company" name="company" placeholder="Company Name" required value="Mautic">
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" required value="jan@linhart.email">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<script type="text/javascript">
$(() => {
$('#mautic').on('submit', (e) => {
e.preventDefault();
let form = $('#mautic');
let values = {mauticform: form.serializeArray().reduce((obj, val) => { obj[val.name] = val.value; return obj; }, {})};
$.ajax({
url: form.attr('action') + '?formId=' + form.find('[name=formId]').val(),
data: $.param(values),
type: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
success: (content, status, xhr) => {
console.log('The submission was successful.');
},
error: (xhr) => {
console.log('An error occured when submitting the form');
},
});
});
});
</script>
</body>
</html>
@M-o-T-a
Copy link

M-o-T-a commented May 7, 2018

@escopecz Hi, it works great i get the form on mautic ,but i get this error.
Mixed Content: The page at 'xxx' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://this-must-exist/'. This request has been blocked; the content must be served over HTTPS.
Could you help me?

@steinjo
Copy link

steinjo commented May 31, 2018

Hi,
thank you so much for providing this script. However, I have a similar problem as M-o-T-a. Additionally, I'm nor sure what the expected behaviour of your script in connection with the form in my application is.

Problem:
I installed your script in the login-form of my application. It gets called correctly and also transmits the form data to mautic where it is stored correctly. The problem is that my login form is not reacting after pressing the submit button: it should close (which it doesn't), call method loginAction in the application's domain controller (which it doesn't) and the user should get logged in (which consequently doesn't happen as well).

The form's action is set as action="../user/login", but controller loginAction never gets called, even if I enter "https://mydomain/user/login" for "this-must-exist" and enter the same as the Redirect URL in mautic in the respective form. If I change the mautic form in mautic to "show text" and set "this-must-exist" as "" it executes nicely (console says 'The submission was successful.'), but the login form doesn't close, the user does not get logged in etc.

My expectation was that the submission of the data to mautic via your JQuery script runs asynchroniously from the PHP-action (= submission of the form to action="../user/login"). This is apparently not the case. Apparently the login-form is waiting for a response from mautic or do you have an idea why is it not processing the request through the controller of my application and closes the login form?

Is there any way to completely asynchroniously submit form-data to mautic, meaning that the submission process (sucessful or not) never disturbs the applications workflow? Would that work with your PHP-script?

I had another problem, which might or might not be related to this and which I raised in the mautic-forum, but never received any king of answer:
https://www.mautic.org/topic/focus-items-keep-re-appearing/

I would really appreciate a short notice if you could help me on this one.

Thanks and regards

@ilearnbydoing
Copy link

this is not working.

@yrammos
Copy link

yrammos commented Oct 21, 2018

Well, it's curious... It is working, in the sense that form contents are uploaded to the Mautic database, but it is also producing CORS errors on the browser's side. The browser complains that a preflight request doesn't pass access control check (this is despite all relevant configuration options being in order on the Mautic end).

@escopecz
Copy link
Author

Ok, so there had to be some change in Mautic. I tested again and had to add these hidden fields in the code example as it was redirecting (302) instead of submitting (200) without it:

<input type="hidden" name="formName" value="" />
<input type="hidden" name="messenger" value="1" />

The code example is updated.

Also make sure that you use the same field names as Mautic does. If you open the Mautic form preview you can see the input like this:

<input id="mauticform_input_email_f_email" name="mauticform[f_email]" value="" class="mauticform-input" type="email">

This means that your input should have name of f_email. Not just email. Like this:

<input type="email" class="form-control" id="f_email" name="f_email" placeholder="Email Address">

Also ensure that you have the domain where the form is submitted in the Mautic's CORS settings.

@yrammos
Copy link

yrammos commented Oct 25, 2018

Thank you very much, @escopecz. The messenger input had indeed escaped me entirely, and as soon as I included it in the query string everything fell into place. Case closed, I suppose.

I did not find any f_-prefixed inputs in the form preview DOM, not even after rebuilding the forms and clearing caches. Are you perhaps using a different Mautic build?

Copy link

ghost commented Oct 29, 2018

Hi there. How much knowledge of js or php must be known to get this working?

My users are filling out a form from the WP plugin eForm. I'd like a contact to be created in Mautic when they fill it out. It that possible with what you've shared? Is there an easier way?

Also thanks for putting this info out there. I thought integration would be a bit easier :(

@felipebossolani
Copy link

Worked very well in my website, thank you so much!

@rvernon9
Copy link

rvernon9 commented Jun 6, 2019

Been trying to make this work all day with no success. I made sure our account has "CORS settings" to restrict domains set to "NO" (at least for now). I submit the form using the standard submit button on a basic HTML page and the form information is submitted okay. When I try to submit via jquery ajax, I keep getting this response:

Access to XMLHttpRequest at 'http://{mysite}/sample/testfly.html?mauticError=This%20form%20is%20no%20longer%20available.' (redirected from 'https://{mysite}.flywheelma.com/form/submit?formId=1') from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My end-goal is to submit the form via server-side code so we don't have make form changes and other things already in place. When I try submitting via server-side, I also get a 302 response redirecting to 'http://{mysite}/testpage?mauticError=This%20form%20is%20no%20longer%20available.' I tried submitting server-side with and without Basic Authentication headers.

Since it works submitting straight from an HTML form, I would think we could duplicate this action via server-side code. I have replicated all of the data being sent server-side as what is sent from the HTML form (looking at both requests via Fiddler). Same fields being submitted. But still get the 302 error.

Any suggestions on what to try next?

Thanks.

@rvernon9
Copy link

rvernon9 commented Jun 6, 2019

Quick note: one other interesting thing. When submitting the basic HTML form (ie. no jquery), I see in Fiddler that a 302 response is given. But the form data is submitted successfully into the mautic form.

@escopecz
Copy link
Author

escopecz commented Jun 7, 2019

@rvernon9 what language do you use server side? If it's PHP then I have a library for that.

The error would suggest that you don't have CORS properly configured and the origin that is in the HTTP request is 'null'. Have you tried to put 'null' to the whitelisted CORS domain list in Mautic configuration?

@rvernon9
Copy link

rvernon9 commented Jun 7, 2019

Thanks for the response. Server side language is Microsoft .Net (specifically, VB.Net, but I can translate from C# as well).

I am sending an "Origin" header from my server-side call.

If the CORS settings are set to "NO" for Restrict Domains, shouldn't that allow all hosts? I'll try changing it back to "YES" (for CORS restricting domains) and adding in null.

UPDATE: adding "null" in CORS domain list in Mautic configuration did not help.
Question -- can you confirm if this is the format that your jquery sends data to Mautic?
{ "mauticform": { "mauticform[make]": "My Make" , "mauticform[drive]": "2WD" , "mauticform[cab]": "No Cab" , "mauticform[first_name]": "john doeCORS" , "mauticform[zip_code]": "50325" , "mauticform[comments]": "testing comments here" , "mauticform[submit]": , "mauticform[formId]": 1 , "mauticform[return]": , "mauticform[formName]": "myform" }}

@incentfit
Copy link

I got this to work for me on Mautic 2.15.2 and PHP 7.1. I used the MauticJS.makeCORSRequest() method to do the request. The reason being the request is coming from a site that has the Mautic JS library loaded but from an action on the page (starting a chat) rather than an actual Mautic form. Here's the code:
MauticJS.makeCORSRequest('POST', 'https://my.mauticsite.com/form/submit', {'mauticform[formId]':9999, 'mauticform[formName]': 'formnamefrommautic', 'mauticform[form_field_from_your_form]':'someformdata', 'mauticform[messenger]': 1});
Just make sure to set all your post variables to match the formId, formName, and formFields...

@blzbruno
Copy link

Thanks, I simplied ur code and worked well with me

  function sendMautic() {
    var name = $("#name").val();
    var email = $("#email").val();
    var whatsapp = $("#whatsapp").val();
    $.ajax({
        url: "https://domain.com/form/submit?formId=XX",
        type: "post",
         enctype: 'multipart/form-data',
          headers: {'X-Requested-With': 'XMLHttpRequest'},
        data: { "mauticform":{
          name : name,
          email : email,
          whatsapp :whatsapp,
          return : "",
          formId : XX,
          formName : "yourformname",
          submit : ""
        }} ,
        success: function (response) {
          console.log("Data: " + response);
           // You will get response from your PHP page (what you echo or print)
        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });
  }

@g00dv1n
Copy link

g00dv1n commented Jan 15, 2020

Another example to send via fetch

function serializeData(obj) {
    if ('string' == typeof obj) {
        return obj;
    }
    return Object.keys(obj).map(function(key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
    }).join('&');
}

async function sendToMautic(name, email) {
    const FORM_ID = XX
    const url = 'https://domain.com/form/submit';
    
    const data = {
        'mauticform[formId]': FORM_ID,
        'mauticform[enter_your_name]': name,
        'mauticform[enter_your_email]': email
    };

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
        },
        body: serializeData(data)
    })
}

@adiux
Copy link

adiux commented Apr 30, 2020

I believe this does no longer work with Mautic v3. I use the same parameters on a production form and on the v3.0.0-beta running locally with DDEV.

The values get added to the form on production. On my local instance, I receive a 500 error

log:
mautic.CRITICAL: Uncaught PHP Exception Doctrine\ORM\ORMInvalidArgumentException: "A new entity was found through the relationship 'Mautic\FormBundle\Entity\Submission#lead' that was not configured to cascade persist operations for entity: Mautic\LeadBundle\Entity\Lead with ID #. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"})." at /var/www/html/vendor/doctrine/orm/lib/Doctrine/ORM/ORMInvalidArgumentException.php line 102 {"exception":"[object] (Doctrine\\ORM\\ORMInvalidArgumentException(code: 0): A new entity was found through the relationship 'Mautic\\FormBundle\\Entity\\Submission#lead' that was not configured to cascade persist operations for entity: Mautic\\LeadBundle\\Entity\\Lead with ID #. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={\"persist\"}). at /var/www/html/vendor/doctrine/orm/lib/Doctrine/ORM/ORMInvalidArgumentException.php:102)"} []

Does anybody else have the same problem?

@YouBuiltThat
Copy link

Is there any intention to get this working in M3?

@benbehringer
Copy link

Another example to send via fetch

function serializeData(obj) {
    if ('string' == typeof obj) {
        return obj;
    }
    return Object.keys(obj).map(function(key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
    }).join('&');
}

async function sendToMautic(name, email) {
    const FORM_ID = XX
    const url = 'https://domain.com/form/submit';
    
    const data = {
        'mauticform[formId]': FORM_ID,
        'mauticform[enter_your_name]': name,
        'mauticform[enter_your_email]': email
    };

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
        },
        body: serializeData(data)
    })
}

Thanks! This works for me with Mautic 3.0.2!

@bebjakub
Copy link

bebjakub commented Nov 12, 2020

@g00dv1n thanks for the inspiration! I added a simple validation.

const formData = new FormData()
formData.append('mauticform[formId]', 1)
formData.append('mauticform[messenger]', 1) // required

// form inputs names
formData.append('mauticform[first_name]', first_name)
formData.append('mauticform[last_name]', last_name)
formData.append('mauticform[email]', email)
formData.append('mauticform[f_message]', message)

fetch('https://yourmautic.com/form/submit', {
  method: 'POST',
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  },
  body: formData,
})
.then(response => response.text())
.then(result => {
  if (result.includes('results')) {
    console.log('Thank you for a message')
  } else {
    console.log('Error')
  }
})
.catch(() => {
});

@digitalmkt
Copy link

The HTML form worked perfectly for me on wordpress and WPBakery. Aafter 2 days of fighting with the mautic 3.2.1 submitform insisting to call http instead of https. Thank you.

@peseotni
Copy link

peseotni commented Jun 30, 2021

I used the code on my website, but it complains that "first_name", "last_name", "email" and "message" is not defined.
I do not know javascript. I tried to define them like this:

formData.append('mauticform[vorname]', document.getElementById('firstname'))
formData.append('mauticform[nachname]', document.getElementById('lastname'))
formData.append('mauticform[email]', document.getElementById('email'))

and it sends a form to Mautic, but those fields are empty.
How do I send the values correctly?

Also, is there a way of doing this for more than just one form on the same website?

thank you for your help.

@bebjakub
Copy link

@peseotni could you provide a minimal example on https://jsfiddle.net/ etc.?

@peseotni
Copy link

peseotni commented Jun 30, 2021

@bebjakub here it is:

https://jsfiddle.net/peseotni/k92dcrzg/#&togetherjs=egReh13vuc

thanks for your help

mautic

this is what I get in mautic

@bebjakub
Copy link

bebjakub commented Jul 1, 2021

@peseotni in your javascript, you have just a script for posting data, but you are missing an event (on click submit button, etc.) to trigger that script and validation of inputs. If you are not familiar with javascript use embeds from mautic administration, pls...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment