简体   繁体   中英

Using front-end AJAX in WordPress plugin

I'm trying to write an AJAX request as a WordPress plugin. I initially made the request to an outside non-WP server (where it ran fine) simply for testing because I'm entirely new to developing for WP. I then tried using wp_localize_script and .ajaxurl according to the WP codex, but the only response I'm getting is a '0' from admin-ajax. Here is the plugin code:

imap.php:

<?php
/**
 * Plugin Name: JQVMap & ChartJS World Map
 * Author:      Jesse Dillman
 */
add_action( 'wp_enqueue_scripts', 'enqueue_dependencies' );

function enqueue_dependencies()
{
    # Run only on given page
    if( !is_page(229) )
        return;

    # Enqueue styles
    wp_enqueue_style( 'jmap-css', plugins_url( '/css/jqvmap.css', __FILE__ ) );

    # Register dependencies files
    wp_register_script( 'js', plugins_url( '/js/jquery-1.7.2.min.js', __FILE__ ) );
    wp_register_script( 'jmap-js', plugins_url( '/js/jquery.vmap.js', __FILE__ ) );
    wp_register_script( 'world-js', plugins_url( '/js/jquery.vmap.world.js', __FILE__ ) );
    wp_register_script( 'unregions-js', plugins_url( '/js/jquery.vmap.un_regions.js', __FILE__ ) );
    wp_register_script( 'regioncolors-js', plugins_url( '/js/region_colors.js', __FILE__ ) );
    wp_register_script( 'chart-js', plugins_url( '/js/Chart.js', __FILE__ ) );

    # Enqueue custom JS file along with dependencies
    wp_enqueue_script( 
        'start-js', 
        plugins_url( '/js/start.js', __FILE__ ), 
        array( 'js', 'jmap-js', 'world-js', 'unregions-js', 'regioncolors-js', 'chart-js' ), // dependencies
        false,
        true  
    );

    wp_localize_script( 'start-js', 'get_data', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
}


function get_chart_data(){
$region1Pie = array(50, '#ddd', 50, '#dc7d50');
$region2Pie = array(25, '#ddd', 75, '#7a9e89');
$region3Pie = array(75, '#ddd', 25, '#867e40');

$chartData = new stdClass();
$pieData = array();

// Swtich based on region
switch($_REQUEST['region']) {
  case 'China':
    $pieArray = $region1Pie;
    break;
  case 'Canada':
    $pieArray = $region2Pie;
    break;
  case 'Brazil':
    $pieArray = $region3Pie;
    break;
}

for($i=0; $i<count($pieArray); $i+=2) {
  $pie= new stdClass();
  $pie->value = $pieArray[$i];
  $pie->color = $pieArray[$i+1];
  $pieData[] = $pie;
}

$chartData->pieData = $pieData;
echo json_encode($chartData);

die();
}

add_action('wp_ajax_get_chart_data', 'get_chart_data');
add_action('wp_ajax_nopriv_get_chart_data', 'get_chart_data');
?>

start.js:

// get pie chart canvas
var pie= document.getElementById("pie").getContext("2d");


jQuery(document).ready(function() {

    jQuery('#vmap').vectorMap({
        map: 'world_en',
        backgroundColor: '#fff',
        // more config options....
        onRegionClick: function(element, code, region)
        {
            $.ajax(get_data.ajaxurl, {
                data: {region: region},
                action: 'get_chart_data',
                dataType: 'json',
                success: function(response) {
                    new Chart(pie).Doughnut(response.pieData, pieOptions);
                }
            });
        }   
    });
});

When running correctly outside of WP, this renders a world map that displays a pie chart using different data tables depending on where the user clicked. It uses ChartJS and JQVMaps. Again, I'm new to using AJAX in WordPress. Am I using localize_script incorrectly, or is there another problem with how I've implemented the WP admin-ajax?

Get rid of the

action: 'get_chart_data',

in your AJAX call and add it to the data attribute like so...

data: {'region': region, 'action': 'get_chart_data'}, 

That should get the action being passed into WP so it can get matched to the wp_ajax_get_chart_data action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM