load php function on ajax success - php

I'm looking for a way to call a php function if an ajax request is successful.
Basic setup code:
wp_register_script( 'theme-follow-me-ajax', ... );
wp_localize_script('theme-follow-me-ajax', 'ajax_setting', array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_follow_error' => $this->km_follow_me_error(),
....
));
wp_enqueue_script( 'theme-follow-me-ajax' );
Content to display the error, which should be customizable
public function km_follow_me_error() {
$content = esc_html__( 'An error happened. We\'re unable to complete your request.', 'theme' );
echo apply_filters( 'theme_hook_follow_me_error_message', $content );
}
Ajax call:
$.ajax( {
url : ajax_setting.ajax_url,
type : 'post',
data: {
action : 'km_ajax_follow_me',
security : ajax_setting.ajax_nonce,
...
},
success: function( data ) {
$('.km-follow-me').html( ajax_setting.ajax_follow_success ).hide().fadeIn( 'slow' );
//console.log( ajax_setting.ajax_follow_success );
},
} )
WP wp_ajax_ function
public function addon_ajax_follow_me() {
check_ajax_referer( 'km-ajax-create-nonce', 'security' );
... update user meta ...
wp_die();
}
$this->loader->add_action( 'wp_ajax_km_ajax_follow_me', $plugin_public, 'addon_ajax_follow_me' );
In console I get the null message, so it's not grabbing the km_follow_me_error function.
Is there a better way?

You're doing it incorrectly. A PHP function cannot be called/accessed from Javascript the way you're trying to do. You have two options to call that function on your AJAX success.
Create/register another AJAX function in WordPress, maybe named as ajax_follow_success and call it in success of the previous AJAX call.
Identify in your first function WordPress AJAX function i.e. addon_ajax_follow_me whether it's a success or failure and call the next function there.

Related

Ajax post request results with 400 error in wordpress

I'm currently developing a plugin. In the plugin's main.php file, I have the following code to do an ajax post request:
main.php
<?php
add_action( 'admin_footer', 'first_ajax' );
function first_ajax() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#mybutton').click(function(){
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
action : 'second_ajax'
},
success: function(response) {
console.log("successful");
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
<?php } ?>
But on the browser console, I see an error object.
Screenshot 1
Screenshot 2
I wrote this function taking as reference: https://codex.wordpress.org/AJAX_in_Plugins.
Any help is appreciated.
You're calling javascript from a php function tho your javascript is "raw" and not wrapped in a php variable. We're also missing a bunch of information in regard to the ajax action function (the php part which is supposed to answer to the request).
An ajax request need two things to be able to work properly.
The javascript call to action function and the backend php action function.
It a standard to use anonymous php functions as action functions.
Ajax action functions hooks are prepended with a wp_ajax_{$action} for public function (non-logged-in users) and wp_ajax_nopriv_{$action} for logged-in users. A logged-in user won't be able to use a public ajax function same goes for non-logged-in users.
The {$action} part is set in your javascript call to action function.
It is standard to pass a nonce as well as the ajax admin url through the localize_script() function. Localizing data only works if the script has already been registered.
An example of registering/enqueuing a script and localizing varaibles: functions.php
<?php
wp_enqueue_script( 'my-ajax-script', trailingslashit( get_template_directory_uri() ) . 'assets/js/my-ajax-script.js', array(), wp_get_theme()->version, true );
wp_localize_script( 'my-ajax-script', 'localize', array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );
(The Object's name localize and variables _ajax_url and _ajax_nonce used in wp_localize_script() are just a personal preference).
A basic javascrip ajax call to action function looks like this: my-ajax-script.js
$( '#selector' ).click( function ( event ) {
$.ajax( {
type: 'POST',
url: localize._ajax_url,
context: this,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73933867', //where this match {$action} from wp_ajax_{$action} in our php action function.
},
success: function ( response ) {
console.log( response );
//...
},
} );
} );
Where we use are localized variables: localize._ajax_url and localize._ajax_nonce (best practices).
A basic php ajax action function looks like this: functions.php
<?php
add_action( 'wp_ajax__wpso_73933867', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
//...
wp_send_json_success();
} else {
//...
wp_send_json_error();
};
wp_die();
} );
If the function is intended to be use by a non-logged-in user wp_ajax_nopriv should be prepended instead of wp_ajax_. Vice versa. If both case are supposed to be used, the function should be doubled.

Ajax script with wordpress is adding a random '0' in my output [duplicate]

This question already has answers here:
Wordpress Ajax returns '0'
(3 answers)
Closed 1 year ago.
I have created a wordpress plugin that uses ajax to update a div every 10 seconds.
It seems to work and is running the AJAX GET request, and outputs test as it should, how ever also adds a 0 to the div output. (response)
I cant work out why it is doing it? Any suggestions?
PHP
<?php
add_action( 'wp_enqueue_scripts', 'aj_enqueue_scripts' );
function aj_enqueue_scripts() {
wp_enqueue_script( 'aj-demo', plugin_dir_url( __FILE__ ). 'aj-demo-ajax-code.js?v=2', array('jquery') );
// The second parameter ('aj_ajax_url') will be used in the javascript code.
wp_localize_script( 'aj-demo', 'aj_ajax_demo', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'aj_demo_nonce' => wp_create_nonce('aj-demo-nonce')
));
}
add_action( 'wp_ajax_nopriv_aj_ajax_demo_get_count', 'aj_ajax_demo_process' );
add_action( 'wp_ajax_aj_ajax_demo_get_count', 'aj_ajax_demo_process' ); // For
function aj_ajax_demo_process() {
echo "test";
}
?>
Jquery / JS
jQuery(document).ready( function(){
setInterval(function(){
jQuery.ajax({
url : aj_ajax_demo.ajax_url,
type : 'get',
data : {
action : 'aj_ajax_demo_get_count',
nonce : aj_ajax_demo.aj_demo_nonce,
},
success : function( response ) {
jQuery('.now_playing_info').html(response);
},
error : function( response ) {
}
});
}, 10000);
});
Try to add an exit; at the end of function.
function aj_ajax_demo_process() {
echo "test";
exit; // add this line
}
WordPress will continue to call all of the AJAX registered callbacks until one of the callbacks kills the execution, with the final one dieing with the response of 0.
So just use wp_die() at the end of your code
function aj_ajax_demo_process() {
echo "test";
wp_die();
}

How to pass php variable to wordpress AJAX handler

Struggling to pass through some php variables into my ajax handler function in functions.php
Example provided below doesn't work, probably has something to do with the hooks but I can't find any info on how to do this:
/*Unsubscribe*/
$test_variable = "derp";
function user_unsubscribe($test_variable){
echo json_encode($test_variable);
wp_die();
};
add_action('wp_ajax_user_unsubscribe', 'user_unsubscribe');
add_action('wp_ajax_nopriv_user_unsubscribe', 'user_unsubscribe');
Solved it with this solution: can I pass arguments to my function through add_action?
Working code solution is:
/*Unsubscribe*/
$test_variable = "derp";
function user_unsubscribe($test_variable){
echo json_encode($test_variable);
wp_die();
};
add_action('wp_ajax_user_unsubscribe', function() use ($test_variable){
user_unsubscribe($test_variable);
});
add_action('wp_ajax_nopriv_user_unsubscribe', function() use ($test_variable){
user_unsubscribe($test_variable);
});
You can pass that PHP variable in ajax data. Please check below files in which I had send the "test_variable" Value to Ajax Function from jQuery.
Jquery File Code
jQuery(document).ready(function($) {
$('#btn').on('click',function(){
$.ajax({
data: {action: 'get_listing_names','test': global.test_variable},
type: 'post',
url: global.ajax,
success: function(data) {
console.log(data);
}
});
});
});
Functions.php file Code.
<?php
/**
* Enqueue scripts and styles.
*
* #since 1.0.0
*/
function ja_global_enqueues() {
wp_enqueue_script(
'global',
get_template_directory_uri() . '/js/global.js',
array( 'jquery' ),
'1.0.0',
true
);
wp_localize_script(
'global',
'global',
array(
'ajax' => admin_url( 'admin-ajax.php' ),
'test_variable' => 'Test Value',
)
);
}
add_action( 'wp_enqueue_scripts', 'ja_global_enqueues' );
add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');
function ajax_listings() {
$test_variable = $_POST['test_variable'];
wp_send_json_success( $test_variable );
}
The prefered way to pass variables to ajax is to add them to the request and read them from $_GET or $_POST official documentation
If you need other variables you'll either have to use globals or call a extra function.
favorite
Struggling to pass through some php variables into my ajax handler function in functions.php
Example provided below doesn't work, probably has something to do with the hooks but I can't find any info on how to do this:
function user_unsubscribe(){
$test_variable = get_test_variable();
echo json_encode($test_variable);
wp_die();
};
add_action('wp_ajax_user_unsubscribe', 'user_unsubscribe');
add_action('wp_ajax_nopriv_user_unsubscribe', 'user_unsubscribe');
function get_test_variable() {
// here get/fetch your variable;
/*Unsubscribe*/
$test_variable = "derp";
return $test_variable;
}

Passing variable from Ajax to PHP in WordPress plugin

I am developing a WordPress plugin and I am trying to pass a variable from ajax to a php file. Both files are inside my plugin folder. The js file is running but when I fire the ajax function, it seems that is not sending a post.
Plugin structure:
-plugin folder
--ajax.js
--folder/example.php
This is my ajax.js
// using jQuery ajax
// send the text with PHP
$.ajax({
type: "POST",
url: "/absoluteurlpluginfolder/folder/example.php",
data: {
'action': 'my_action',
'whatever': 1234
},
// dataType: "text",
success: function(data){
console.log('Connection success.');
// console.log(data);
}
});
And this is my example.php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
alert($whatever);
wp_die(); // this is required to terminate immediately and return a proper response
}
I have two problems:
I cannot see that example.php is receiving anything
How could I use a relative URL to connect with my PHP file? When I try such as 'url: "folder/example.php",' it seems that it starts with "http://localhost/my-wp-project/wp-admin/" and not in my plugin folder, and fails.
I think that the main problem was that I need to add "wp_enqueue_script" and "wp_localize_script". However, I am working in the development of a TinyMCE plugin inside WordPress.
That means that although the JS file is already include, it is not working when I add "wp_enqueue_script" and "wp_localize_script". Why? I do not know but the strange thing is that I made it working with another line.
wp_register_script( 'linked-plugin-script', null);
I have tried with different versions, and the minimum necessary to work is this one above. I can put the URL, version, jquery dependency and false or true. All of them work.
So at the end this is my code and is working.
This is the plugin.php
// Include the JS for TinyMCE
function linked_tinymce_plugin( $plugin_array ) {
$plugin_array['linked'] = plugins_url( '/public/js/tinymce/plugins/linked/plugin.js',__FILE__ );
return $plugin_array;
}
// Add the button key for address via JS
function linked_tinymce_button( $buttons ) {
array_push( $buttons, 'linked_button_key' );
return $buttons;
}
// Enqueue the plugin to manage data via AJAX
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'linked-plugin-script', null);
wp_enqueue_script( 'linked-plugin-script');
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'linked-plugin-script', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'whatever' => '' )
);
}
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = strtoupper($_POST['whatever']);
echo $whatever;
wp_die();
}
And this is the plugin of TinyMCE in JavaScript
// JavaScript file for TinyMCE Linked Plugin
//
//
//
( function() {
tinymce.PluginManager.add( 'linked', function( editor, url ) {
// Add a button that opens a window
editor.addButton( 'linked_button_key', {
// Button name and icon
text: 'Semantic Notation',
icon: false,
// Button fnctionality
onclick: function() {
// get raw text to variable content
var content = tinymce.activeEditor.getContent({format: 'text'});
// using jQuery ajax
// send the text to textrazor API with PHP
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: { 'action': 'my_action',
'whatever': ajax_object.whatever = content
},
beforeSend: function() {
console.log('before send..');
},
success: function(response){
console.log('Success the result is '+response);
}
});
} // onclick function
} ); // TinyMCE button
} ); // tinymce.PluginManager
} )(); // function
Have you seen this page? This is the best tutorial. But you have missed a few things:
You should set global js variable with wp_localize_script() function. Like
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
Replace your url in JS to ajax_object.ajax_url.
IF you wanna work ajax with wp_ajax hooks - you should send all your requests do wp-admin/admin-ajax.php. You can get this url by admin_url('admin-ajax.php');.

Call ajax action after submission of comment in wordpress

I have searched for this a lot but still didn't found any solution for this . I want to call an ajax action after submission of post comment . How can I do this with WordPress ?
Without code, I cannot give you the following steps with code myself:
Track the event that triggers comment submission and on which DOM element it happens.
In the event handler, send an XMLHTTPRequest to server using jQuery.ajax.
Make sure you create the ajax call in the Wordpress way, and so by sending requests to wp-admin/admin-ajax.php and puting logic under functions.php. Add the die() function.
I would filter the comment with a WordPress filter. You may not need an AJAX request at all. But I'm not exactly sure why you need AJAX. To learn more about this filter.
function preprocess_comment_handler( $commentdata ) {
//some code
return $commentdata;
}
add_filter( 'preprocess_comment' , 'preprocess_comment_handler' );
If you do need AJAX, here's how to make it run in WordPress. You'll need to use wp_localize_script() to get your AJAX to admin-ajax.php.
//add wp_localize_script to your functions.php
//make sure to enqueue the js file you are writing to and it's dependencies
function acarter_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script('your-script', get_template_directory_uri() . '/js/theme.js');
wp_localize_script('your-script', 'your_script_vars', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
add_action( 'wp_enqueue_scripts', 'acarter_enqueue_scripts' );
//do your AJAX call in the file you just enqueued
jQuery( document ).ready( function($) {
//Ajax Form Processing
var $form = $( '#button' )
$form.submit( function (e) {
e.preventDefault();
$.ajax({
type: '',
url: your_script_vars.ajaxurl,
data: {
action: 'function_name_of_the_callback',
//key : values of stuff you want in the php callback
},
dataType: 'json',
success: function (response) {
if ( true === response.success ) {
console.log( 'success!!' );
});
} else if ( false === response.success && response.data ) {
window.alert( 'doing it wrong' );
}
}
});
});
});
You maybe able to send the data to the aforementioned filter, thus using the filter as the callback, but, I've never tried this. At the least you'll know how to setup AJAX in WordPress.

Categories