Using a do_shortcode in wordpress via an ajax call - javascript

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.

Related

Problem when sending an ajax post request in WordPress

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.

WordPress AJAX "POST" response only works from functions.php

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 )

What is the best way to post input data and insert them to the database with ajax in wordpress?

I developed a contact form with pure PHP and HTML. I wanna insert the input values into the database with AJAX. Here is my Javascript/jQuery code:
var email = jQuery("#email").val();
var data = {
'email': email
}
jQuery.ajax({
type: "POST",
url: "http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php",
dataType: "json",
data: data,
success : function(data) {
// do something
}
});
And my contactform.php:
$date = date('Y-m-d H:i:s');
global $wpdb;
$wpdb->insert('myTableName', array(
'email' => $_POST["email"],
'date' => $date,
));
My code works well. My question is what is the correct way to do that? Because I think it's not a good idea to create a .php file inside the WordPress theme and use it just for inserting data into the database. I think it has security issues and users can see my script URL (http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php) that used in my javascript file for using ajax.
Do you have better ways to do that?
Create a function for inserting data and also enqueue script for ajax call and pass it in url. example like:
function mytheme_admin_scripts() {
wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/admin_script.js');
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts','mytheme_admin_scripts' );
Enqueue your js file which you have wrote your ajax call and pass my_ajax_object.ajx_url in your ajax url.
jQuery.ajax({
type : "POST",
url : my_ajax_object.ajax_url,
data : data,
dataType: "json",
cache: false,
success : function(data) {
// do something
}
});

Wordpress cannot get_current_user_id() from ajax request

I try to do an ajax request with wordpress. So I've created a simple js request:
$.ajax({
url: '?',
type: 'POST',
data: {
'pr_post': post,
'pr_rating': rating
},
success: function (response) {
console.log(response);
}
});
Here is my function to handle the request.
function pr_request()
{
if (isset($_REQUEST['pr_post']) && isset($_REQUEST['pr_rating']) && isset($_REQUEST['pr_user'])) {
$post = $_REQUEST['pr_post'];
$rating = ($_REQUEST['pr_rating'] > 5 ? 5 : $_REQUEST['pr_rating']);
$user = get_current_user_id();
if (!pr_has_user_already_voted($user, $post)) {
global $wpdb;
$table = $wpdb->prefix . 'mitmach_ratings';
$wpdb->query($wpdb->prepare("insert into $table values (null, $post, $rating, '$user');"));
wp_send_json(['message' => 'success']);
} else {
wp_send_json(['message' => 'duplicate'], 403);
}
}
}
As you see I call the get_current_user_id() function. This function always returns true even if the user logged in. How can I get the user id in my handler without sending it via ajax?
For a start check docs - WP Ajax.
You need to send action key
Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below. This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.
$.ajax({
url: '?',
type: 'POST',
data: {
action : 'pr_post',
pr_rating : rating
},
success: function (response) {
console.log(response);
}
});
and call like this:
add_action( 'wp_ajax_pr_request', 'pr_request' );
add_action( 'wp_ajax_nopriv_pr_request', 'pr_request' );
function pr_request() {
// Code
}

Wordpress Plugin Class setup Ajax

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.

Categories