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 )
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 create a post from the front-end using WP Ajax but getting a 400 Bad Request error.
The data is coming from a server API response. What I'm trying to achieve is to save the JSON data I'm getting from the API response into a WP POST using Ajax. I know that there are lots of similar questions here in StackOverflow and Google Search and I already tried all of the solutions but still can't solve mine. I'm literally trying to solve this by just doing research for about 12 hours but still no luck.
Below is my current code:
PHP:
add_action( 'wp_enqueue_scripts', 'invicta_uploadpage_enqueue_scripts_styles', 5 );
function invicta_uploadpage_enqueue_scripts_styles() {
// AJAX JS
wp_enqueue_script(
'dropzone-config',
get_stylesheet_directory_uri() . '/lib/assets/dropzonejs/dropzone.config.js',
array('jquery')
);
wp_localize_script(
'dropzone-config',
'dropzoneconfigajax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
// Creating Ajax call
function vc_create_post() {
$fileid = $_POST['uploadfileid'];
$filename = $_POST['uploadfilename'];
$filesize = $_POST['uploadfilesize'];
$post_id = wp_insert_post( array(
'post_title' => $filename,
'post_content' => 'Download ' . $filename,
'post_status' => 'publish',
'post_author' => '1',
'comment_status' => 'closed',
'meta_input' => array(
'fileid' => $fileid,
'filesize' => $filesize,
)
));
if ( $post_id != 0 ) {
// success. do something.
} else {
// failed. say something.
}
die();
}
add_action( 'wp_ajax_vc_createpost_ajax', 'vc_create_post' );
add_action( 'wp_ajax_nopriv_vc_createpost_ajax', 'vc_create_post' );
JS dropzone.config.js:
jQuery(document).ready(function($){
function createPost(fileID, fileName, fileSize) {
$.ajax({
url: dropzoneconfigajax.ajaxurl,
type: 'POST',
data: {
action: 'vc_createpost_ajax',
uploadfileid: fileID,
uploadfilename: fileName,
uploadfilesize: fileSize
},
success: function(data, textStatus, XMLHttpRequest) {
console.log('post succesfully created! Data: ' + data )
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
});
The value of fileID, fileName, fileSize will be coming from another ajax call which is a server response after a file upload. ex: createPost(json.result.id, json.result.name, json.result.size);
Edit: I would also like to note that I'm implementing it on a WP Child Theme and not as a plugin and on a custom page template (Genesis Framework).
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
}
});
I am displaying events with a date filter in wordpress. Current date is preselected and so events on the current day display by default. If someone clicks on another date, I call function newDate.
Problem: I pass the new variable with post method successfully, but can't pass it to php. Variable is in the unix timestamp format.
//calendar.js
function newDate(selectedDate){
var sendDate = selectedDate;
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate : sendDate
}
});
}
In my functions php I enqueue, localize the scrip and call the functions
//functions.php
wp_enqueue_script( 'calendar', get_template_directory_uri() .
'/resources/js/calendar.js', array( 'jquery' ), '1.0', true);
wp_localize_script('calendar', 'ajax_date', array(
'ajaxurl' => admin_url('admin-ajax.php'));
add_action( 'wp_ajax_nopriv_submit_date', 'submit_date' );
add_action( 'wp_ajax_submit_date', 'submit_date' );
function submit_date(){
$newdate = $_POST['sendDate'];
wp_die();
};
And finally my php file for displaying events. var_dump prints out null and echo also displays no content.
<div id ="events-container">
<?php
echo $newdate;
var_dump($newDate);
?>
EDIT - FIXED
Thank you, it worked, my code as follows:
//events-page.php
<div id ="events-container">
<?php
echo get_events($args);
?>
</div>
//calendar.js
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate1 : date1,
sendDate2 : date2
}
}).done(function(data) {
console.log( data ); // will log the data you get back from your PHP function.
// Now you can display it on the view
$('#events-container').html(data);
})
//functions.php
wp_enqueue_script( 'calendar', get_template_directory_uri() . '/resources/js/calendar.js', array( 'jquery' ), '1.0', true);
wp_localize_script('calendar', 'ajax_date', array(
'ajaxurl' => admin_url('admin-ajax.php')));
//ajax actions
add_action( 'wp_ajax_nopriv_submit_date', 'submit_date' );
add_action( 'wp_ajax_submit_date', 'submit_date' );
function submit_date(){
$newdate1 = $_POST['sendDate1'];
$newdate2 = $_POST['sendDate2'];
$args = array(
'post_type' => 'epsa_events',
'posts_per_page' => 5,
'order' => 'ASC',
'meta_query' => array (
array(
'key' => 'start_time',
'value' => array($newdate1, $newdate2),
'compare' => 'BETWEEN'
)
));
get_events($args);
wp_die();
};
function get_events($args){
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="entry-content">';
the_title();
the_content();
$startTime = DateTime::createFromFormat('Y-m-d H:i', get_field('start_time'));
echo date_format($startTime, 'H:i a d.m.');
echo '</div>';
endwhile;
}
You need a callback on your $.ajax() method. Right now, you just send the data to your PHP function, but you don't get it back on front.
//calendar.js
function newDate(selectedDate){
var sendDate = selectedDate;
$.ajax({
type : 'POST',
url: ajax_date.ajaxurl,
data: {
action: 'submit_date',
sendDate : sendDate
}
}).done(function(data) {
console.log( data ); // will log the data you get back from your PHP function.
// Now you can display it on the view
$('#events-container').html(data);
});
}
More information : http://api.jquery.com/jquery.ajax/
You need to process ajax date after getting date in $_POST['sendDate'] in submit_date function either by applying WP_Query or any your custom written function of your plugin and you need to echo processed results before wp_die() then you can get the data in ajax success function and with jquery can insert your results.
A thorough guide you can check here:
https://www.creare.co.uk/blog/simple-wp_query-ajax
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.