I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg_code) which is a combination of submission date and a random number to make it unique.
So I added an hidden input field to my CF7 code with the id "reg_code". On my first try, I used JS to generate a "reg_code" variable right after users visit my site and set the hidden field value to the generated "reg_code" variable. The "reg_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg_code" would not be correct because that code was generated at his first visit time and cached in the browser.
To avoid this issue, I decided to move the "reg_code" generation function from JS to PHP and the procedure would be like this:
- Submit button clicked
- Use AJAX to call a PHP function which returns a reg_code
- Set the hidden field "reg_code" in CF7 value to the returned result
- Really perform CF7 submission which saves all CF7 fields to Flamingo
This is my JS to trigger the AJAX call before CF7 submit event:
$('.wpcf7-form').on('submit', function (e) {
$.ajax({
type: "post",
dataType: "json",
url: js_object.ajax_url,
data: {
action: "custom_reg_code",
},
success: function (response) {
if (response.success) {
$('#reg_code').val(response.data)
}
else {
console.log('Something wrong')
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('fail: ' + textStatus, errorThrown);
},
complete: function() {
}
})
})
My result: It works only some times. Only some submissions have "reg_code" value, some others have empty "reg_code".
As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add e.preventDefault() to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck.
Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ?
Thank you very much