I'm writing a WordPress plugin. My plugin has forms that post data to other pages generated by my plugin within the WordPress dashboard. I am trying to create an AJAX function that is triggered when the form is submitted. My AJAX is working just fine - just to test it, I triggered the event when I click on my plugin header, and it works perfectly fine there. However, if I try to trigger the event when I click a submit button (any input type="submit"), it doesn't work. The JavaScript runs just fine, but it can't find the PHP function to run.
Here is my JavaScript:
$('.button').on('click', function (e) {
var url = testingajax.ajaxurl;
var data = {
'action': 'testing_ajax_wtf',
}
$.post(url, data, function (response) {
console.log(response);
});
});
The PHP function just returns a string (for testing purposes).
This works just fine if I change the first line to:
$('.my-plugin-header').on('click', function (e) {
But if I try to trigger it when a submit button is clicked, or when a form is submitted, the JavaScript runs, but it cannot find the PHP function.
Any idea what is going on here? Does WordPress somehow stop you from running AJAX when you submit forms in the dashboard?
(Also, FYI, I posted this question here as well: http://wordpress.stackexchange.com/questions/189241/cant-trigger-an-ajax-function-with-a-submit-button-in-the-dashboard/189244?noredirect=1#comment275919_189244 At first I thought that adding $('#your_form_id').submit();
was a reasonable workaround, but then I realized that submit() doesn't actually send the value of the submit button, and that value is vital to what I am doing (some forms have a yes button and a no button)).
So is there a way I can run an AJAX function when clicking a submit button in the dashboard?