Last active
August 5, 2022 22:06
-
-
Save simplistik/765dee17f6404e1cd77df32a37648fd6 to your computer and use it in GitHub Desktop.
Convert ACF (Advanced Custom Fields) front-end forms into an AJAX submitted form. Disabling page refresh.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable */ | |
/** | |
* Disables the refresh logic that ACF front-end forms uses in favor | |
* of a custom AJAX submission. | |
* | |
* This was tested with ACF 5.12.3 | |
* | |
* This logic makes a few assumptions: | |
* 1. ACF is queued and your script is properly defining it as a dependency. | |
* 2. jQuery is queued; ACF already does this so it shouldn't be an issue. | |
* 3. You know how to do an AJAX hook in WP: https://codex.wordpress.org/AJAX_in_Plugins. | |
* 4. You know how to create your own logic to process the form, or how to dig into | |
* code and copy it. | |
* 5. You're amazing and already use https://www.acf-extended.com/ to enhance ACF. | |
*/ | |
if ( acf !== 'undefined' ) { | |
acf.addAction( 'validation_success', ( $el, json ) => { | |
const $formEl = $( $el ); | |
/** | |
* Custom class set on the form just to ensure I'm doing | |
* what I want on the correct form | |
*/ | |
if ( ! $formEl.hasClass( 'force-ajax-submission' ) ) return; | |
/** | |
* You could check for json.data.errors here if you're feelin froggy. | |
*/ | |
$formEl.on( 'submit', ( event ) => { | |
event.preventDefault(); | |
/** | |
* Forces the form to lock itself to prevent submissions. This happens automatically | |
* during the first submission, but doesn't happen automatically after subsequent | |
* submissions, which makes this redundant the first time, but doesn't impact performance. | |
*/ | |
acf.lockForm( $formEl ); | |
const data = acf.serialize( $formEl ); | |
/** | |
* Your custom action will do all the submission similar to | |
* how ACF already does it. I recommend just finding their | |
* method and jacking it =) | |
*/ | |
data.action = 'tprt_custom_action'; | |
$.ajax( { | |
url: acf.get( 'ajaxurl' ), | |
data: acf.prepareForAjax( data ), | |
type: 'post', | |
dataType: 'json', | |
error( jqXHR, textStatus, errorThrown ) { | |
console.log( [textStatus, errorThrown] ); | |
acf.unlockForm( $formEl ); // Reset the ACF form back to normal. | |
}, | |
success( data, textStatus, jqXHR ) { | |
console.log( textStatus ); | |
}, | |
complete( jqXHR, textStatus ) { | |
console.log( textStatus ); | |
acf.unlockForm( $formEl ); // Reset the ACF form back to normal. | |
} | |
} ); // End $.ajax | |
} ); // End submit listener | |
} ); // End validation_success hook | |
} // End acf check |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment