How to use function within class for ajax request - javascript

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?

Related

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?

"Bad Request" 400 server response for AJAX request

All of the usual suspects have been tried to no avail, including setting: ContentType: and dataType:. jQuery has defaults for both, if not specified. Tried serializing the json using JSON.stringify(data) - all combinations of the above don't change the server response. Can't see what I'm missing here that's causing the problem.
Here's the javascript in question:
jQuery(document).ready(function() {
jQuery('.delete_listing').on('click', (function(e) {
var post_type = jQuery(this).data( 'type' ); // Get post type via the 'data-type' attribute of the button.
e.preventDefault();
if (confirm('You want to delete this listing?')) {
jQuery.ajax({
url: fpf_ajax_delete_listing.ajax_url, // 'fpf_ajax_delete_listing' is from wp_localize_script() call
type: 'post',
data: {
action: 'fpf_ajax_delete_listing_process', // part of add_action() call
nonce: fpf_ajax_delete_listing.fpf_delete_listing_nonce, // from wp_localize_script() call.
post_type : post_type
},
success : function( response ) {
console.log(response);
},
error : function( response) {
alert('Error retrieving the information: ' + response.status + ' ' + response.statusText);
console.log(response);
}
});
// clear edit page, msg delete successful, redirect to seller account dashboard
jQuery(function() {
jQuery(".form-group").remove();
jQuery("p").remove();
jQuery("#remove-listing").remove();
jQuery("hr").replaceWith('<h4 style="color:green;"><em>Listing successfully deleted.</em></h4>');
// return to seller dashboard
}); // clear & redirect
} else {
// Do nothing!
}
}));
});
And here's the PHP from the plugin:
function fpf_ajax_delete_listing_shortcode() {
return '<button class="delete_listing" data-type="post" type="button" style="background:red; border-radius:5px; border-width:1px; color:white;">Delete Listing</button>';
}
add_shortcode('ajax_delete_listing', 'fpf_ajax_delete_listing_shortcode');
add_action('wp_enqueue_scripts', 'fpf_enqueue_scripts');
function fpf_enqueue_scripts() {
wp_enqueue_script( 'fpf-delete-listing', plugin_dir_url( __FILE__ ). 'ajax-delete-listing-code.js', array('jquery') );
wp_localize_script( 'fpf-delete-listing', 'fpf_ajax_delete_listing', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'fpf_delete_listing_nonce' => wp_create_nonce('fpf-delete-listing-nonce')
));
}
add_action( 'wp_ajax_fpf_ajax_delete_listing', 'fpf_ajax_delete_listing', 20 ); // logged in users only.
function fpf_ajax_delete_listing() {
check_ajax_referer( 'fpf-delete-listing-nonce', 'nonce' ); // dies if nonce is not correct.
$post_id = get_the_ID();
update_post_meta($post_id, 'wpcf-listing-status', 'inactive');
}
return;

Wp-api 2 cookie authentication

So, I have a php page in wordpress (WP-Api 2):
<?php
/**
* Template Name: WP-Api
*/
add_action("wp_enqueue_scripts", "enqueue_");
function enqueue_() {
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
}
get_header(); ?>
<h1>oi</h1>
<script type="text/javascript">
jQuery.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
</script>
I want to run this example but the console says
Uncaught ReferenceError: wpApiSettings is not defined
What am I doing wrong? Thank you!
Take a look at the example here: https://codex.wordpress.org/Function_Reference/wp_localize_script
You need to wp_register_script and wp_enqueue_script or the JS variable will not be created.
Add the following code to functions.php and check if the user already logged in has the capabilities to POST (Create Products, Posting, Upload Media File, etc.)
/*Cookies Authentication*/
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
wp_enqueue_script('wp-api');

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

Categories

Resources