Wordpress AJAX in plugin response 0 - javascript

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

Related

How to use function within class for ajax request

I've created a WordPress plugin for my custom Stripe Checkout integration.
I'm extending a WooCommerce class which then has the ajax initialisers and functions:
class WC_Stripe_Checkout_Gateway extends WC_Payment_Gateway {
public function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
add_action( 'wp_ajax_create_checkout_session', array( $this, 'create_checkout_session' ) );
add_action( 'wp_ajax_nopriv_create_checkout_session', array( $this, 'create_checkout_session' ) );
}
}
public function payment_scripts() {
// Load relevant JS on checkout page only.
if( is_checkout() ) {
// Enqueue Stripe JS
wp_enqueue_script( 'stripe_js', 'https://js.stripe.com/v3/' );
// and this is our custom JS in your plugin directory that works with token.js
wp_register_script( 'stripecheckout_js', plugins_url( '../scripts/stripe_checkout.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'stripecheckout_js' );
//
wp_localize_script( 'stripecheckout_js', 'stripejs_ajax', array(
// 'publishableKey' => $this->publishable_key
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'stripe_checkout_session_nonce' ),
) );
}
}
I should be able to make an ajax request to create_checkout_session but I receive an error 400 in the console.
jQuery( function($) {
$("form.woocommerce-checkout").on('submit', function() {
$.ajax({
url: stripejs_ajax.url,
data: {
action: 'create_checkout_session',
nonce: stripejs_ajax.nonce
}
})
.done( function(response) {
if(response.type == 'success') {
console.log('level 1');
}
else {
console.log('level 2');
}
})
.fail( function(response) {
console.log(response);
});
});
});
Error:
https://example.test/wp/wp-admin/admin-ajax.php?action=create_checkout_session&nonce=5c6cf91687 400
Is it correct to have the function I want to ajax call within the class which then extends WC_Payment_Gateway, could this be causing any issues?

Wordpress ajax call in an admin menu page

I'm trying to use the data of an ajax call in my custom wordpress admin menu page.
The wp_localize_script is working fine:
wp_enqueue_script( 'ajax-function', plugin_dir_url( __FILE__ ) . 'JavaScript/ajax-function.js', array( 'jquery' ), $this->version,false );
wp_localize_script('ajax-function', 'WP_MY_AJAX',
array(
'security' => wp_create_nonce('wp-my-nonce'),
'success' => 'this is a success',
'error' => 'an error occurred'
)
);
If I click the button, my ajax fires and it has a status of 200.
jQuery(document).ready(function() {
let message = jQuery('.table-message');
jQuery('#ajax-test').on('click', function () {
let data = 111;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'get_edit_id',
security: WP_MY_AJAX.security,
edit_id: data
},
success: function ( response ) {
//Do something
},
error: function ( error ) {
jQuery('.error').remove();
message.after('<div class="error"><p>' + WP_ESCORT_AJAX.error + '</p></div>');
}
});
});
I end up in this function, which is located in my main plugin file.
function my_escort_get_edit_id() {
check_ajax_referer('wp-escort-nonce', 'security');
echo $_POST['edit_id']
die();
}
add_action('wp_ajax_get_edit_id', 'my_escort_get_edit_id');
add_action('wp_ajax_nopriv_get_edit_id', 'my_escort_get_edit_id');
However my goal is to work with the $_POST['edit_id'] in my admin menu page function:
function my_custom_admin_menu() {
add_menu_page(
__( 'My Menu', 'my-menu' ),
__( 'My Menu', 'my-menu' ),
'edit_posts',
'my-menu-slug',
'my_admin_page_function',
'dashicons-universal-access',
3 ) ;
}
add_action( 'admin_menu', 'my_custom_admin_menu' );
function my_admin_page_function() {
require_once __DIR__ . '/View/Admin/Partials/cover-menu-models.php';
requireModel('all');
$controller = new ModelController();
$modelQuery = $controller->modelQuery('all');
echo $controller->renderModelDataTables($modelQuery, 'all');
//I need the id here
}
How can I achive this?

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

The WordPress Ajax request returns 0

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();

Ajax not working in front end of wordpress plugin shortcode

Hi this my code for wordpress plugin
function my_action_callback() {
check_ajax_referer( 'my-special-string', 'security' );
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die();
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_shortcode('my_products','my_shortcode');
function my_shortcode($atts)
{
extract(shortcode_atts(array(
'id'=>''
), $atts));
ob_start();
wp_enqueue_script( 'my-script', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
wp_localize_script( 'script-name', 'MyAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'my-special-string' )
));
}
example.js code
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
security : MyAjax.security,
whatever: 1234
};
$.post(MyAjax.ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
It does not alert any values. why?
my shortcode [my_products]
You need to localize the script first before enqueuing it, also you are currently localizing script-name whilst enqueueing my-script.
Try this:
function my_shortcode($atts)
{
extract(shortcode_atts(array(
'id'=>''
), $atts));
ob_start();
// Register the script first.
wp_register_script( 'script-name', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
// Now localize it.
wp_localize_script( 'script-name', 'MyAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'my-special-string' )
));
// Now enqueue the script
wp_enqueue_script( 'script-name')
}

Categories

Resources