I'm trying to update my checkout cart's shipping with AJAX...
I've got the action in functions.php
function jwd_update_shipping()
{
WC()->cart->calculate_shipping();
echo "hi";
die();
}
add_action('jwd_update_shipping_callback', 'jwd_update_shipping');
Then in js I call it, like so
jQuery.ajax({
type: "POST",
url: 'MYSITE.com/wp-admin/admin-ajax.php',
data: ({
action: "jwd_update_shipping"
}),
success: function(response) {
console.log("got this: " + response);
if (response.type == "success") {
alert("here");
jQuery('body').trigger('update_checkout');
} else {
alert("fail");
}
},
error: function(request, status, error) {
alert(request.responseText);
}
});
I just get a 0 alerted back at me, which suggests that the AJAX call failed.
First your ajax request is not reaching the related php function… Also you need more things to refresh checkout… Try the following instead:
// The jQuery script that send the Ajax request
add_action( 'wp_footer', 'refresh_shipping_js' );
function refresh_shipping_js() {
// Only on checkout
if( is_checkout() && ! is_wc_endpoint_url() ):
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
var refresh = 'yes';
$.ajax({
type: "POST",
url: wc_checkout_params.ajax_url,
data: ({
'action': 'updating_shipping',
'refresh_shipping': refresh,
}),
success: function(response) {
if( response === '1' ) {
$(document.body).trigger('update_checkout');
console.log('Success: '+response); // For testing (to be removed)
} else {
console.log('Failled: '+response); // For testing (to be removed)
}
},
error:function(error) {
console.log('Error: '+error); // For testing (to be removed)
}
});
});
</script>
<?php
endif;
}
// function that gets the Ajax data
add_action( 'wp_ajax_updating_shipping', 'updating_shipping' );
add_action( 'wp_ajax_nopriv_updating_shipping', 'updating_shipping' );
function updating_shipping() {
if ( isset($_POST['refresh_shipping']) && $_POST['refresh_shipping'] === 'yes' ){
WC()->session->set('refresh_shipping', '1' );
} else {
WC()->session->set('refresh_shipping', '0' );
}
echo WC()->session->get('refresh_shipping');
die(); // Alway at the end (to avoid server error 500)
}
// Function that refresh session shipping methods data
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
if ( WC()->session->get('refresh_shipping' ) === '1' ) {
foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
WC()->session->set( 'shipping_for_package_' . $package_key, false );
}
WC()->cart->calculate_shipping();
}
}
Related
I want to check the order status continuously using ajax and if I get the order status is "processing" then I want to redirect the customer to a specific URL. I tried below snippet but it didn't work.
<script>
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php?action=fetch_order_status&order_id=<?php echo $order->get_order_number(); ?>',
type : 'post',
error : function(response){
console.log(response);
},
success : function( response ){
window.location.href = "url to redirect";
}
});
}
setInterval(fetchStatus, 1000);
</script>
In functions.php:
<?php
function fetch_order_status(){
$order = wc_get_order( $_REQUEST['order_id'] );
$order_data = $order->get_data();
if($order->has_status == 'processing'){
echo $order_data['status'];
}
die();
}
add_action('wp_ajax_nopriv_fetch_order_status', 'fetch_order_status');
add_action('wp_ajax_fetch_order_status','fetch_order_status');
?>
This is the thing I did:
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=fetch_order_status&order_id=<?php echo $order_id; ?>',
type : 'post',
dataType:"json",
error : function(response){
console.log(response);
},
success : function( response ){
console.log(response);
if (response.status == "processing") {
window.location.href = "URL to redirect";
} else {
fetchStatus();
}
}
});
}
fetchStatus();
</script>
and in function.php:
function fetch_order_status(){
$order = wc_get_order( $_REQUEST['order_id'] );
$order_data = $order->get_data();
echo json_encode(array("status"=>$order_data['status']));
die();
}
add_action('wp_ajax_nopriv_fetch_order_status', 'fetch_order_status');
add_action('wp_ajax_fetch_order_status','fetch_order_status');
has_status is a method, that accepts an argument. It returns a boolean, not a string.
Maybe try $order->has_status( 'processing' );.
Also - update the success logic:
success : function( response ){
if (response === 'DESIRED_STATUS') {
window.location.href = "url to redirect";
}
}
Where, DESIRED_STATUS is the status you're waiting for to make the redirect.
Answer without race conditions
Since you're making an HTTP request, it is possible for a race condition to happen.
<script>
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=fetch_order_status&order_id=<?php echo $order->get_order_number(); ?>'
type : 'post',
error : function(response){
console.log(response);
},
success : function( response ){
if (response === 'DESIRED_STATUS') {
window.location.href = "url to redirect";
} else {
fetchStatus();
}
}
});
}
fetchStatus();
</script>
I've removed the standard "Added to cart" message given by WooCommerce. I have then added the code below which is using the Sweet Alert. The idea is to remove all "added to cart" messages and to only use the sweet alert.
Based on "JS alert on ajax add to cart for specific product category count in Woocommerce" answer code by #LoicTheAztec, my code works for the first product added, but not for the following ones. So it works fine when the cart is empty and when adding the first product.
Here's the code I'm using:
// remove add to cart woocommerce message
add_filter('wc_add_to_cart_message_html', '__return_null');
// Wordpress Ajax PHP
add_action('wp_ajax_nopriv_checking_items', 'atc_sweet_message');
add_action('wp_ajax_checking_items', 'atc_sweet_message');
function atc_sweet_message() {
if (isset($_POST['id']) && $_POST['id'] > 0) {
$count = 0;
$product_id = $_POST['id'];
foreach(WC()-> cart-> get_cart() as $cart_item) {
$count += $cart_item['quantity'];
}
}
echo $count;
die();
}
// jQuery Ajax
add_action('wp_footer', 'item_count_check');
function item_count_check() {
if (is_checkout())
return;
?>
<script src="https://unpkg.com/sweetalert2#7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($) {
if ( typeof wc_add_to_cart_params === 'undefined' )
return false;
$(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'checking_items',
'id' : $button.data( 'product_id' )
},
success: function (response) {
if(response == 1 ){
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: 'Product Added To Cart'
})
}
}
});
});
});
</script>
<?php
}
I tried removing if(response == 1 ){ without success. Any input on this is appreciated.
There was little mistakes in your code on the function for Wordpress Ajax PHP. Try the following:
// remove add to cart woocommerce message
add_filter('wc_add_to_cart_message_html', '__return_null');
// Wordpress Ajax PHP
add_action('wp_ajax_nopriv_item_added', 'addedtocart_sweet_message');
add_action('wp_ajax_item_added', 'addedtocart_sweet_message');
function addedtocart_sweet_message() {
echo isset($_POST['id']) && $_POST['id'] > 0 ? (int) esc_attr($_POST['id']) : false;
die();
}
// jQuery Ajax
add_action('wp_footer', 'item_count_check');
function item_count_check() {
if (is_checkout())
return;
?>
<script src="https://unpkg.com/sweetalert2#7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($) {
if ( typeof wc_add_to_cart_params === 'undefined' )
return false;
$(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
var $pid = $button.data('product_id');
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'item_added',
'id' : $pid
},
success: function (response) {
if(response == $pid){
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: 'Product Added To Cart'
})
}
}
});
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
It works now for all ajax added to cart items (and not just the first one).
It's getting the link to the word press ajax file but giving me a bad request error.
The exact error im getting is POST http://[Website URL]/wp-admin/admin-ajax.php 400 (Bad Request)
Functions.php file
function as_custom_ajax_localizing() {
wp_enqueue_script( 'custom.js', get_template_directory_uri() . '/guest-list/custom.js', array( 'jquery' ), '1.0.0', true );
wp_localize_script( 'custom.js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'as_custom_ajax_localizing' );
Custom php file
add_action( 'wp_ajax_my_delete_post', 'as_delete_guest' );
function as_delete_guest(){
$permission = check_ajax_referer( 'as_delete_guest_nonce', 'nonce', false );
if( $permission == false ) {
echo 'error';
} else {
wp_delete_post( $_REQUEST['id'] );
echo 'success';
}
die();
}
Custom Js file
$( document ).ready(function() {
$( ".remove_guest" ).click(function() {
var guestRowId = $(this).attr('id');
alert( "This id is " + guestRowId + " and has been clicked");
var nonce = $(this).data('nonce');
$.ajax({
type: 'post',
url: MyAjax.ajaxurl,
data: {
action: 'my_delete_post',
nonce: nonce,
id: guestRowId
},
success: function( result ) {
if( result == 'success' ) {
alert("Success");
}
else{
alert("problem");
}
}
})
return false;
});
});
Hi guys i am new to wordpress and ajax , i use this code for checking an input value before submitting the form :
$j("#ninja_forms_field_75").focusout(function(){
var content = document.getElementById("ninja_forms_field_75").value;
$j.ajax({
url : 'check.php',
data : {'mid':content},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
},
error : function(resp){
alert("some error occured !");
}
});
});
problem is i dont know where shall i put that php file to work with database...
please help me!!!
pardon my english...
Inside your js file write your code above:
javascript.js
$j("#ninja_forms_field_75").focusout(function() {
var content = document.getElementById("ninja_forms_field_75").value,
my_data = {
'action': 'my_action',
'mid': content
};
$j.ajax({
url: ajaxurl,
data: my_data,
type: 'POST',
success: function(resp) {
if (resp == '1') {
//success message or whatever
},
error: function(resp) {
alert("some error occured !");
}
});
});
});
Then the php part begins, I prefer to store it inside the functions.php if it's just one ajax request. If it is more than one create a file like ajax-handler.php and include it inside your functions.php
functions.php
if ( defined( 'DOING_AJAX' ) ) {
include_once( 'ajax-handler.php' );
}
ajax-handler.php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_ajax_my_action', 'my_custom_ajax_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_custom_ajax_action' );
function my_custom_ajax_action() {
$result = 'Hello';
wp_send_json( $result );
}
You can try in the functions.php, I have made a form by steps and I do it on functions.php in yout theme directory.
AJAX Post is not returning success call in wordpress. I have the following code and I can get to the first dialog box in testing, but no mater what I do its not getting to the second. It's not finding the function in functions.php even though I have it declared.
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var datastring = $("#redemmpointsForm").serialize();
var points = $('#points').val();
var comments = $('#comments').val();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {"action": "redeempoints", "points":points},
success: function(response) {
if(response.type == "success") {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
functions.php file
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
die();
return true;
}
add_action("wp_ajax_functionRedeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints");
Ok so i treid the following
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var allData = {
action: 'functionRedeempoints',
points: points,
comments:comments
}
var data = JSON.stringify(allData);
alert( data);
jQuery.ajax({
type : "post",
dataType : 'json',
url : myAjax.ajaxurl,
data : data,
success: function(response) {
if(response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
And iN MY FUCNTIONS php Its like its not fidning the php function.
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
wp_send_json_success(true);
}
add_action("wp_ajax_redeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_redeempoints", "functionRedeempoints");
The problem is that your function functionRedeempoints does not return anything that the ajax call can handle.
It just dies even before the return statement.
Also a return by the PHP end will never actually be interpreted by the JS. JS can only read from the http request, so you need to actually write to it by an echo statement.
Wordpress provides a convenient way of handling this for you:
What you need would be something like:
function functionRedeempoints() {
wp_send_json_success(true);
}
This already takes care of stopping execution and properly JSON encoding your response.
Also the correct response handling on the JS side is a little different than in your example code.
You can find the details on this here:
https://codex.wordpress.org/Function_Reference/wp_send_json_success
But what it boils down to is that the success is encoded in the result.success property of the response.
Hence you want your check to be
if(response.success)
instead of if(response.type == "success")
With these changes your example should work though :)
Working example ( in plugin form) based on your code:
Put this in hello.php in the plugins folder
<?php
/*
Plugin Name: Ajax demo
*/
function test_load_js() {
wp_register_script( 'ajax_demo', plugins_url( 'hello.js' ), array( 'jquery' ) );
wp_localize_script( 'ajax_demo', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax_demo' );
}
function functionRedeempoints() {
wp_send_json_success( true );
}
add_action( "wp_ajax_functionRedeempoints", "functionRedeempoints" );
add_action( "wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints" );
add_action( "init", "test_load_js" );
if ( ! defined( 'DOING_AJAX' ) ) {
echo '<input type=button value="send" id="send_btn">';
}
Put this in hello.js in the plugins folder
jQuery(document).ready(function () {
jQuery("#send_btn").click(function () {
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var data = {
action: 'functionRedeempoints',
points: points,
comments: comments
};
alert(JSON.stringify(data));
jQuery.ajax({
type: "post",
dataType: 'json',
url: MyAjax.ajaxurl,
data: data,
success: function (response) {
if (response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
});
Hope this helps you to get a start here, works just fine when you click the button that should appear on the upper left of your admin screen ( zoom in ;) )