We’ve had quite a few people ask for it and Fabian has done a fantastic job of adding AJAX support to ACF forms powered by the Advanced Forms WordPress plugin. This feature is available to both free and pro versions of the plugin as of version 1.8.0.
AJAX is support is easy to enable and there are a few hooks and filters you might find useful when leveraging the power of Advanced Forms Pro for ACF.
Enable AJAX on any form by simply defining the ajax
property
Whether you are using the shortcode or the PHP function to load up your form, you can easily enable AJAX submissions. If using the shortcode, just add ajax="1"
to your shortcode string and you’re done. e.g;
[advanced_form ajax="1"]
If you are using the PHP function, all you need to do is add 'ajax'=>true
to the config array. e.g;
Modify AJAX responses using PHP before they are sent to the browser
If you need to change the outcome depending on the values of the submitted form, then you can hook into the af/form/ajax/response
filter and modify the response accordingly. You might do this if you need to redirect a user in some circumstances, show a different response message depending on submitted data, or even add you own data for use in a custom AJAX JavaScript callback.
Here is an example of redirecting a user when they provide a rating less than a certain value. In this example, you might redirect the user to a follow up form to collect more information or perhaps to some kind of special offer page.
Fire custom JavaScript handlers on successful AJAX submissions
When an ACF form is submitted via AJAX, a JavaScript hook is fired using the JavaScript API provided by Advanced Custom Fields. Using this hook, it is possible to run any custom JavaScript code you need after a form is submitted. You may wish to fire custom tracking scripts, open a modal window, replace the form with a custom markup block, and more. There are many possibilities at hand and the basic recipe you need for this looks like this:
Customise the success message on the fly
If you need to modify the success message using JS, this is easy to do as you can see in the following example:
Change a message to a redirect on the fly
Similar to the previous example, you may have a situation where you need to redirect somebody based on certain conditions, perhaps using custom data you’ve added while customising the AJAX response via PHP. Here’s an example of changing the AJAX behaviour so that it redirects the user:
Conclusion
With the added power of AJAX based submissions, Advanced Forms offers even more possibilities for faster user experiences. The hooks and filters give you, the developer, a whole lot of flexibility in how you craft your WordPress websites.