The WordPress Ajax request returns 0 - javascript

I can't figure out why nothing is returned
I am a real beginner in Ajax ..
I just read a lot of topics about using Ajax in Woprdpress but the examples are super advanced for me
Here is my JS code combo_checkout_iRange.js
jQuery(document).ready(function() {
jQuery('#loader').hide();
jQuery('#check-out-date').hide();
jQuery('#check-in-date').change(function(){
jQuery('#check-out-date').fadeOut();
jQuery('#loader').show();
jQuery.ajax({
type: 'POST',
url:myAjax.ajaxurl,
data: {
action : 'my_ajax_handler',
parent_id: jQuery("#check-in-date").val()
},
success: function(data){
alert(data);
jQuery('#loader').hide();
jQuery('#check-out-date').show();
jQuery('#check-out-date').append(data);
}});
return false;
});
jQuery('#check-out-date').change(function(){
alert(jQuery('#check-out-date').val());
});
});
This is what I wrote on function.php
Note: this should work in post type called "meetings"
add_action("wp_enqueue_scripts", function() {
if (is_single()) {
if (get_post_type() == 'meetings')
{
wp_enqueue_script('combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array( 'jquery' ), '1.0' ,true);
$data_array = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_register_script( 'combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array('jquery') );
wp_localize_script( 'combo_checkout_iRange', 'myAjax', $data_array );
}
}
});
and this is my ajax handler i put it inside single_meetings.php
add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");
function my_ajax_handler() {
if ( isset($_REQUEST["parent_id"]) ) {
$id = $_REQUEST["parent_id"];
return $id;
die();
}
}

You can't use return in your AJAX callback. The code never gets to die on the line beneath. You need to echo the value instead and then use wp_die().
Replace:
return $id;
die();
With:
echo $id;
wp_die();

Related

WooCommerce set cart quantity with AJAX?

I've now been scratching my head about this for several days and need some pointers.
I'm making a custom theme totally from scratch for a WooCommerce site and now I'm trying to get the cart functionality to work. I'm stuck at trying to have buttons (+/-) for updating the quantity of a product item in the cart.
The problem to me seems to be that the WC() I use inside functions.php is not the same instance as the current frontend-session, or something among those lines. At least my thought for now.
If I've debugged correctly the WC()->cart->set_quantity($cart_item_key, 0) gives no error (if using number 0), all other numbers gives '500 (Internal Server Error)'. But even with 0 quantity in cart is never changed nonetheless.
I've enqueued the scripts correctly so the AJAX function call executes fine when the button is clicked.
Here's my HTML and PHP (simplified)
<div class="cart-items">
<?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>
<div class="cart-item">
<div class="quantity" id="cart-qty-<?php echo $cart_item_key ?>">
<button class="minus" id="cart-subtract"
onclick="updateCartQuantity('<?php echo $cart_item_key ?>', '<?php echo $cart_item['quantity'] ?>', -1)">-</button>
<p><?php echo $cart_item['quantity'] ?></p>
<button class="plus" id="cart-add">+</button>
</div>
</div>
<? endforeach; ?>
</div>
Here's my JS (inside a file called shopping-ajax.js)
function updateCartQuantity(cart_item_key, current_qty, value) {
function qty_cart() {
jQuery.ajax({
type: "POST",
url: my_ajax_object.ajax_url,
data: {
action: "update_cart",
hash: cart_item_key,
quantity: current_qty,
value: value,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
});
}
qty_cart();
}
Here's my PHP function (inside functions.php)
function updateCartQuantity(){
$cart_item_key = $_REQUEST['cart_item_key'];
$quantity = $_REQUEST['quantity'];
$value = $_REQUEST['value'];
WC()->cart->set_quantity($cart_item_key, $quantity + $value);
echo $quantity + $value;
wp_die();
}
add_action( 'wp_ajax_nopriv_update_cart', 'updateCartQuantity' );
add_action( 'wp_ajax_update_cart', 'updateCartQuantity' );
A massive thanks for any help or pointer in advance!
You should manage product qty according to the qty input box(change qty).
My JS:
location: theme directory -> js -> custom.js
jQuery( function( $ ) {
$( document ).on( 'change', 'input.qty', function() {
var $thisbutton = $(this);
var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
var item_quantity = $( this ).val();
var currentVal = parseFloat(item_quantity);
$.ajax({
type: 'POST',
url: cart_qty_ajax.ajax_url,
data: {
action: 'my_cart_qty',
hash: item_hash,
quantity: currentVal
},
success: function(response) {
jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
//jQuery(document.body).trigger('update_checkout');
}
});
});
});
fuctions.php -
Setup Enqueue Ajax Scripts:
function enqueue_cart_qty_ajax() {
wp_register_script( 'my_cart_qty-ajax-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );
wp_localize_script( 'my_cart_qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'my_cart_qty-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
Ajax call -
function ajax_my_cart_qty() {
// Set item key as the hash found in input.qty's name
$cart_item_key = $_POST['hash'];
// Get the array of values owned by the product we're updating
$threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
// Get the quantity of the item in the cart
$threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
// Update the quantity of the item in the cart
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
}
// Refresh the page
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_my_cart_qty', 'ajax_my_cart_qty');
add_action('wp_ajax_nopriv_my_cart_qty', 'ajax_my_cart_qty');

jQuery Ajax callback is either not triggered or not working

I just started experimenting with jQuery and ajax. I have looked through similar posts but I am still unable to resolve my issue.
So here goes, I am writing a wordpress plugin. I have the following:
add_action('wp', 'wl_init');
add_action('wp_ajax_wl_add_wishlist', 'wl_wishlist_process');
add_action('wp_ajax_nopriv_wl_add_wishlist', 'wl_wishlist_process');
function wl_wishlist_process (){
echo 'test';
die();
}
function wl_init(){
wp_register_script( 'wishlist-js', plugins_url( '/wishlist.js', __FILE__ ), array('jquery') );
wp_localize_script( 'wishlist-js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery');
wp_enqueue_script( 'wishlist-js' );
}
And this is my js file"
jQuery(document).ready(function($) {
$('#wl_wishlist').click(function(e) {
alert('This runs');
//var plugurl = document.location.protocol+'//'+document.location.host+'/test/wp-admin/admin-ajax.php';
//"<?php echo admin_url('admin-ajax.php'); ?>"
//"/test/wp-admin/admin-ajax.php"
jQuery.ajax({url: myAjax.ajaxurl, type: 'post', data: {action: 'wl_wishlist_process', post_id:100}, success: function(response) {
alert(response);
},
error : function (xhr){
alert('There is an error');
}});
});
});
I know the js file is loaded and running as I see the alert('This runs'). However, it neither gives me success nor error. Is it error with the ajax call or is it the callback function error? What am I missing here?
Also, When I open the url of the ajax call (http://localhost/test/wp-admin/admin-ajax.php), it shows '0'. Is this correct?
I have used all the commented methods to get the url, but none works.
Thanks!

jQuery does not hit the Ajax URL on Wordpress

I am trying to implement a poll plugin on wordpress. The jQuery onchange event is working very fine of the below script but doesn't call or display the ajax hit on network .
plugin index page
PHP :
function my_scripts_main() {
wp_enqueue_script(
'my_voter_script',
plugins_url( '/js/main.js' , __FILE__ ),
array( 'jquery' )
);
wp_localize_script( 'my_voter_script',
'myAjax',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
'action'=>'my_poll_srt')
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_main' );
Plugin Short code Page :
add_action( 'wp_ajax_nopriv_my_poll_srt', 'my_poll_srt_callbck' );
add_action( 'wp_ajax_my_poll_srt', 'my_poll_srt_callbck' );
function my_poll_srt_callbck() {
global $wpdb;
$poll_id=$_POST['poll_id'];
$answer=$_POST['answer'];
$d=mktime(11, 14, 54, 8, 12, 2014);
$created= date("Y-m-d h:i:sa", $d);
/******* My Logic ****************/
echo json_encode(array('YES'=>$count_yes,
'NO'=>$count_no));
wp_die();
}
JS script :
jQuery(document).ready(function(){
jQuery("input[name=answer_srt]:radio").change(function (e) {
e.preventDefault();
// submit();
// $(this).closest("form").submit(function() {
// alert('Hello');
var poll_answer=$(this).val();
var poll_id=jQuery(this).closest("form").find('#poll_id_srt').val();
var vi=jQuery(this);
jQuery.ajax({
url: myAjax.ajaxurl,
type: 'POST',
data: {
action: myAjax.action,
answer:poll_answer,
poll_id:poll_id
},
// dataType: 'html',
success: function(response) {
var obj = JSON.parse(response);
// console.log(obj);
jQuery(vi).closest('form').find('#poll_sht').html('YES='+obj.YES+' NO='+obj.NO);
}
// });
});
});
});
In the code above there are no errors in console panel.
If I put alert() inside the script its working fine but its not hitting admin-ajax.php file. What to do now ? Where am I wrong please help me ?
Your action URL should contain query string of action.
e.g
The action URL is like this
http://localhost/wordpress/wp-admin/admin-ajax.php?action=my_poll_srt

Wordpress AJAX in plugin response 0

I create plugin for Wordpress and use AJAX in plugin but AJAX response 0. I try to solve this problem by following this answer but can't solve my problem.
This is my handler function
if( is_admin()) {
add_action( 'admin_menu', 'language_redirect_add_config_page' );
}
else {
add_action( 'plugins_loaded', 'preference_language' );
add_action( 'wp_enqueue_scripts', 'enqueue' );
add_action( 'wp_ajax_preference_language', 'preference_language' );
add_action( 'wp_ajax_nopriv_preference_language', 'preference_language' );
}
function language_redirect_config_page() {
add_options_page( __( 'Language Redirect Setting' ), __( 'Language Redirect' ), 'manage_options', basename( __FILE__ ), '' );
}
function enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/js/plugin-script.js', __FILE__ ), array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
}
// Handler function...
function preference_language() {
$language = $_POST['language'];
if($language == 'th') {
header( 'Location: ' . site_url('th') );
}
else {
return;
}
die;
}
And this my AJAX script
jQuery(document).ready(function($) {
var language = localStorage.getItem('language');
var data = {
action: 'preference_language',
language: language
};
$.post(
ajax_object.ajax_url,
data,
function(response) {
console.log(response);
});
});
Try replacing the
die;
with
exit;
the 0 error is a default error in wordpress for ajax most of the time it is die; will break everything. hope this helps
header( 'Location: ' . site_url('th') );
You can't set headers after output has been rendered. Remember ajax is called from the frontend and obviously output has already started.
heres an way of doing this (untested):
function preference_language() {
$language = $_POST['language'];
if($language == 'th') {
echo site_url('th');
} else {
return;
}
exit;
}
js
jQuery(document).ready(function($) {
var language = localStorage.getItem('language');
var data = {
action: 'preference_language',
language: language
};
$.post(
ajax_object.ajax_url,
data,
function(response) {
window.location = response;
});
});
Are you quite sure that
localStorage.getItem('language')
actually holds a value that is or could be 'th'?
To be sure that your code works you could use the following code instead of your current preference_language():
function preference_language() {
$language = $_POST['language'];
if($language == 'th') {
echo "language is th.";
}
else {
echo "language is not th.";
}
die;
}

Ajax not working wordpress

js file: (walking_log.js)
jQuery.ajax
({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
'action':'myaction'
},
success: function(data)
{
alert('Happy new year 2015 :) ');
},
error: function(data)
{
alert( 'Sorry! No Happy New year 2015 :(' );
}
});
php file:
// Ajax Handler.
function so_enqueue_scripts()
{
$plugin_dir_path = dirname(__FILE__);
$plugin_url = plugins_url();
wp_enqueue_script( 'ajaxHandle', $plugin_url . '/walking-log/js/walking_log.js', array('jQuery') );
wp_localize_script( 'ajaxHandle', 'myAjax', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
}
add_action( 'init', 'so_enqueue_scripts' );
function so_wp_ajax_function()
{
die();
}
path of walking_log.js is right, i have opened it in the browser. I am getting the success failure alert. don't know why. any help would be appreciated.
Edit:
I am getting this on firebug.
"NetworkError: 404 Not Found - http://192.168.1.6/Interaction/exercise-log/%3C?php%20echo%20admin_url(%22admin-ajax.php%22);%20?%3E"
why this is happening?
In js file, This line must be causing the error..
url: '<?php echo admin_url("admin-ajax.php"); ?>',
You are calling a php function admin_url in js file. JS files will not call your php fn.
Your error confirms it .... Encoded url
%3C?php%20echo%20admin_url(%22admin-ajax.php%22);%20?%3E
Decoded URL
<?php echo admin_url("admin-ajax.php"); ?>

Categories

Resources