How to get wp_ajax to work with jQuery $.post - php

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.php:
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?

Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?

Related

how to get result of a function as string with ajax in wordpress

I'm developing a plugin for wordpress and I want to use ajax in it. lets say I have the following function:
function ajax_say_hello(){
return "hello";
}
I want to get the result of ajax_say_hello() as a string with ajax. something like "hello".
to do this, I added the following:
in my plugins function.php >
add_action('wp_ajax_ajax_say_hello', 'ajax_say_hello');
add_action( 'wp_ajax_nopriv_ajax_say_hello', 'ajax_say_hello' );
and in my ajax.js >
jQuery(document).ready(function($) {
$('#myform').on('submit', function(e) {
var data = {
action: 'ajax_say_hello',
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
and ajaxurl is defined correctly.
but I get the entire page as result with no error in console. what is wrong here and what should I do?
Try the below code.
add_action('wp_ajax_ajax_say_hello', 'ajax_post_ajax_say_hello');
add_action( 'wp_ajax_nopriv_ajax_say_hello', 'ajax_post_ajax_say_hello' );
function ajax_post_ajax_say_hello(){
echo "hello";
die;
}

Clear WooCommerce cart on Currency Switcher change

I'm using the currency switcher WordPress plugin to change currencies on my website, I want the cart to be cleared once I change the currency. I've been trying for some time now, but can't figure out why it isn't working.
This is my source code in the theme functions.php file
function currency_change_action_callback() {
global $woocommerce;
$url_data=$_POST['url_data'];
$woocommerce->cart->empty_cart();
echo $url_data;
die();
}
add_action( 'wp_ajax_currency_change_action', 'currency_change_action_callback' );
add_action( 'wp_ajax_nopriv_currency_change_action', 'currency_change_action_callback' );
I've also tried creating a javascript file and calling it to my functions.php file. here are my source codes
app.js
$('#alg_currency_select').on('change', function () {
function Clearcart(d){
jQuery.post(
"http://localhost/epay/wp-admin/admin-ajax.php",
//ajaxurl,
{
"action": "clearcart",
"data": d.getAttribute("data-product")
},
function(){
window.location = d.getAttribute("data-href");
}
);
})};
functions.php
function load_javascript() {
wp_register_script('custom', get_template_directory_uri().'/app.js', 'jquery', 1, true);
wp_enqueue_script('custom');
}
add_action('wp_enqueue_scripts', 'load_javascript');
would greatly appreciate it if someone can help me solve the issue of why my cart isn't clearing. thanks.
There are some mistakes in your code and unnecessary things.
In the code below, the jQuery code is now located in a php function and enqueued in WordPress using the WooCommerce wc_enqueue_js() function.
// The jQuery Ajax enqueued code
add_action('template_redirect', 'currency_change_trigger_clear_cart_js' );
function currency_change_trigger_clear_cart_js() {
wc_enqueue_js( "jQuery( function($){
$(document.body).on('change', '#alg_currency_select', function() {
$.ajax({
url: '" . admin_url('/admin-ajax.php') . "',
type: 'POST',
data: {
'action': 'currency_change_clear_cart'
},
success: function(response) {
if( response == 'cleared' ) {
$(document.body).trigger('wc_fragment_refresh'); // Refresh cart
}
// console.log(response);
}
});
});
});" );
}
// Php AJAX receiver: Empty cart
add_action( 'wp_ajax_currency_change_clear_cart', 'currency_change_clear_cart' );
add_action( 'wp_ajax_nopriv_currency_change_clear_cart', 'currency_change_clear_cart' );
function currency_change_clear_cart() {
if( count(WC()->cart->get_cart()) > 0 ) {
WC()->cart->empty_cart();
echo 'cleared';
}
die();
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Passing ajax variable to more than one wordpress plugin function

I'm trying to get information from the front end of my Wordpress site, I used ajax to do that, it gave me the ability to use the data in one of my plugin functions, but in my case I want to use this data in more than just one function.
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data);
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
$whatever = $_POST['whatever'];
}
In other words I need to use $_POST['whatever'] in other functions in my plugin not only my_action() function, I tried using PHP global variables like so , but it didn't workout:
$whatever;
function my_action(){
global $whatever = $_POST['whatever'];
}
function my_other_function(){
global $whatever;
if(isset($whatever)){
echo $whatever;
}
}

Woocommerce aJax apply coupon code to basket

I am attempting to apply a coupon code to the basket on a button press.
I have the following code:-
coupon = jQuery(this).data('coupon');
data = {coupon_code : coupon};
jQuery.post( "?wc-ajax=apply-coupon", { coupon_code: coupon }).done(function( data ) {
alert( "Data Loaded: " + data );
});
I can see the following data is being parsed to the server:-
coupon_code: 10percentdiscount
The 10percentdiscount exists.
The Server is not sending back a response once I have sent the request.
Am I correctly making this request or is there another way?
Thank you in advance.
You don't need to add custom code in your functions.php. Woocommerce supports adding coupons via AJAX natively (see how below).
Errors in your code:
You forgot to send the nonce (security parameter);
It is apply_coupon not apply-coupon (underscore vs dash);
Your URL should start with a slash "/?wc-ajax=apply_coupon";
Correct version:
var data = {
coupon_code: jQuery(this).data('coupon'),
security: '<?php echo wp_create_nonce("apply-coupon") ?>'
};
jQuery.post('/?wc-ajax=apply_coupon', data).done(function(data) {
alert("Data Loaded: " + data);
});
I would do so:
Define ajax url in header.php or in page would you add coupon
<script type="text/javascript" language="javascript">
var ajax_url = "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php";
</script>
In function.php you must define ajax call
function implement_ajax() {
include(TEMPLATEPATH . '/ajax_return.php');
}
add_action('wp_ajax_my_special_action', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_action', 'implement_ajax');
In ajax_return.php you past code that add coupon to woocommerce:
if (isset($_POST['couponcode']))
{ apply_coupon($_POST['couponcode']); };
function apply_coupon($couponcode) {
global $woocommerce; WC()->cart->remove_coupons();
$ret = WC()->cart->add_discount( $couponcode );
$array = array('return' => $ret); print_r($array);
}
exit;
Your jQuery.post will became this:
<script type="text/javascript">
jQuery(function(){
coupon = jQuery(this).data('coupon');
jQuery.post(ajax_url, {action : 'my_special_action', couponcode : coupon}, return_function, 'JSON');
});
function return_function(data)
{
console.log(data.return); //contains true if coupon was applied
}
</script>
If you need, call return_function to manage response.

How to send ajax request in wordpress without displaying zero

I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property action as below so that WP knows which action to call.
In your particular case you'll also have to declare ans_name (as opposed to data), so that $_POST['ans_name'] exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used $_POST['ans_name'] in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.
Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
<script type="text/javascript">
function key_press(){
var data = {
url: '<?php echo get_admin_url()?>admin-ajax.php',
type: 'POST',
action: jQuery('[name="ans_name"]').serialize(),
ans_name: jQuery('[name="ans_name"]').serialize()
};
var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
alert('Got this from the server: ' + response);
});
myRequest.done(function(){
alert("success");
});
}
</script>
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax(){
echo $_POST['ans_name'];
die(); // Required for a proper Wordpress AJAX result
}
Addition
To ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to your functions.php file.
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

Categories