2

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

2
  • wp_localize_script does not belong inside your ajax handler, not sure what that's supposed to be doing there.
    – Milo
    Commented Dec 9, 2017 at 17:21
  • Should I put out of the function? I am sorry but I've tried in many ways and always get pos NULL
    – Caesar
    Commented Dec 9, 2017 at 17:24

1 Answer 1

0

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
});
6
  • Thank you a lot Jack! Have made some tries and get Notice: Undefined index: pos in /home/.../wp-content/plugins/zaeplug-userslocation/zaeplug-userslocation.php on line 20 now will make a brake because my eyes are near to explote.
    – Caesar
    Commented Dec 8, 2017 at 10:56
  • I'm getting NULL Notice: Undefined index: pos in /home/.../wp-content/plugins/zaeplug-userslocation/zaeplug-userslocation.php on line 21 NULL
    – Caesar
    Commented Dec 8, 2017 at 11:07
  • It seems there is a problem with the variable
    – Caesar
    Commented Dec 8, 2017 at 11:07
  • Nothing, I wrote it without apostrophes and get the same notice. In my_function() have written the php from the template-userslocation.php. After trying to declare also the pos variable out of the conditional as var pos; get the same answer. Have changed lat: position.coords.latitude, lng: position.coords.longitude to real coordinates like: lat: 43.362344, lng: -8.411540 and stil get NULL. Thank you for your support Jack.
    – Caesar
    Commented Dec 9, 2017 at 6:06
  • Added the changes that I've done to the question. Thank you!
    – Caesar
    Commented Dec 9, 2017 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.