Im making a plugin using Class , I need to run some Ajax on the Front end. All scripts are queue up correctly. when i trigger the call, i get 400 error.
class CCYTFeatured {
public function __construct(){
add_action( 'wp_enqueue_scripts', array($this, 'cc_yt_scripts' ));
add_action( 'wp_ajax_cc_get_featured_yt', array( $this, 'cc_get_featured_yt' ) );
add_action( 'wp_ajax_nopriv_cc_get_featured_yt', array( $this, 'cc_get_featured_yt' ) );
}
public function cc_yt_scripts() {
// JAVASCRIPT
wp_register_script( 'cc_yt_script',
plugins_url( '/js/cc_yt.js', __FILE__ ),
array('jquery'),
cc_yt_version(),
true
);
wp_localize_script(
'cc_yt_script',
'cc_yt_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
wp_enqueue_script('cc_yt_script');
}
public function cc_get_featured_yt(){
echo 'SUCCESS!';
die();
}
My ajax call is:
function start_yt(){
jQuery('#cc_yt_light_wrap').show();
// REGISTER NEW ENTRY USING AJAX
jQuery.ajax({
url: cc_yt_ajax.ajax_url,
type: 'POST',
data: {
action : 'cc_get_featured_yt',
},
async: true,
success: function(response) {
console.log(response);
}
});
}
Thanks for your help! X)
Try this:
Change the method name from cc_get_featured_yt to get_featured, and change the method name everywhere in your class.
and then in the ajaxcall you put this code:
data: {
action : 'featured_yt',
}
I think the get in the methodname is a keyword. This worked for me.
The code is ok,
The way i was calling the class was wrong.
I was calling this inside a theme. Instead, i created a new method and moved everything from __construct().
Started my class and called the method inside the plugin file. After i started the class again and only called the needed method inside my theme. Worked perfectly.
Related
I've read several articles on how to do this and all of them mention the same thing that I am using. I have two files for this:
In the receiver.php file:
<?php
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action( 'wp_ajax_my_action', 'theActionFunction' );
function my_enqueue() {
wp_register_script( 'ajax-script', plugins_url( '/src/WyrRoute.js' , __FILE__ ), array('jquery') );
wp_enqueue_script('ajax-script');
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
function theActionFunction(){
$theQuestion = $_POST['question_id'];
echo $theQuestion; //doesn't show anything in the frontend
wp_die();
}
echo "hello" //works if outside the function
The issue is that nothing inside this theActionFunction prints in the frontend. Anything I type outside shows in the frontend, there must be something basic that I'm missing here.
WyrRoute.js
clickHandler(e) {
var ajax_url = my_ajax_object.ajax_url
var data ={
'action': 'my_action',
'question_id': '10183'
}
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
dataType: 'json',
success: function (xhr, x, checkStatus) {
console.log(xhr);
console.log(checkStatus.status)
console.log("success")
},
error: function(e) {
console.log(e.statusText);
console.log("failure")
}
});
}
Ajax returns with 200 success, so no issue there, but for some reason, I can't get the $_POST['value'] to print in the frontend using php.
Welcome.
Well, from what I'm seeing in the code, it looks ok. At first glance, the thing I noticed is that you are declaring the function called "theActionFunction", but you arent calling it anywhere. Again it may just be me, but, if the method isn't printing anything, right underneath it, put this:
theActionFunction();
And you should be good to go. In total, it should look like this:
function theActionFunction(){
$theQuestion = $_POST['question_id'];
echo $theQuestion; //This should now work
wp_die();
}
theActionFunction();
Happy coding.
I'm trying to follow this tutorial to add a load more button to a site I'm working on.
tldr:
Ajax request just printing
<empty string>
on success and failing to render anything to the page
So I've added the button
<?php
// don't display the button if there are not enough posts
if ($query->max_num_pages > 1)
echo '<div class="misha_loadmore">More posts</div>';
?>
and localised the script I'm using
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');
// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
$args = [
'post_type' => 'news',
'posts_per_page' => 1,
'paged' => get_query_var('paged') ? get_query_var('paged') : 1
];
$query = new WP_Query($args);
// we have to pass parameters to myloadmore.js
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $query->max_num_pages
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
This seems to be fine, the cpt is 'news' so i added a query to the function here to look for that.
Then I added the js
jQuery(function ($) {
// use jQuery code inside this to avoid "$ is not defined" error
$(".misha_loadmore").click(function () {
var button = $(this),
data = {
action: "loadmore",
query: misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
page: misha_loadmore_params.current_page,
};
$.ajax({
url: misha_loadmore_params.ajaxurl, // AJAX handler
data: data,
type: 'POST',
dataType: 'text',
beforeSend: function (xhr, data) {
button.text("Loading..."); // change the button text, you can also add a preloader image
console.debug(data);
},
success: function (data) {
console.debug(data);
if (data) {
button.text("More posts").prev().before(data); // insert new posts
misha_loadmore_params.current_page++;
if (
misha_loadmore_params.current_page == misha_loadmore_params.max_page
)
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.debug(xhr.status);
console.debug(ajaxOptions);
console.debug(thrownError);
},
});
});
});
and this is my ajax function
function misha_loadmore_ajax_handler(){
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
// get_template_part( '<h1>testBen</h1>' );
// for the test purposes comment the line above and uncomment the below one
get_the_title();
endwhile;
endif;
die; // here we exit the script and even no wp_reset_query() required!
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
So my issue I think is in the jquery file (not sure?) on the pre function I'm outputing the data and it's showing:
Object { url: "http://nichy.local/wp-admin/admin-ajax.php", type: "POST", isLocal: false, global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: {…}, contents: {…}, responseFields: {…}, … }
But printing it on the success just shows:
<empty string>
And the button 'loads' and goes away but nothing more is rendered to the page
I'm trying to create a stand alone WordPress Ajax plugin.
The code works but only if I put the PHP code to process the Ajax POST request in my WordPress theme's functions.php file.
When I put the PHP code to process the request in a separate file within my plugin folder instead of functions.php, I get POST response 0.
I've been struggling with this for days now, any help would be appreciated.
Main Plugin .PHP
<?php
/**
*Plugin Name: poc-invoice-ajax
*Description: Custom POC Invoicing
*Author: A-POC
**/
if (! defined('ABSPATH')) {
exit;
}
add_action('wp_ajax_poc_invoice_send','poc_invoice_send');
add_action('wp_ajax_nopriv_poc_invoice_send','poc_invoice_send');
add_action('wp_enqueue_scripts','load_poc_assets');
function load_poc_assets(){
global $template;
if ( basename( $template ) === 'poc.php' ) {
wp_enqueue_script('ajax-script', plugins_url( '/js/poc-invoice.js', __FILE__ ), array( 'jquery' ));
wp_enqueue_script('poc-process', plugins_url( '/process/index.php', __FILE__ ));
wp_localize_script( 'ajax-script', 'poc_invoice_js_objects', array(
'security' => wp_create_nonce( 'poc_invoice_nonce' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
wp_enqueue_script( 'jspdf', $src='https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js');
}
}
?>
Javascript
jQuery(document).ready(function(){
jQuery("#form1").submit(function(){
event.preventDefault();
var form_data = jQuery(this).serialize();
var formdata = new FormData;
formdata.append('enquiry', form_data)
jQuery.ajax({
method: "post",
url: poc_invoice_js_objects.ajax_url,
data: {
action: 'poc_invoice_send',
//security: poc_invoice_js_objects.security,
data: form_data
},
success: function(data){
console.log(data)
}
});
});
});
PHP code to process ajax request:
[If this code is in functions.php the ajax POST will send the correct response.]
<?php
$path = preg_replace('/wp-content.*$/','',__DIR__);
require_once($path."wp-load.php");
add_action('wp_ajax_poc_invoice_send','poc_invoice_send');
add_action('wp_ajax_nopriv_poc_invoice_send','poc_invoice_send');
function poc_invoice_send() {
echo "test";
wp_die();
}
?>
Plugin Folder Structure:
Plugin Folder:
Main Plugin.php
js (folder)
plugin.js
process (folder)
index.php (standalone PHP code to process the Ajax request )
i was done adding this script into \mythemes\functions.php:
// FGI CODE started
function my_scripts_method() {
// register your script location, dependencies and version
wp_register_script('custom_script',
get_template_directory_uri() . '/js/javascript_.js',
array('jquery'),
'1.0' );
// enqueue the script
wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
wp_enqueue_script('jquery');
// FGI CODE ended
and also my jQuery script which is located under \mythemes\js\javascript_.js :
(function($) {
$(document).ready(function() {
$("#pilih_bulan").change(function() {
alert('a');
});
})
})(jQuery);
actually my purpose is making a combobox with an ID of : #pilih_bulan
always trigger some ajax function each time user change the selection (dropdown items).
And the above code (using alert code) is working fine. Unfortunately, when I changed into this below code, it doesn't work at all. Any ideas?
(function($) {
$(document).ready(function() {
$("#pilih_bulan").change(function() {
$.ajax({
method: "POST",
url: "./another_processor.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
})
})(jQuery);
Use the below script and why you used wp_enqueue_script('jquery'); please check your source code jquery must be already added
<?php
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/custom_script.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>
I have the following piece of Ajax which calls a php file which intends to return the HTML content of a shortcode.
The Ajax call looks like this :
var PostData = "Action=refresh-cart";
jQuery.ajax({
dataType: "text",
type: 'POST',
url : '<?php echo plugins_url( 'class-booking-system/class-booking-process.php', dirname(__FILE__) );?>',
cache: false,
data : PostData,
complete : function() { },
success: function(data) {
// jQuery("#loading-img").hide();
alert(data);
// jQuery("#join-class-div-3").html(data);
}
});
The PHP looks like this :
<?php
require_once( ABSPATH . '/wp-includes/shortcodes.php' );
if(isset($_POST['Action'])) {
$Action = $_POST['Action'];
if($Action == "refresh-cart") {
echo do_shortcode('[woocommerce_cart]');
}
}
?>
However when I call my Ajax method it returns an HTTP 500 - which I assume means the do_shortcode function was not found in this context. How can I give my plugin the ability to call this wordpress function via ajax?
I think you should take a look at the Codex article on using Ajax in Plugins. It provides a very good example on how to go about making ajax calls in WordPress.
Adapting their example to your code I get something like the following:
First we load the javascript. We also pass some javascript variables via wp_localize_script. In this case, we're going to pass the admin's URL for processing all ajax calls.
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
Second, in our javascript we can make the ajax call and define our ajax "action" and any other data we need in the data object. Because "action" has kind of a different meaning, I've renamed your action to "refresh_cart".
jQuery(document).ready(function($) {
$.ajax({
type: 'POST',
url : ajax_object.ajax_url,
cache: false,
data : { 'action': 'my_action', 'refresh_cart': 'yes' },
complete : function() { },
success: function(data) {
// $("#loading-img").hide();
alert(data);
// $("#join-class-div-3").html(data);
}
});
});
Third, we need to set up the callback for our ajax action. admin-ajax.php looks through all of WordPress's pre-configured actions and then also looks for anything added to the wp_ajax_$my_action_name on the back-end and wp_ajax_nopriv_$my_action_name on the front-end. I am assuming your question concerns the front-end and since in the data object we set action = my_action the corresponding action hook would be wp_ajax_nopriv_my_action... to which we have attached the my_action_callback function. WordPress should be fully loaded and their shouldn't be an issue running shortcodes as far as I can tell.
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
if( isset($_POST['refresh-cart']) && $_POST['refresh-cart'] == 'yes' ) {
echo do_shortcode('[woocommerce_cart]');
}
die();
}
And voila! I think that should do it, but I have to warn you that I didn't test any of this, so use with prudence.