Wordpress wp_ajax not called - javascript

I try to get my first AJAX Function working in Wordpress 4.3.
I have build an plugin named "calipso".
In the plugin there are the two files
calipso.php :
<?php
/**
* #package calipso
* #version 1.0
*/
/*
Plugin Name: calipso
Plugin URI: http://www.calipso.de
Description: Dieses Plugin for Calipso-Projekt.
Author: Calipso
Version: 1.0
Author URI: http://www.calipso.de
*/
function llv_integrates() {
$plugin_url = plugins_url( '/', __FILE__ );
wp_enqueue_script('MyAjax',$plugin_url . 'MYajax.js', array( 'jquery' ),'1.0.0',false);
$ajaxObjekt = array( 'ajaxURL' => admin_url( 'admin-ajax.php' ) );
wp_localize_script('MyAjax', 'ajaxObjekt', $ajaxObjekt);
}
add_action( 'wp_enqueue_scripts', 'llv_integrates' );
function TEST_callback(){
$anzahl= $_POST['anzahl'];
//$anzahl = isset($_POST['anzahl']) ? $_POST['anzahl'] : '';
$datei_handle=fopen("logmeInWPAnzahl.txt","a");
fwrite($datei_handle, "Anzahl: ".$anzahl."\n");
fclose($datei_handle);
wp_die();
}
add_action('wp_ajax_TEST_callback','TEST_callback');
add_action('wp_ajax_nopriv_TEST_callback','TEST_callback');
and MYajax.js :
function JStoPHP(){
console.log("JStoPHP is called");
console.log(ajaxObjekt.ajaxURL);
jQuery.ajax({
url:ajaxObjekt.ajaxURL,
data: {action:'TEST_callback' , anzahl: "12315"},
datatype: "json",
type: "POST",
success: function(respose) {
console.log(respose);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
JStoPHP();
Expected operation: transfer of the variable 'Number' from the JavaScript function JStoPHP to via ajax called PHP function TEST_callback.
Currently the TEST_callback function seems to be not invoked. Where is my mistake?

The Code must be at the first place in the plugin to get working.

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.

WP Ajax Load more button returning empty string

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

WordPress - AJAX and wp-admin/admin-ajax.php 400 Bad Request error

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

Why my wordpress ajax isn't calling in frontend javascript file?

I am using ajax in js file. but now getting error in that "mydomain.com/my_ajax.ajax_url not found 404" in console logs.
here is my js file (demo.js) code. tried all methods but no solution--
jQuery.ajax({
type: "post",
url: "my_ajax.ajax_url",
data: { action: "data_fetch", keyword: input }
});
my functions.php -------
add_action( 'wp_enqueue_scripts', 'hindrise_script');
function my_enqueue() {
wp_register_script('plugin-ajaxJs', CHILD_URL . '/js/demo.js', __FILE__);
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
The function name is different than what you have defined in add_action. Use the same name in the add_action and the function name:
add_action( 'wp_enqueue_scripts', 'hindrise_script');
function hindrise_script() {
wp_register_script('plugin-ajaxJs', CHILD_URL . '/js/demo.js', __FILE__);
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
Also in the JS file remove the quotes for the passing variable:
jQuery.ajax({
type: "post",
url: my_ajax.ajax_url,
data: { action: "data_fetch", keyword: input }
});

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