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
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 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'm trying to create markers on a map via ajax on a wp theme.
After some struggle I found out that I can't use any php file to get data via ajax, I have to use the admin-ajax.php file.
Accordingly to many examples, this is my code
in functions.php
add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file' );
function add_frontend_ajax_javascript_file()
{
wp_localize_script( 'frontend_ajax', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'ajax_custom_script', get_stylesheet_directory_uri() . '/includes/ajax-javascript.js', array('jquery') );
}
add_action( 'wp_ajax_get_post_information', 'get_post_information' );
add_action( 'wp_ajax_nopriv_get_post_information', 'get_post_information' );
function get_post_information()
{
$get_this= $_GET['this'];
$get_that= $_GET['that'];
...my select...
echo json formatted data
}
The js file is loaded and working, it does other stuff before the ajax call, where it stops for an error in this line:
$.post({
url:frontendajax.ajaxurl,
{
action: 'get_post_information',
data: data
},
success: function(response) {
But I always Have the same error:
Reference Error: frontendajax.ajaxurl is not defined
where is my error?
PS: I use get_stylesheet_directory_uri() because I am in a child theme.
From wp_localize_script docs:
IMPORTANT! wp_localize_script() MUST be called after the script it's being attached to has been registered using wp_register_script() or wp_enqueue_script().
And the handle must be the same:
wp_enqueue_script( 'ajax_custom_script', get_stylesheet_directory_uri() . '/includes/ajax-javascript.js', array('jquery') );
wp_localize_script( 'ajax_custom_script', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
I'm trying to create markers on a map via ajax on a wp theme. After some struggle I found out that I can't use any php file to get data via ajax, I have to use the admin-ajax.php file.
admin_url( 'admin-ajax.php' )
));
});
?>
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 ) );
}