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
wp_localize_script
does not belong inside your ajax handler, not sure what that's supposed to be doing there.pos NULL