I am using an external service (emailmeform.com) to handle my contact forms on my site. The only real issue with this service is that there is no public api access to perform server requests to using AJAX. So the only way to send my forms (that I know of) is to just execute submit() and let the form build up its request headers normally, send the data, and let the response redirect me to a static page I provide in emailmeform.com's form manager.
But what I'm really wanting to do is (in this order):
- Use AJAX to POST the form to my OWN server
- If response is OK, POST the form to emailmeform's server
- If response is OK, let my server handle it from there (dont redirect me automatically).
I have already completed #1 above. Here is my code:
function submitForm(id, action, postData) {
$.ajax({
data: postData,
type: 'POST',
url: action,
success: function(data){
console.log("yay!");
}
});
}
$('button[type="submit"]').on('click', function(e) {
var id = {{ $business->id }},
form = $('#business-contact-form'),
action = form.attr('action'),
postData = form.serialize();
e.preventDefault(e);
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('[name="_token"]').val()
}
})
$.ajax({
data: postData,
type: 'POST',
url: "/contact/contact-submit/"+id,
success: function(data){
console.log(data);
form.submit(); // this works, but redirects me
// submitForm(id, action, postData); // this doesn't work
},
error: function(data, response){
console.log('error: '+ response);
}
});
});
The form HTML is generated automatically, using an embed code provided to me through emailmeform. This form contains lots of javascript logic, which I guess generates the proper headers for the POST request. So if I were to POST to the form action using submitForm(), I get an error:
XMLHttpRequest cannot load http://www.emailmeform.com/builder/form/0o350Mh8Zda. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://trustdale.dev' is therefore not allowed access.
Yes. I am posting using my local dev server (if that matters).
So I guess my question is, how would I POST my form data to emailmeform's servers with the correct request headers? The logic is here in my form code... but I cant make sense of it to make my own request!