AJAX in WordPress, sending coords data to MySQL and show after into map

I’ve spent some months trying to figure out how to get users geolocation and pass it into MySQL and so after being shown with markers on the map. I’ve got stuck already in passing the data through ajax to php. And have search and research and also asked in stackoverflow. And as it seems my code is correct.

It seems that AJAX has a special way to work with WORDPRESS.

Here the code that exists in template-maps.php:

  var pos;
  var infoWindow = new google.maps.InfoWindow({map: map});
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            infoWindow.setPosition(pos);
            infoWindow.setContent('You are here');
            map.setCenter(pos);
            $.ajax({
                type: 'POST',
                data:  { action : 'my_action', pos : pos},
                url: '/wp-admin/admin-ajax.php'
            });
        },
        function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    };

What I have to write with the WordPress Codex to make my AJAX work?

Here the changes that I’ve made so far, creating a plugin for add function my_function ():

<?php

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

    $translation_array = array(
        'admin_uri' => admin_url('admin-ajax.php') ,
    );
    wp_localize_script( 'script-handle', 'object_name', $translation_array );

    function my_function(){

         $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
         $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;


       var_dump($_POST['pos']);

    }

?>

And here the Notice that I get from the plugin:

Notice: wp_localize_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /…/wp-includes/functions.php on line 4146

and this one:

Notice: Undefined index: pos in /…/wp-content/plugins/zaeplug-userslocation/zaeplug-userslocation.php on line 26 NULL

1 Answer
1

You can’t and shouldn’t directly ping any PHP file inside your theme or plugin folder. It’s not safe, and most importantly, will almost never work since you don’t have access to WordPress’s core.

Instead, create an Admin-Ajax handler and process your code there.

To create one, all you have to do is add these lines to your theme’s functions.php file:

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

function my_function(){
    // Your php code here
}

Now, alter your ajax request to ping the admin-ajax.php file:, and include the action in your data:

$.ajax({
    type: 'POST',
    data:  { action : 'my_action', pos : pos},
    url: '/wp-admin/admin-ajax.php'
});

However, I suggest you use wp_localize_script to pass the admin_url() to your Ajax function.

Let’s say you have enqueued your JS file the following way:

add_action( 'wp_enqueue_scripts', 'my_localization_function');
function my_localization_function(){
    // Enqueue your script
    wp_enqueue_script( 'script-handle', 'my-script-url' );
}

You then can localize it. Add this after you enqueue your script:

$translation_array = array(
    'admin_uri' => admin_url('admin-ajax.php') ,
);
wp_localize_script( 'script-handle', 'object_name', $translation_array );

Now, your Ajax call can be this:

$.ajax({
    type: 'POST',
    data:  { action : 'my_action', pos : pos},
    url: object_name.admin_uri
});

Leave a Comment