vars vars - 1 year ago 66
Ajax Question

WordPress Plugin => How to use JS AJAX to trigger plugin PHP functions

Building my first plugin, I'm having difficulty communicating between scripts. How to use JS AJAX to call the plug-in PHP script handling my functions.

I'm finding that loading the plug-in script NOT in WordPress is (obviously) causing rendering/permission issues.

Here's a boiled down version - the plugin is instantiated via a shortcode:


  • This kicks off the WP plug-in, carrying out some preliminary tasks.

  • After the DOM is loaded, I use HTML5 to find the user's geolocation.

Goal: Pass HTML5 geolocation data via AJAX to a php function located in the php file. Eg: Call to undefined function register_activation_hook()

var sf_path = jQuery('#sf_path').val();
var url = '/wp-content/plugin/plugin_name/plugin_name.php?h=true&=lat='+position.coords.latitude+'&lng='+position.coords.longitude;
var jqxhr = jQuery.get( url , function(data) {
console.log( "geolocate", data );
//Response = PHP Error: Call to undefined function register_activation_hook()

I think I can rewrite the code to differentiate platforms and run differently based on the request (basically, unwordpressify certain functions) but it would be much handier to NOT have to do that. wp_remote_get is very handy as is.

What am I missing?

Answer Source

The WP ajax calls are handled through the admin-ajax.php script. First, what you need to do is to register actions -

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

Next, you need to define what this my_action_callback would be doing.

function my_action_callback() {
    // Handle Geo Location Data
    wp_die(); // this is required to terminate immediately and return a proper response

Once done, you can send the AJAX call

<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        'action': 'my_action',
        'geo': 1234
    };, data, function(response) {
        alert('Got this from the server: ' + response);

If ajaxurl is undefined, you can define it this way -

var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";

You can find more about that on the documentation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download