Add Hidden Field onSubmit
Hi!
I’m having difficulties setting up a XHR call that gets triggered in the onSubmit event of a form.
After I receive the data back from the POST call, I need to store it in some hidden fields in order to have them saved in the marketo database, the issue is that this data is not being saved.
form.onSubmit(function(){
var accessToken = "";
var codeSentback;
var dataToSend = ' {"firstname": "' + form.vals().FirstName + '","lastname": "' + form.vals().LastName + '"}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://test');
xhr.setRequestHeader('Content-type','application/json');
xhr.send(dataToSend);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var returnedData = JSON.parse(this.responseText);
form.addHiddenFields({
assessmentdata: returnedData.data
});
}
};
});
I believe the issue is that by the time I received the data back from the POST call, the form it’s already being sent, so I’m adding the hidden field too late.
I have tested that I receive the data from the POST call ok, so that's not the issue.
How can I maybe stop the submit process and only send the form after I have received the data back and the hidden field is populated?
Thanks!