Access WC() to get cart content in ajax callback - php

I'm trying to get woocommerce cart content in ajax callback function but it returns empty.
I've also tried using global $woocommerce variable that also returns the same result. I'm trying to get the cart content and convert all product to autoship feature. I'm using wooautoship plugin for that. however, main query is, how to get the cart details in ajax callback.
My Code is as follow:
add_action('wp_footer', 'woo_cart_autoship_js', 99);
function woo_cart_autoship_js(){
?>
<script type="text/javascript">
(function($){
$(document).on('click', '#convert-to-autoship', function(e){
e.preventDefault();
$.post( "<?php echo admin_url('admin-ajax.php'); ?>", { action: "convert-to-autoship" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_ajax_convert-to-autoship', 'convert_to_autoship', 99 );
add_action( 'wp_ajax_nopriv_convert-to-autoship', 'convert_to_autoship', 99 );
function convert_to_autoship(){
print_r(WC()->cart->get_cart());
wp_die();
}

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;
}

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 get wp_ajax to work with jQuery $.post

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?

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
}
?>

buddy press ajax new message notifiction

i am working on one buddy press theme and want to display unread messages count via ajax.
i have bellow code in function.php of my theme
<?php
function addMessageRefresh()
{
?>
<script type="text/javascript">
function getMessages(){
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
}
setInterval("getMessages()", 10000);
</script>
<?php
}
add_action( 'wp_head', 'addMessageRefresh');
?>
it worked.
but its only show unread count on page load, but if user receive any message this did’t update.
the main purpose of this script is to display total number of unread messages and it should update via ajax means if user receive any message, it should show total number of unread messages without reloading page.
Thanks
somehow it..
function getMessages(){
jQuery.ajax({
url: '../url.php'
dataType: 'html',
success: function (data) {
jQuery('#user-messages span').text("Unread Messages: " + data);
}}
)
}
../url.php code
<?php echo messages_get_unread_count(); ?>
There are several steps, that you need to do:
1) Place element which contain unread message count. This should be adde to your template.
<div id="unread_messages"></div>
2) Add javascript code which will update your count value.You can add this to your template or you can print it from wp_head/wp_footer hooks
<script type="text/javascript">
function update_unread_count() {
jQuery('#unread_messages').load(
'<?php echo admin_url('admin-ajax.php'); ?>',
{ 'action': 'get_unread_message_count' }
);
}
jQuery(document).ready(function() {
// update every 15 seconds, after page loaded
setInterval('update_unread_count()', 15000);
});
</script>
3) Register ajax request handler. You should add this lines into your functions.php theme file
function my_get_unread_message_count() {
echo messages_get_unread_count();
die();
}
add_action('wp_ajax_get_unread_message_count', 'my_get_unread_message_count');
Something like that.
Your issue lies within:
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
What is being done is when the page is being loaded PHP processes the messages_get_unread_count() function and uses that value to render the page. From there the generated JavaScript will be called at your interval but it will have a static value defined in your preprocessed markup.
You will need to have an AJAX call to a url that will return your message count.
This is the functionality to allow you to get the updated message count.
function add_message_count_js() {
?>
<script type="text/javascript">
//<![CDATA[
var msg_count;
function updateMessages() {
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {"action": "view_message_count"},
success: function(data) {
jQuery('#user-messages span').text("Unread Messages: "+data);
}
});
return false;
}
setInterval('updateMessages()', 10000);
//]]>
</script>
<?php
}
add_action('wp_head', 'add_message_count_js');
This will add the appropriate AJAX hooks.
add_action('wp_ajax_view_message_count', 'view_message_count');
add_action('wp_ajax_nopriv_view_message_count', 'view_message_count');
function view_message_count() {
if (is_user_logged_in())
echo messages_get_unread_count();
die();
}
Both of these snippets should go in your functions.php file.

Categories