Home › Forums › General Issues › Frontend form – post via ajax? › Reply To: Frontend form – post via ajax?
OK this is just a thought as I am only just starting to tackle this myself but it seems that if you just add a bit of javascript to prevent the submit button, you can get all the form fields into an object yourself and then post that through ajax the same way you would any other form.
A brief theoretical code example:
jQuery(":submit").click(function(event){
event.preventDefault();
var form_data = {"action" : "acf/validate_save_post"};
jQuery("form#post :input").each(function(){
form_data[jQuery(this).attr("name")] = jQuery(this).val()
})
jQuery.post(ajaxurl, form_data) // you will need to get the ajax url for you site
.done(function(data){
//you get back something like {"result":1,"message":"Validation successful","errors":0}
})
})
That would validate the form. After that, you need to submit it. To do that, add actions somewhere in your functions.php to point ajax requests to the acf head function:
add_action( 'wp_ajax_save_my_data', 'acf_form_head' );
add_action( 'wp_ajax_nopriv_save_my_data', 'acf_form_head' );
That will point ajax requests to the acf form head function.
then you can call that using the same js
form_data.action = "save_my_data";
jQuery.post(ajaxurl, form_data)
.done(function(save_data){
console.log(save_data)
})
This can go in the return function of the validation ajax call, with an if statement to check the validation came back ok.
Only problem I have found so far is it returns a url it wants to go to which throws a js error. Working on that now…
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.