Task: Create a "plugin" on WP, which will generate the form and display it on certain pages. The form, with the help of AJAX, will receive the necessary data from the database, depending on the previously filled items of this form.
Question: How to implement correctly?
If you create a wp_ajax_ (action) hook with a function in the main file of the plugin, make JS connections, then everything works.
It is impossible to make ajax, if all the code above, add to the main file with the help of include. Error 400 pops up
Code in the main plugin file:
include_once UrlPlugin.'addEditVote/AddEditVote.php'; The file AddEditVote.php (everything below is located in a separate folder):
// при срабатывании хука действия wp_ajax с экшеном hello, выполняется функция say_hello add_action( 'wp_ajax_hello', 'say_hello' ); function say_hello() { echo "УРАААААААААААА!"; wp_die(); } // при хуке действии wp_enqueue_scripts, вызываем функцияю, которая зарегистрирует JS код обработчика AJAX и выставил её после jQuery add_action('wp_enqueue_scripts', function () { wp_enqueue_script('ajaxAddEditVote', plugins_url('ajaxAddEditVote.js', __FILE__), array('jquery'), null); // До вывода JS, вызванного wp_enqueue_script, выводим JS объект с какими либо значениями wp_localize_script('ajaxAddEditVote', 'localizePlugin', array( 'ajaxURL' => admin_url('admin-ajax.php') )); }); And the JS file ajaxAddEditVote.js:
jQuery(document).ready( function() { var data = { action: 'hello' }; jQuery.post(localizePlugin.ajaxURL, data, function (response) { alert('Получено с сервера: ' + response); }); }); How to do it correctly (the sequence of connecting files and requests, read a bunch of topics, and as a result, complete confusion =). thank) ?