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
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');
How can I show a simple form (similar to the search form) somewhere in the admin panel of Woocommerce (maybe as a separate menu entry) where I can just enter the order number and it sets that order (with that order number) to complete, without having to reload the page.
Why I need this: On my shipping labels there is a QR code containing the order number. When I scan that QR code it should set that order to complete (and thus notifying the customer that the order is now completed). As stated the form should work without having to reload the page after each scan, so that I can scan orders continuously.
Regarding form submission without page reload, you have to submit the value using AJAX. jQuery has $.ajax() and $.post() methods which you could use for this purpose.
Example (copied from Codex):
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);
});
});
When the data is submitted, you have to make use of the wp_ajax_(action) to process the request.
Example (copied from Codex) :
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
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' => 1234 ) );
}
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die();
}
You can get detailed explanation from the official documentation : https://codex.wordpress.org/AJAX_in_Plugins
And, you could do the order status updation of an order using the update_status() function. Example:
$order_id = ''; //-- received from AJAX request
$order = new WC_Order($order_id);
if (!empty($order)) {
$order->update_status( 'completed' );
}
So I've followed a very basic tutorial just to figure out the workings of AJAX calls within WordPress. Here are all the relevant bits of code:
In functions.php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() .'/js/my_query.js', 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' => 1234 ) );
}
In my_query.js
jQuery(document).ready(function($) {
console.log('myquery');
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 at the bottom of admin-ajax.php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die();
}
This covers all the points in the tutorial, but what I get when I load an admin page is this 400 error, whereas, I should be getting an alert, right?
Any ideas would be truly appreciated, I'm at my wit's end.
Thanks.
You seem to have added your custom code at the end of admin-ajax.php. That is not the correct way to do this. In general, you should never edit a core/admin WordPress file, because it will be overwritten when you update WordPress (among other reasons).
Even ignoring that, the reason why it's not working is that admin-ajax.php is only executed when actually requested, so your callback will be registered too late. You should add your add_action and the relative callback in your theme's functions.php or in a plugin, so that your actions will be registered at due time.
I try to use woocommerce Ajax, I find a lot example online, none of them works.
could someone take a look on my code, where's the problem.
add_action( 'wp_ajax_my_action', 'mmy_real' );
add_action( 'wp_ajax_nopriv_my_action', 'mmy_real' );
function mmy_real(){
check_ajax_referer( 'my-special-string', 'security' );
$make = $_SESSION['vpf']['search']['make'];
$model = $_SESSION['vpf']['search']['model'];
$year = $_SESSION['vpf']['search']['year_id'];
die();
}
function mmy_script(){
wp_register_script( "hover_script", get_template_directory_uri() . '/js/mmy.js', array('jquery'), '1.0.0', true );
wp_localize_script( 'hover_script', 'mmy', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'security' => wp_create_nonce( 'my-special-string' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'hover_script' );
}
add_action('init', 'mmy_script');
jQuery(document).ready(function() {
jQuery.ajax({
type: "post",
url : mmy.ajaxurl,
data:{
action:"mmy_real",
make: "make",
model: "model",
year: "year"
},
success: function( response ) {
alert("success");
}
});
});
I test in localhost. It won't alert success messagebox, if I change url to localhost/fhgroupauto/test.php . it will alert success .
I don't know what do i miss for this .
Thanks
The value of "action" is wrong.
You add the hook "wp_ajax_my_action" and "wp_ajax_nopriv_my_action", so the string after "wp_ajax_" and "wp_ajax_nopriv_" is the parameter for the "action" key.
Which means your data array for the ajax call should look like this:
data:{
action: "my_action",
make: "make",
model: "model",
year: "year"
},
For more information see the Wordpress documentation - AJAX in Plugins
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');.