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.
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 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
}
});
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.
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.