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.
Related
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;
}
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();
}
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?
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
}
?>
I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I'm pretty new to WordPress.
I have solve my problem on my own.First i have define ajaxurl in my themes function.php like below:
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<? }
?>
And I put the below script on the top of my plugin file.
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
var data = {
action: 'my_action',
value: val,
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
and here's the field, for which i am trying to do in my plugin.
<textarea name="custom_text_message" id="custom_text_message"></textarea>
and then I put my action which i m calling to my script in function.php.
add_action('wp_ajax_my_action', 'my_action_session');
function my_action_session() {
global $wpdb; // this is how you get access to the database
session_start();
$_SESSION['cus_msg'] = $_POST['value'];
die(); // this is required to return a proper result
}
and then call my session value in to my function.That's all i do and work for me and i hope this will helps someone else.
Note:
The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action.
In WordPress, Ajax requests should be made to http://your-wordpress-site/wp-admin/admin-ajax.php - which can be obtained using admin_url( 'admin-ajax.php' ) - and you should use action parameter to specify which function to call. You can pass the admin-ajax path to your javascript file via localization.
Add to your plugin PHP file after you enqueue your script:
wp_localize_script( 'your-script', 'js_obj', array('ajax_url' => admin_url( 'admin-ajax.php' ) );
In your javascript:
jQuery.post(js_obj.ajax_url, {value: val, action: 'run-my-ajax'})
Function to process the ajax in your plugin PHP file:
function call_my_ajax(){
// do stuff
exit;
}
add_action('wp_ajax_run-my-ajax', 'call_my_ajax');
add_action('wp_ajax_nopriv_run-my-ajax', 'call_my_ajax');
Read more: https://codex.wordpress.org/AJAX_in_Plugins
<script type="text/javascript">
function setVal()
{
jQuery.ajax({url:"<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php",success:function(result){alert(result);}}
}
</script>
WordPress works on absolute paths, use a complete URL instead of the relative URL:
jQuery.post('session.php', {value: val})
Use something like:
jQuery.post('<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php', {value: val})