jQuery(document).ready(function(e) {
jQuery('#m').click(function()
{
//jQuery(this).fadeOut();
var d='<?php echo $plugins;?>';
jQuery.ajax({url:d,data:{q:10},type:GET,success: function(msg)
{
alert(msg);
}
}
)
});
I have to develop my own plugin, basically Wordpress has an admin-ajax file which handles this type of request, so how can I make it request using its own file to handle an Ajax request?
for that you need to do it like this:
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
and in your handler file :
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) return; // Only applies to dashboard panel
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, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $email_nonce ) );
}
And Do not forget to enqueue your script :
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) return; // Only applies to dashboard panel
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, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $email_nonce ) );
}
Related
My ajax call on click redirects me to /undefined, /wp-admin/admin-ajax.php has value 0
I'm using Divi theme, custom ajax script which is localized:
function my_enqueue() {
wp_enqueue_script( 'increment_counter', get_stylesheet_directory_uri() . '/js/slug-ajax.min.js', array('jquery') );
wp_localize_script( 'increment_counter', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
Counter function:
add_action('wp_ajax_increment_counter', 'my_increment_counter');
add_action('wp_ajax_nopriv_increment_counter', 'my_increment_counter');
function my_increment_counter(){
// Name of the option
$option_name = 'my_click_counter';
// Check if the option is set already
if ( get_option( $option_name ) !== false ) {
$new_value = intval(get_option($option_name)) + 1;
// The option already exists, so update it.
update_option( $option_name, $new_value );
} else {
// The option hasn't been created yet, so add it with $autoload set to 'no'.
$deprecated = null;
$autoload = 'no';
add_option( $option_name, 1 , $deprecated, $autoload );
}
}
Ajax file has this jQuery code for increment counter:
jQuery(document).ready(function($){
$('.activate-popup-animation').click(function(e){
e.preventDefault();
$.ajax({
url: my_ajax_object.ajaxurl,
data: {
action: 'increment_counter',
},
type: 'POST',
})
.done(function(){
// go to the link they clicked
window.location = $(this).attr('href');
})
.fail(function(xhr){
console.log(xhr);
})
});
});
Now, plan is to create custom widget in dashboard and call this function:
get_option('my_click_counter')
Where I'm making mistake, is that url problem with call action?
Your ajax function should call some action, in this case "my_increment_counter", but instead you wrote "increment_counter", same with wordpress hooks. It should be:
add_action('wp_ajax_my_increment_counter', 'my_increment_counter');
add_action('wp_ajax_nopriv_my_increment_counter', 'my_increment_counter');
I am using a metabox in the Post creator to store extra content as described in this post
Now, I would like to execute the shortcode [extra] on the click of a button similar to this post, but I can't get it to work.
Here's my code so far:
jQuery
jQuery(document).ready(function($) {
$('#extra').on('click',function() {
$.ajax({
type: "POST",
url: my_ajaxurl,
data: {
action : 'process_shortcode_on_click_action'
},
success:function(data) {
console.log("Success");
},
error: function(errorThrown){
console.log("Error");
}
});
})
})
functions.php
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'extra-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
wp_localize_script( 'extra-script', 'my_ajaxurl', admin_url( 'admin-ajax.php' ) );
}
add_shortcode( 'extra', 't5_extra_content' );
add_action( 'add_meta_boxes_post', 't5_register_extra_metabox' );
add_action( 'save_post', 't5_save_shortcode_box', 10, 2);
add_action( 'wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
add_action( 'wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
function process_shortcode_on_click_ajax() {
echo do_shortcode('[extra]');
die;
}
function t5_extra_content( $attributes, $content = '' )
{
$args = shortcode_atts( array ( 'cap' => 'edit_posts' ), $attributes );
if ( current_user_can( $args['cap'] ) )
return wpautop(
get_post_meta( get_the_ID(), '_t5_extra_box', TRUE )
. $content
);
}
function t5_register_extra_metabox()
{
add_meta_box(
't5_extra',
'My Point of View',
't5_extra_metabox_callback',
NULL, // screen
'normal',
'default'
);
}
function t5_extra_metabox_callback( $post )
{
$nonce = wp_create_nonce( __FILE__ );
echo "<input type='hidden' name='t5_extra_box_nonce' value='$nonce' />";
$content = get_post_meta($post->ID, '_t5_extra_box', TRUE );
wp_editor(
$content,
'_t5_extra_box',
array (
'textarea_rows' => 10,
'media_buttons' => FALSE,
'teeny' => TRUE,
'tinymce' => TRUE
)
);
}
function t5_save_shortcode_box( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE
or ! isset ( $_POST['post_type'] )
or 'post' !== $_POST['post_type']
or ! current_user_can( 'edit_post', $post_id )
or ! wp_verify_nonce( $_POST[ 't5_extra_box_nonce' ], __FILE__ )
)
{
return;
}
if ( isset ( $_POST['_t5_extra_box'] ) )
update_post_meta( $post_id, '_t5_extra_box', $_POST['_t5_extra_box'] );
else
delete_post_meta( $post_id, '_t5_extra_box' );
}
I am seeing "Success" in the console, so I know that the jQuery is getting called correctly. I can't figure out how to get the do_shortcode('[extra]') to fire however. Any help is greatly appreciated.
Your ajax call does not have coxtent of the global $post from the page the ajax request is coming from and thus get_the_ID() should be false and get_post_meta( get_the_ID(), '_t5_extra_box', TRUE ) will also be false. Furthermore, you're calling do_shortcode('[extra]') (no content) so $content inside your callback will be an empty string. So return wpautop(get_post_meta( get_the_ID(), '_t5_extra_box', TRUE).$content); becomes return wpautop(''); which is just an empty string. Based on your code I would expect your data response to always be an empty string.
To fix this I would add an extra ajax post data item along with the action that tells the callback what $post_id should be. That's the most primitive way. You may want to add a nonce or some other measure for security (but that may not be relevant for your original question).
UPDATE
I haven't tested this, and you may want to do it differently, but here is one option. Ultimately you just need a way to get the $post_id from the original request and pass it along to the ajax call. Since you're already passing the ajax url via wp_localize_script, I would just add another JavaScript variable there.
jQuery
jQuery(document).ready(function ($) {
$('#extra').on('click', function () {
$.ajax({
type: "POST",
url: my_ajaxurl,
data: {
action: 'process_shortcode_on_click_action',
post_id: my_postid,
},
success: function (data) {
console.log("Success");
},
error: function (errorThrown) {
console.log("Error");
}
});
})
})
functions.php
add_action('wp_enqueue_scripts', 'add_my_script');
function add_my_script () {
wp_enqueue_script(
'extra-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
wp_localize_script('extra-script', 'my_ajaxurl', admin_url('admin-ajax.php'));
wp_localize_script('extra-script', 'my_postid', get_the_ID());
}
add_action('wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
add_action('wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
function process_shortcode_on_click_ajax ()
{
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if (empty($post_id = $_POST['post_id']) || !is_numeric($post_id)) {
wp_die('Post ID is Invalid', 400);
}
echo do_shortcode("[extra post_id='{$post_id}']");
wp_die();
}
add_shortcode('extra', 't5_extra_content');
function t5_extra_content ($attributes, $content = '')
{
$defaults = [
'post_id' => get_the_ID(),
'cap' => 'edit_posts'
];
$args = shortcode_atts($defaults, $attributes);
if (!current_user_can($args['cap']) || empty($args['post_id'])) {
return ''; // or some message on fail
}
return wpautop(get_post_meta($args['post_id'], '_t5_extra_box', TRUE) . $content);
}
I have used Wordpress Admin Ajax and the console shows that 400 (Bad Request)
jQuery('#submitid').click(function(e){
e.preventDefault();
//var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: {status: 'status', name: 'name'},
success:function(data){
jQuery("#result").html(data);
}
});
});
The Wordpress AJAX process has some basic points that should be followed if you want it to work correctly:
1.In functions.php add the action you'd like to call from the frontend:
function logged_in_action_name() {
// your action if user is logged in
}
function not_logged_in_action_name() {
// your action if user is NOT logged in
}
add_action( 'wp_ajax_logged_in_action_name', 'logged_in_action_name' );
add_action( 'wp_ajax_nopriv_not_logged_in_action_name', 'not_logged_in_action_name' );
2.Register the localization object in functions.php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$some_object = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( 'some_handle', 'ajax_object', $some_object );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
3.Create the AJAX request on the frontend
// source: https://codex.wordpress.org/AJAX_in_Plugins
var data = {
'action': 'not_logged_in_action_name',
'whatever': 1234
};
jQuery.post( ajax_object.ajax_url, data, function( response ) {
console.log( response );
}
All Wordpress Ajax call must have action param which points to hook wp_ajax_{action_param} or wp_ajax_nopriv_{action_param} and from there you jump to function from that hooks.
From Codex:
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
$status = $_POST['status'];
}
first you shouldn't write the url by yourself. You could use the localize function to add the url to your javascript file:
wp_enqueue_script('myHandle','pathToJS');
wp_localize_script(
'myHandle',
'ajax_obj',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
After this you can use ajax_obj.ajax_url within your script to receive the url.
Second, did you implement the correct hook?
// Only accessible by logged in users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// Accessible by all visitors
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
Best Regards
This question already has answers here:
Wordpress admin-ajax.php 400 bad request
(8 answers)
Closed 4 years ago.
I'm working on a search plugin for the front-end of a Wordpress site. At the moment I keep getting a 400 Bad Request Error and I can't understand why. I've reviewed many questions on SO and the WordpressStackExchange but cannot see where I'm going wrong, nothing appears to be out of place. Please give me guidance:
plugin.php:
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_register_script('veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', '', '', true);
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_the_ajax_hook', 'handle_request' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
One would expect to see "Hello" in the console but I only see the error in the console:
jquery.js?ver=1.12.4:4 POST http://localhost/wp-admin/admin-ajax.php 400 (Bad Request)
Please replace code and check
plugin.php
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
Use JSON instead:
function handle_request(){
echo json_encode( array( "message" => "hello" ) );
exit;
}
Parse the JSON in your ajax.js response handler:
function( response ) {
var returndata = JSON.parse( response );
console.log( returndata.message );
}
Don't forget to add json2 as a dependency to your script.
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery', 'json2' ) );
I am building a Wordpress plugin that has standalone PHP that is run via AJAX. As such I am using
define( 'SHORTINIT', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
at the top of the PHP file so that Wordpress functions are available throughout my class and its member functions. However, the Wordpress functions are not available in the member functions.
This is a simplified version of my class but I am getting the error :
Uncaught Error: Call to undefined function wp_insert_post()
define( 'SHORTINIT', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
class fpe_events {
public function add_post_and_meta( $post_data ) {
if( $post_data["ID"] ) {
// Post exists, update it
wp_update_post( $post_data );
} else {
wp_insert_post( $post_data );
}
}
}
You should do your PHP-Code in WordPress Plugin files.
Here is an example:
Add your JS-File to Plugin Main PHP:
wp_enqueue_script( 'your-script', plugins_url( '/js-file.js', __FILE__ ),
array('jquery'), '1.0', true );
wp_localize_script( 'your-script', 'your_awesome_name', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
Ajax-Call:
jQuery( document ).on( 'click', '.simple-button', function() {
var post_id = jQuery(this).data('id');
jQuery.ajax({
url : your_awesome_name.ajax_url,
type : 'post',
data : {
action : 'my_php_script',
post_id : post_id
},
success : function( response ) {
alert(response)
}
});
})
And run on your Plugin php file this:
add_action( 'wp_ajax_my_action', 'my_php_script' );
function my_php_script() {
//your php script
wp_die();
}
Or read the codex: https://codex.wordpress.org/AJAX_in_Plugins