Wordpress ajax call in an admin menu page - javascript

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?

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?

Can't Output Anything from WordPress AJAX, no Errors

I have an issue with Ajax in WordPress, I viewed 1000 posts about AJAX for a WordPress, but nothing. Everything seems ok.
I have a button with data-id attribute for every post on my index page, inside data-id I have its post id.
So idea is simple when someone click on this button I want to create a div with text, which will be post id. But I get nothing, I haven't any error, in my console everything is ok, but div is not created.
My enqueue scripts:
function _themename_assets() {
wp_enqueue_script( '_themename-dummy-scripts', get_template_directory_uri() . '/dist/assets/js/ajax.js', array('jquery'), '1.0.0', true );
wp_localize_script('_themename-dummy-scripts', 'viasun_dummy_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
add_action('wp_enqueue_scripts', '_themename_assets');
My JS:
$('.c-post__button a').on( 'click', function(e){
e.preventDefault();
var button = $(this);
var id = button.data('id');
var data = {
id: id,
action: "viasun_dummy_ajax_data_action"
};
$.ajax({
url: viasun_dummy_ajax.ajax_url,
data: data,
type: "POST",
beforeSend: function( ) {
console.log("sending");
},
success: function(message) {
if( data ) {
$("body").append(data);
console.log(data);
}
},
error: function() {
console.log("error");
}
} );
});
My action for ajax:
function viasun_dummy_ajax_data_action(){
$id = $_POST['id'];
echo '<div class="id-container">' . $id . '</div>';
wp_die();
}
add_action( 'wp_ajax_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
add_action( 'wp_ajax_nopriv_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
In my console from js I get:
Object { id: 15, action: "viasun_dummy_ajax_data_action" }
And XHR in console says 200 OK.
What am I doing wrong? Can you help me, please?

"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');

Variations Javascript not working when single_product_content is loaded via Ajax (WooCommerce)

In my WooCommerce Shop Templates I am loading the single-product-content dynamically in the archive-product.php page with Ajax. This part is working.
But the javascript to choose the product variations is missing so I tried to add the script to the html after the successful ajax request.
I could load the script but I still can not choose a product variation. No events are triggered. Seems like I am missing something...
My Javascript:
jQuery('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript () {
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
In functions.php
add_action( 'wp_enqueue_scripts', 'child_add_scripts' );
function child_add_scripts(){
wp_register_script( 'pa_script', get_stylesheet_directory_uri() . '/main.js', array('jquery'), true );
wp_localize_script( 'pa_script', 'singleprojectajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('pa_script');
}
function load_single_product_content () {
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
echo "There were no products found";
}
}
wp_die();
}
add_action('wp_ajax_load_single_product_content', 'load_single_product_content');
add_action('wp_ajax_nopriv_load_single_product_content', 'load_single_product_content');
The WooCommerce script "add-to-cart-variations.js":
https://searchcode.com/codesearch/view/95139130/
Did you try like:
jQuery(document).ready(function($) {
"use strict";
$('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
},
complete: function(){
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript() {
$.getScript("www.yoursitenamehere.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
$.getScript("www.yoursitenamehere.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
});
You used $ for your AJAX, so it's safe to assume you're already inside the document ready environment. So you don't need to use jQuery.
I placed the $.getScript() in the complete ajax method. Plus you need to include the entire url to your page.

Categories

Resources