Using front-end AJAX in WordPress plugin - javascript

I'm trying to write an AJAX request as a WordPress plugin. I initially made the request to an outside non-WP server (where it ran fine) simply for testing because I'm entirely new to developing for WP. I then tried using wp_localize_script and .ajaxurl according to the WP codex, but the only response I'm getting is a '0' from admin-ajax. Here is the plugin code:
imap.php:
<?php
/**
* Plugin Name: JQVMap & ChartJS World Map
* Author: Jesse Dillman
*/
add_action( 'wp_enqueue_scripts', 'enqueue_dependencies' );
function enqueue_dependencies()
{
# Run only on given page
if( !is_page(229) )
return;
# Enqueue styles
wp_enqueue_style( 'jmap-css', plugins_url( '/css/jqvmap.css', __FILE__ ) );
# Register dependencies files
wp_register_script( 'js', plugins_url( '/js/jquery-1.7.2.min.js', __FILE__ ) );
wp_register_script( 'jmap-js', plugins_url( '/js/jquery.vmap.js', __FILE__ ) );
wp_register_script( 'world-js', plugins_url( '/js/jquery.vmap.world.js', __FILE__ ) );
wp_register_script( 'unregions-js', plugins_url( '/js/jquery.vmap.un_regions.js', __FILE__ ) );
wp_register_script( 'regioncolors-js', plugins_url( '/js/region_colors.js', __FILE__ ) );
wp_register_script( 'chart-js', plugins_url( '/js/Chart.js', __FILE__ ) );
# Enqueue custom JS file along with dependencies
wp_enqueue_script(
'start-js',
plugins_url( '/js/start.js', __FILE__ ),
array( 'js', 'jmap-js', 'world-js', 'unregions-js', 'regioncolors-js', 'chart-js' ), // dependencies
false,
true
);
wp_localize_script( 'start-js', 'get_data', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
}
function get_chart_data(){
$region1Pie = array(50, '#ddd', 50, '#dc7d50');
$region2Pie = array(25, '#ddd', 75, '#7a9e89');
$region3Pie = array(75, '#ddd', 25, '#867e40');
$chartData = new stdClass();
$pieData = array();
// Swtich based on region
switch($_REQUEST['region']) {
case 'China':
$pieArray = $region1Pie;
break;
case 'Canada':
$pieArray = $region2Pie;
break;
case 'Brazil':
$pieArray = $region3Pie;
break;
}
for($i=0; $i<count($pieArray); $i+=2) {
$pie= new stdClass();
$pie->value = $pieArray[$i];
$pie->color = $pieArray[$i+1];
$pieData[] = $pie;
}
$chartData->pieData = $pieData;
echo json_encode($chartData);
die();
}
add_action('wp_ajax_get_chart_data', 'get_chart_data');
add_action('wp_ajax_nopriv_get_chart_data', 'get_chart_data');
?>
start.js:
// get pie chart canvas
var pie= document.getElementById("pie").getContext("2d");
jQuery(document).ready(function() {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#fff',
// more config options....
onRegionClick: function(element, code, region)
{
$.ajax(get_data.ajaxurl, {
data: {region: region},
action: 'get_chart_data',
dataType: 'json',
success: function(response) {
new Chart(pie).Doughnut(response.pieData, pieOptions);
}
});
}
});
});
When running correctly outside of WP, this renders a world map that displays a pie chart using different data tables depending on where the user clicked. It uses ChartJS and JQVMaps. Again, I'm new to using AJAX in WordPress. Am I using localize_script incorrectly, or is there another problem with how I've implemented the WP admin-ajax?

Get rid of the
action: 'get_chart_data',
in your AJAX call and add it to the data attribute like so...
data: {'region': region, 'action': 'get_chart_data'},
That should get the action being passed into WP so it can get matched to the wp_ajax_get_chart_data action.

Related

What prevents wp_enqueue_script inside a loop_start

The wp_enqueue_script operates fine as a stand alone script in the main function file. However, when this is placed inside a loop_start function (isolated to run on a specific page), the javascript it calls does not load. Both the 'page name' and post ID work in is_page( ) validated by $message.
add_action( 'loop_start', 'run_on_config_page' );
function run_on_config_page() {
if ( is_page( 1885 ) ) {
function config_scripts() {
wp_enqueue_script( 'config_scripts', get_stylesheet_directory_uri() . '/js/myscript.js', array( 'jquery' ) , '0.0.1', time(), true );
}
add_action( 'wp_enqueue_scripts', 'config_scripts' );
// $message = "Load Script Here";
// echo "<script type='text/javascript'>alert('$message');</script>";
}
}
You are doing it wrong. Use this code to fulfill your requirement.
function config_scripts() {
if( is_page( 1885 ) ){
wp_enqueue_script( 'config_scripts', get_stylesheet_directory_uri() . '/js/myscript.js', array( 'jquery' ) , '0.0.1', time(), true );
}}
add_action( 'wp_enqueue_scripts', 'config_scripts' );

Remove WooCommerce Product Addons addons.min.js script from output

The function code below outputs a referral to a javascript file called addons.min.js I believe this is done in line 6 of the code.
Because I don't want to edit the plugins core addons.min.js file I have created my-custom-addons.min.js file and added it to the wp-footer (via wp_enqueue_script).
All good but I can't remove the original referral.
I tried to use
// Remove plugins core addons.min.js
function iw_wcpa_script_remove() {
if ( is_product() ) {
wp_dequeue_script( 'woocommerce-addons' );
wp_deregister_script( 'woocommerce-addons' );
}
}
add_action( 'wc_quick_view_enqueue_scripts', 'iw_wcpa_script_remove', 99 );
// Add custom addons.min.js
function iw_wcpa_script_add() {
if ( is_product() ) {
wp_enqueue_script( 'iw-woocommerce-addons', get_site_url() . '/wp-content/uploads/iwebbers/js/addons.min.js' );
}
}
add_action( 'wp_footer', 'iw_wcpa_script_add' );
But addons.min.js still keeps coming up in my HTML output like this:
<script type='text/javascript' src='https://iwebbers.com/wp-content/plugins/woocommerce-product-addons/assets/js/addons.min.js'></script>
I'm completely in the dark here how to get this done.
Anyone?
If it helps, here's the live page to see the whole HTML source:
https://iwebbers.com/samenstellen/gratis-website-pakket
And just to be clear, I can't edit the function below because it's plugins core.
public function addon_scripts() {
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting' . $suffix . '.js', array( 'jquery' ), '0.4.2' );
wp_enqueue_script( 'woocommerce-addons', plugins_url( basename( dirname( dirname( __FILE__ ) ) ) ) . '/assets/js/addons' . $suffix . '.js', array( 'jquery', 'accounting' ), '1.0', true );
Try to hook wp_enqueue_scripts instead of wp wp_footer with the high priority value:
add_action( 'wc_quick_view_enqueue_scripts', 'iw_wcpa_custom_script', 99 );
UPDATE
replace wocoomerce-addons with woocommerce-addons in your iw_wcpa_script_remove
Try this:
function remove_product_addons_js() {
wp_dequeue_script( 'woocommerce-addons' );
}
add_action( 'wp_print_footer_scripts', 'remove_product_addons_js', 0 );

Add php to js file

I am working on a USA map with states to show which states have available properties by changing the color of the state.
I am using Leaflet for the map and have used the Interactive Choropleth Map (https://leafletjs.com/examples/choropleth/) as a basis to build this.
I have added "availability":"2" to the us-states.js file, this is where the number of properties will be shown. I would like to insert a php query
into the .js file to pull the number of properties for that state. Here is a sample from the us-states.js file so that you can see the layout:
{"type":"Feature","id":"02","properties":{"name":"North Carolina","availability":"2"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-131.602021,55.117982],
And I am using this to change color:
// get color depending on population density value
function getColor(d) {
return d > 1 ? '#e1cb7f' :
'#173e34';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 1.9,
fillColor: getColor(feature.properties.availability)
};
}
This is my php query:
<?php $count = array('post_type' => 'property', 'meta_key' => 'state', 'meta_value' => 'NC'); $myquery = new WP_Query($count); ?>
and I have tried to add this to the js file, but it will not work:
"availability":"<?php echo json_encode($myquery->found_posts) ?>"
If I manually add the number of properties to the us-states.js file the color does change on the map, so the color change part is working, I just cannot get the php to work in the .js file.
Here is my webpage: https://www.thekeithcorp.com/interactive-map/
Any help would be appreciated!
What you are looking for is wp_localize_script
Execute the query
Register the script using wp_register_script
Localize the registered script with the result of the query using wp_localize_script
Enqueue the script using wp_enqueue_script which references the JavaScript array that WordPress adds before the registered script
on WordPress, can pass variables to JS, eg. with the theme's functions.php:
function localize() {
$items = WP_Query ...
wp_register_script( 'custom', get_template_directory_uri() . '/js/scripts.js', array('jquery'), false, true );
$script_vars = ["features" => []];
for($i=0; $i < $items.size(); $i++) {
array_push($script_vars['features'], (object) array(
"id" => 2,
"type" => "Feature",
"properties" => (object) array(
"name" => "North Carolina",
"availability"=> 2
),
"geometry" => (object) array(
"type" => "MultiPolygon",
"coordinates"=> [ ... ]
)
));
}
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'custom' );
wp_localize_script('custom', 'script_vars', $script_vars);
}
if( !is_admin()) {
add_action("wp_enqueue_scripts", "localize", 10);
}
while you just could change the file-name suffix from .js to .php ...however, when integrating the map with WordPress posts, it's better to localize or to use WP AJAX for loading the data asynchronously - or even cache the HTML output, which may not change that much, except when something is being added.
I got this to work using this in the functions file:
wp_register_script( 'scount', get_template_directory_uri() . '/assets/js/us-states.js' );
// Localize the script with our data that we want to use
$args = array(
'post_type' => 'property',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => 'state',
'value' => 'NC'
)
)
);
$results = new WP_Query($args);
$completed = count($results->posts);
wp_localize_script( 'scount', 'completed', $completed );
// The script can be enqueued now or later.
wp_enqueue_script( 'scount' );
And using this in the json file:
( JSON.stringify(completed) )}
Note there is no ";" at the end!

Script not included with wp_enqueue_scripts

I have learned to include scripts the following way.
add_action( 'wp_enqueue_scripts', 'woomps_ajax_frontend' );
function woomps_ajax_frontend() {
wp_enqueue_script( 'woomps_sub_slider', plugins_url( '/js/woomps-ajax-frontend.js', dirname(__FILE__)) , array('jquery'), '1.0', true );
$parameters = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'woomps_sub_slider', 'subpost', $parameters);
}
This should fire of my jQuery:
jQuery( document ).on( 'click', '.button_sub_chooser', function() {
alert("test");
jQuery.ajax({
url : subpost.ajax_url,
type : 'post',
data : {
action : 'woomps_update_subscription_chooser',
},
success : function( response ) {
jQuery('#button_sub_chooser').effect( "bounce", "slow" );
}
});
return false;
})
When this is clicked:
<a id="button_shake" class="button_sub_chooser" '.$woomps_ajax_url.'>VElg denne</a>
But wp_enqueue_scripts does not fire of the jQuery. If i just call the function like this woomps_ajax_frontend() it will fire. Why does it work when called like a function and not through wp_enqueue_scripts?
Can you please try this plugin_dir_url(__FILE__) insted of plugins_url().
add_action( 'wp_enqueue_scripts', 'woomps_ajax_frontend' );
function woomps_ajax_frontend() {
wp_enqueue_script( 'woomps_sub_slider', plugin_dir_url(__FILE__). 'js/woomps-ajax-frontend.js' , array('jquery'), '1.0', true );
$parameters = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'woomps_sub_slider', 'subpost', $parameters);
}
The PHP code was put in an included (required_once) file which i had enqueue the following way.
function woomps_scripts() {
require_once ('includes/woomps-ajax-sub-chooser.php');
} //END woomps_scripts
add_action('wp_enqueue_scripts','woomps_scripts');
If I put the require_once ('includes/woomps-ajax-sub-chooser.php'); outside this function woomps_scripts it got included.
So it seems I cant do wp_enqueue_scripts two times down.

jQuery functions to Wordpress child theme using enqueue

My wordpress knowledge is pretty low and I am in desperate need of help on adding some jQuery functions to a wordpress child theme.
I basically want to add this effect to my front-page.php
I somewhat understand how to use the functions.php in order to enqueue my scripts.
Here is what my functions.php file looks like
<?php
function enqueue_scripts() {
wp_register_script( 'js name', get_template_directory_uri() . '/myfile.js', array( 'jquery' ), '1.0', true );
wp_register_script( 'js name', get_template_directory_uri() . '/myfile.js', array( 'jquery' ), '1.0', true );
wp_register_script( 'js name', get_template_directory_uri() . '/myfile.js', array( 'jquery' ), '1.0', true );
wp_enqueue_script( 'global' );
if ( is_page( 'front-page' ) ) { // example page
wp_enqueue_script( 'js name', 'js name', 'js name' );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
?>
As of right now it of course does not work.
Any help is much appreciated. Thanks.
Try this:
function yourtheme_enqueue_scripts() {
wp_register_script( 'js_name', get_template_directory_uri() . '/myfile.js', array( 'jquery' ), '1.0', true );
wp_register_script( 'js_name_2', get_template_directory_uri() . '/myfile2.js', array( 'jquery' ), '1.0', true );
wp_register_script( 'js_name_3', get_template_directory_uri() . '/myfile3.js', array( 'jquery' ), '1.0', true );
if ( is_front_page() ) {
wp_enqueue_script( 'js_name' );
wp_enqueue_script( 'js_name_2' );
wp_enqueue_script( 'js_name_3' );
}
}
add_action( 'wp_enqueue_scripts', 'yourtheme_enqueue_scripts' );
In your themes root folder (same folder as functions.php), create new file called myfile.js. This is the file you refer to in the function above.
As you theme grows in size, it's better to organise your files. You can do this by creating subfolders, like this:
Create a folder named assets (name could be anything);
Inside assets create three new folders called js, css and images;
Put your files in the right folders;
Update your function to follow the right path to your folders;
e.g.
wp_register_script( 'js_name', get_template_directory_uri() . '/assets/js/myfile.js', array( 'jquery' ), '1.0', true );
Note: You don't have to close ?> in your functions.php.

Categories