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
Related
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 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'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 )
Am using WordPress ajax to load the sub-categories dynamically.
Here's my code
Php code
function techento_getsubcat() {
$category_name = $_POST['catname'];
$cat_id = $_POST['catid'];
return wp_dropdown_categories( 'show_option_none=Choose a Sub Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );
}
add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');
Jquery
jQuery(document).ready(function(){
$('#cat').change(function(e){
alert("changed");
$.ajax({
type: 'POST',
dataType: 'json',
url: pcAjax.ajaxurl ,
data: {
'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
'catname': $('#cat option:selected').text(),
'catid': $('#cat option:selected').val() },
success : function(response){
alert(response);
console.log(response);
$("#subcats").html(response);
}
});
e.preventDefault();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return
even if set it to
return true;
it then returns the raw html of subcategories generated plus '0'
You're missing the $ shortcode in
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success(), so we don't have to worry with return or echo, exit or die. For that, set echo to false in the dropdown arguments:
function techento_getsubcat() {
$cat_id = intval( $_POST['catid'] );
$args = array(
'hide_empty' => 0,
'echo' => 0,
'child_of' => $cat_id,
'taxonomy' => 'category'
);
$data = wp_dropdown_categories( $args );
wp_send_json_success( $data );
}
On Ajax success, use response.data:
success : function(response){
console.log(response.data);
}
I am trying to call ajax in wordpress. It work fine in browser but in mobile device it return response 0 . Here is my wordpress & Jquery code. please suggest where i am doing wrong
The code in functions.php file
function get_nearest_destinations()
{
$data = array();
check_ajax_referer( "getnearestdestinations" );
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$the_query = new WP_Query($args);
if($the_query->have_posts()){
while ( $the_query->have_posts() ) :
$the_query->the_post();
$data[] = array('title'=>get_the_title());
endwhile;
}
echo json_encode($data); exit();
}
add_action( 'wp_ajax_getnearest', 'get_nearest_destinations' );
Below is js code in template file....
<?php $nonce = wp_create_nonce( 'getnearestdestinations' ); ?>
jQuery.ajax({
type: "POST",
url: "<?php echo bloginfo('url').'/wp-admin/admin-ajax.php'; ?>",
data: { action: 'getnearest', _ajax_nonce: '<?php echo $nonce; ?>'},
dataType: "json",
success: function(html){
alert(html)
}
}); //close jQuery.ajax(
May be you have non logged in user issue.Pl use below syntax for non logged in users
add_action('wp_ajax_nopriv_getnearest', 'get_nearest_destinations'); // Not logged in user