javascript – How to make Contact Form 7 work when injected via AJAX in WordPress?
I am working on a WordPress project where I need to use Contact Form 7 as part of an AJAX response to check if certain data is available. However, I am facing an issue where the form is not working as expected.
Here’s the scenario: When an AJAX request succeeds, I return the Contact Form 7 shortcode as part of the JSON response like so:
wp_send_json_success(array(
// ...
'form' => apply_shortcodes('
')
));
In my AJAX response handler, I include the form in the HTML as follows:
let formData = data.form;
let summary =`${formData}`;
document.getElementById('element').innerHTML = summary;
However, when I attempt to submit the form, I am redirected to a new page that only contains the text “0”. Additionally, the browser console logs a 400 Bad Request error pointing to admin-ajax.php
as follows:
domain.localpc/wp-admin/admin-ajax.php 400 (Bad Request), filename : admin-ajax.php#wpcf7-f87-o1:1
I am unsure of what might be causing this issue. Is there a specific way to make Contact Form 7 work in JavaScript, especially when it’s being injected into the page as a response to an initial AJAX request? Any insights or solutions would be greatly appreciated.
Thank you!
Leave an answer