I know this question has been asked probably 100 times, but i couldn't find a convincing answer for my situation.
Here is my understanding:
On PHP side:
var obj= json_encode ($array);
so then $array
is available on admin-ajax.php in Json format,
On JS side:
$.ajax({
url: ajax_url,
data: {
action: 'myphpfunction',
nonce:mynonce,
},
dataType: "json",
success: success action
});
Where i'm stuck is that my source is not an array nor a string,but a json file so all data are stored in json format already on the sever side.
Which means json_encode
is not useful here as my source is already json
and an echo
or a print
will not make the data available on the admin-ajax.php but on the current page i'm running on.
So this where i'm stuck, how can i pass this json file to the front end, is there a way to make it available so a simple HTTP GET could be done like that for instance (using jQuery)?
$.getJSON('./path/to/my.json',data,callback);
PS: context i'm migrating a static HTML website which include google map (with data) to a WordPress environment.
So basically, my issue is on the PHP side where my data are already JSON formatted and needs to be push to the front-end (JS).
Hope the question it's clear enough
Thanks for any input which could help me better understand how this is working.
Kindly
EDIT:
Here is what i'm doing for now but it doesn't clean method to me, is there a better way to do this?
PHP:
wp_register_script('google_map', get_template_directory_uri() . '/assets/scripts/map.js', array('jquery'), '1.0.0', true);
wp_localize_script('google_map', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('google_map');
function json_gmap(){
$get_file = file_get_contents(get_template_directory_uri() . '/assets/scripts/config/mapdata.json');
$json_to_array = json_decode($get_file,true);
die (json_encode($json_to_array));
}
add_action('wp_ajax_json_gmap', 'json_gmap'); add_action('wp_ajax_nopriv_json_gmap', 'json_gmap');
JS:
$.ajax({
url: mdu.ajax_url,
data: {
action: 'json_gmap',
nonce:mdu.nonce,
},
dataType: "json",
success: this.mapDataLoaded(self, maparea)
});
Matth.