I have a desktop app and I use $.getJSON to get data from my wordpress site using the plugin the WP REST API. This works fine and so I assume I can also make an Ajax call to a function in the functions.php? How do I do this? None of the examples I have seen supply the ajaxURL. How do I find out what this is?
I have the following code:
Functions.php (in wordpress site on server)
//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
print_r($files);
return $files;
die();
}
add_action('wp_ajax_my_action', 'folder_contents');
app.js (run using node webkit locally from machine)
//ajax call
var data = {
action: 'path',
path: datafolder;
};
var ajaxurl = baseurl + ''; //WHAT IS THIS?!?!
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
-------------------EDIT----------------------
After the answer below I have tried the below code based on the advice but I get
"index.html:324 Uncaught ReferenceError: ajax_params is not defined"
Functions.php
//add code to use ajax
function add_ajax_script() {
wp_localize_script( 'ajax-js', 'ajax_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
wp_send_json($files);
die();
}
add_action('wp_ajax_folder_contents', 'folder_contents');
add_action('wp_ajax_nopriv_folder_contents', 'folder_contents');
add_action( 'wp_enqueue_scripts', 'add_ajax_script' );
App.js
//ajax call
var data = {action: 'powerpoint_folder_contents',path: datafolder};
var ajaxurl = ajax_params.ajax_url;
console.log(ajaxurl);
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
If I remove the add_ajax_script() function and simply use the below it returns 0.
var ajaxurl = baseurl + 'wp-admin/admin-ajax.php';
Please help...