I have a form created with Elementor Pro on my WordPress website. After clicking the button, I can process the results in some way using the WordPress backend, but at the same moment the form is reloaded and all fields have default values again. In some cases, this hinders greatly – for example, when you are trying to build a simple web application.
To be specific, let’s build the form to add two numbers (this tutorial).
Frontend looks like this:
HTML code for "The result will appear here" element:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
jQuery( document ).ready(function( $ ){
jQuery( document ).on('submit_success', function(event, response){
document.getElementById("result").innerHTML = response.data['1'].result;
});
});
</script>
<p id='result'>The result will appear here.</p>
PHP code (in Code Snippets WordPress plugin):
function add_two_numbers($fields) {
$a = $fields['a'];
$b = $fields['b'];
return $a + $b;
}
// A send custom WebHook
add_action( 'elementor_pro/forms/new_record', function( $record, $handler ) {
// make sure its our form
$form_name = $record->get_form_settings( 'form_name' );
if ( 'AdderForm' !== $form_name ) {
return;
}
$raw_fields = $record->get( 'fields' );
$fields = [];
foreach ( $raw_fields as $id => $field ) {
$fields[ $id ] = $field['value'];
}
$output['result'] = add_two_numbers($fields);
$handler->add_response_data( true, $output );
}, 10, 2 );
I’ve been trying to dig into the Elementor documentation, setting dynamic "default" values, exploring form setting and googling things like "Elementor don’t reload form after submit", "Elementor save default values form", etc, but I didn’t find anything. Apparently, official Elementor tools does not allow you to do this, which, in my opinion, is quite weird.
I found a solution that I want to share with others, but it doesn’t seem intuitive to me. Feel free to comment if you know the better solution or if the new versions of Elementor allow you to do this.
2
Answers
The answer I found is to explicitly return the current values of the form fields and display them using jQuery.
To do this, change the PHP code as follows (CHANGE line):
And jQuery script for the HTML element:
When an elementor form is sent several triggers will be fired, the one we need to listen is reset, that is fired into the onSubmit function (form.bundle.min.js)
Source image form.bundle.min.js
So we can listen for this event and prevent its execution using e.preventDefault(). This "filter" will be executed on all the reset events.
If you want to prevent the reset only on specific forms you can also check the target’s id value: