R
R
Roman2018-04-17 15:13:49
JavaScript
Roman, 2018-04-17 15:13:49

How to implement AJAX in wordpress plugin in switch?

Immediately the code that does not work is at the end of the question =):

The main file of the wordpress plugin:

define('UrlPlugin', plugin_dir_path(__FILE__));	// Путь до плагина
    
    switch ($_SERVER['REQUEST_URI']) { // Навигация по сайту
    	case '/vyistavit-redaktirovat-golosa':
    		include UrlPlugin.'addEditVote/AddEditVote.php';
    		break;
    }


AddEditVote.php file:

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')
    	));
    });


JS with AJAX request added in the previous file:

var data = {
    	action: 'hello',
    };
    jQuery.post(localizePlugin.ajaxURL, data, function (response) {
    	alert('Получено с сервера: ' + response);
    });


Needed:

- So that AJAX would work on a certain page of the site and all files
associated with it would be stored in a separate plugin folder.
- In the code above, all paths are spelled out correctly (rechecked many times),
action for unauthorized people is not required.
- If from
switch

pull out
include UrlPlugin.'addEditVote/AddEditVote.php';


And just place it in the main plugin file, then everything works, but on all pages of the site. As soon as you drive into switch or if, it stops working and a 400 AJAX error appears

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question