I'm working on a Wordpress Google Maps plugin which pulls locations from a database via Ajax and returns an XML file which is then processed by a Javascript script so that they can be plotted them on a Google Map. This all works perfectly but I'd like to be able to restrict the data that it displayed to just those locations that are owned by the currently logged in user. As the WP users id is stored in the table this should be easy ...
In my theme functions.php file I have this function:
// Same handler function...
add_action( 'wp_ajax_get_current_user_id', 'get_current_user_id_callback' );
function get_current_user_id_callback() {
if (is_user_logged_in()) {
echo get_current_user_id();
wp_die();
}
}
add_action('template_redirect', 'my_enqueue');
function my_enqueue() {
// Enqueue the Javascript file
wp_enqueue_script( 'ajax-script', '/ajax/ajax-user.js', array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )) );
}
In the Javascript file which processes the XML I have the following function:
function getUserId() {
var data = {'action': 'get_current_user_id'};
jQuery.post(ajax_object.ajax_url, data, function(response) {
userId=response;
alert ('Within JQuery userId=' + userId);
return userId;}
);
}
Which is called by this when the script loads:
var userId;
function load () {
userId=getUserId();
alert ('Outside of JQuery UserId=' + userId);
}
The problem is that getUserId runs and returns undefined before it's had time to get the response from the database. I know the solution to this is to user Ajax promises but I cannot find anywhere a working example on how to do this specifically within Wordpress.
According to this:
How do I return the response from an asynchronous call?
I just need to rewrite my getUserId function so that it includes .done and .fail but if I try this I get syntax errors as it's not really JQuery
How would I rewrite getUserId in the JQuery syntax so that I can use .done and .fail and call it from my existing script ? Sadly I'm no JQuery expert and I'm not much better at Javascript !