I am trying to learn how to process AJAX requests in Wordpress the correct way. To do this I am adapting this tutorial to create a super simple AJAX request to place the ID of a post (from a link) into my page content.
The Logic
When the #our-work a links are clicked [js]
Get the post ID (from the data-id attribute) & store it as postID variable [js]
Pass postID via an AJAX (using the WP's admin-ajax.php file) [js]
The example_ajax_request function will pick up the ID & simply echo it [php]
If successful, append the server response to the #hero div.
I realise this has no benefit but once I have that working I will amend the function to serve a real purpose.
My Code
Here is a copy of the function I have created in the plugins folder:
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'acl-plugin.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
function example_ajax_request() {
if ( isset($_REQUEST) ) {
$postID = $_REQUEST['postID'];
echo $postID;
}
die();
}
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
And here is a copy of the JS file
jQuery(document).ready(function($) {
$('#our-work a').click( function() {
var postID = $(this).attr("data-id");
$.ajax({
url: MyAjax.ajaxurl,
data: {
'action':'example_ajax_request',
'postID' : postID
},
success:function(data) {
$('#hero').append( "Well this seems to work" + data );
},
error: function(errorThrown){
console.log("This has thrown an error:" + errorThrown);
}
});
return false;
});
});
The Problem
Upon clicking the link the JS does fire but yields the following response:
<div id="hero">
Well this seems to work 0
</div>
Using an alert I know the ID is being picked up before the AJAX request. So the problem is in my function. To find out more, I (temporarily) tweaked WP's admin-ajax.php file, so that I could find out which die(); was yielding the response of "0".
It is the very last one in the file which I thought wouldn't fire as I have a die(); command in my own function. Can someone please point out where I am going wrong?
This is one of those rare times I can proudly say... there isn't any problem here!
The reason the server is returning with 0 is because I was logged in! The wp_ajax_nopriv_example_ajax_request is only for users who are not logged in. After logging out this works fine.
So if you are looking to do the same thing, just make sure you have both actions below the function:
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Related
The below code produces an error:
Notice: wp_enqueue_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the waitlist_update_call handle. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/food/domains/xyz.com/public_html/wp-includes/functions.php on line 5225"
It also shows an error in the console of:
POST https://theste.com/wp-admin/admin-ajax.php 400 (Bad Request)
PHP code in my functions file
wp_enqueue_script( 'update_call',
get_theme_file_uri( '/assets/js/update_call.js' ),
array('jquery'), null, true );
wp_localize_script('update_call', 'my_ajax',
array('ajax_url' => admin_url('admin-ajax.php')));
//calls Waitinglist data and creates table
add_action('wp_ajax_function_1', 'update_function'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'update'); // non logged in user can make a call
function update_function() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` =
'myupdate1' WHERE ID = '1'"));
die($results);
}
EDIT 1:
I was trying to call it directly. Please excuse my newness.Ok the fist below solved Enqueue issue but POST 400 error remains. The error is
POST https://x.com/wp-admin/admin-ajax.php 400 (Bad Request)
When clicking my button that is supposed to trigger I get -
Uncaught ReferenceError: update_functionis not defined
at HTMLButtonElement.onclick
I have changed my PHP in the functions file to:
function my_scripts() {
wp_enqueue_script( 'update_call', get_theme_file_uri( '/assets/js/update_call.js' ), array('jquery'), null, true );
wp_localize_script('update_call', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
//calls Waitinglist data and creates table
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action('wp_ajax_function_1', 'waitlist_update'); // logged in user can make a call
function waitlist_update() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'wp_wpdatatable_4' SET `currentstatus` =
'myupdate1' WHERE wdt_ID = '1'"));
die($results);
}
Seperate JS file is :
// JavaScript Document
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
action: 'waitlist_update',
success: function(data){
// callback function
}
});
and HTML is:
<button class="seat-btn" ID="update" onclick="update_function()">Go!</button>
WordPress provides hooks to enqueue scripts properly.
You might have called the enqueue method directly. It should be in action callback of wp_enqueue_scripts hook.
function my_scripts() {
wp_enqueue_script('update-call', get_template_directory_uri() . '/assets/js/update_call.js', array('jquery'), false, true);
wp_localize_script('update-call', 'my_ajax', array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'my_scripts');
Also,
//calls Waitinglist data and creates table
add_action('wp_ajax_function_1', 'update_function'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'update_function'); // non logged in user can make a call
If you check my previous answer in old question. The function_1 is an action requested from AJAX call and update_function is the function name that we should call when the action is triggered. Users who are not logged in upon triggering the action will call to the function update according to your code above which is incorrect.
If you only want to allow the logged in users to make this request, you can remove the second action attached for non logged in users.
add_action('wp_ajax_nopriv_function_1', 'update_function'); // notice the nopriv?
Note:
The ajax action name should match the action hook.
jQuery.ajax({
//...
data: {
action: 'action_name'
}
});
// The action name should be same wp_ajax_{action_name} from whatever defined in jQuery action
add_action('wp_ajax_action_name', 'update_function')
I am creating a button to send an email to the logged-in user's branch.
Just to begin coding this, I need to send an AJAX call successfully, triggering the 'success' method of the AJAX object.
I have read that the proper way is as below, using a wp_localize() function to make the admin-ajax.php file URL available in my Javascript.But it is not working.
I have tested that the enquiry() function is getting called successfully, so the script is properly enqueued.
This is my PHP plugin code:
add_action('woocommerce_after_add_to_cart_button','ajax_register_script');
function ajax_register_script()
{
wp_register_script('mailer-script', plugins_url('/ajax-script.js', __FILE__),
array('jquery'), '1.0', true);
wp_enqueue_script('mailer-script', plugins_url('/ajax-script.js', __FILE__),
array('jquery'), '1.0', true);
wp_localize_script( 'mailer-script', 'mailer_ajax',
array( 'ajax_url' => admin_url('admin-ajax.php')) );
}
add_action('woocommerce_after_add_to_cart_button', 'button_function', 45);
function button_function()
{
echo "<div class='unique' id='mail-button' onclick='enquiry()'>
Not sure of your prescription? Click to be contacted</div>";
}
and this is my JS:
function enquiry() {
$.ajax({
url: mailer_ajax.ajax_url,
type: 'post',
data: {
action: 'go',
},
success: function () {
document.getElementById('mail-button').innerHTML = "Thankyou for your enquiry, an email has been sent to your branch. You will be contacted shortly";
},
})
};
Thanks very much for any insight.
After lots of neatening up and refactoring my code is working.
I wish i knew exactly what the problem was, as in principle the above seems to be correct.
A great help was rams0610's answer on this question.
Using AJAX in a WordPress plugin
I've pored over other threads' WordPress AJAX questions with 400 errors, but I just can't seem to get this right.
I am in WordPress trying to implement some AJAX. Right now I have dummy functions in place just to learn about the AJAX functionality, but I can't get them to work.
On my page template, I have this Javascript at the bottom of the page:
<script>
var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data = { action : 'bp_check_user_role' };
jQuery.post(ajax_url, data, function (success) { console.log(success); });
</script>
In my Code Snippets plugin, I have this PHP:
function bp_check_user_role() {
echo "Hi!";
die();
}
add_action('wp_ajax_bp_check_user_role', 'bp_check_user_role');
add_action('wp_ajax_nopriv_bp_check_user_role', 'bp_check_user_role');
I feel like I'm doing these two steps properly, but when I load the page the code doesn't work and I get this (I've scrubbed {mysite}, but it is correct):
jquery.js?ver=1.12.4:4 POST https://{mysite}.com/wp-admin/admin-ajax.php 400 ()
Any ideas or obvious mistakes I am making? I just can't seem to crack this one :(
Threads I've read in addition to referring to the WordPress Codex:
https://wordpress.stackexchange.com/questions/220661/use-ajax-without-a-plugin
Wordpress Ajax always returns 0
As I've pointed in my comment:
Visit
https://{mysite}.com/wp-admin/admin-ajax.php?action=bp_check_user_role
and see if you see the "Hi!" text.
Why visit that URL?
To verify that your AJAX 'action' is registered (properly) and that the AJAX response is also as you expected.
Additional Note
If you look at the code in wp-admin/admin-ajax.php, you'd see these:
if ( is_user_logged_in() ) {
// If no action is registered, return a Bad Request response.
if ( ! has_action( 'wp_ajax_' . $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
...
do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
// If no action is registered, return a Bad Request response.
if ( ! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
...
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
So as you can see, it says // If no action is registered, return a Bad Request response., and therefore, if your AJAX JavaScript callback receives a 400 Bad Request error/response, then your AJAX 'action' is likely not registered, or that the PHP callback for the 'action' did not get called because the 'action' was registered after the do_action() call.
That may not always be the case; however, it can be a very good "first-aid" in troubleshooting AJAX issues.
I'm trying to figure out how Ajax and Wordpress plugins work, but it seems to be pretty badly documented. Ideally what I want is:
The plugin gets it own Ajax url to use, this is defined globally.
The plugin can handle Ajax requests
I understand that there are two actions that are used for this. One for logged in users and one for users without an account or privileges. However, I just want to create an Ajax endpoint for a form.
I'm not looking for code snippets, just need to be pointed in the write direction as to Wordpress Plugins and Ajax handling.
I implemented below own AJAX functionality in functions.php, Just try this in plugin,
functions.php :
function prefix_ajax_delete_search() {
global $wpdb;
$user_id = get_current_user_id();
$wpdb->delete('sf_save_search', array('id' => $_POST['tid']) );
wp_die();
}
add_action( 'wp_ajax_delete_search', 'prefix_ajax_delete_search' );
Script.js:
function deleteSearch( tid) {
var url = window.location.href;
jQuery.post(
ajaxurl,
{
'action': 'delete_search',
'tid': tid,
},
function(response){
location.reload();
}
);
}
I'm using ajax to collect data from enquiry form, then data is send to another page, and this page supposed to send this data to my email.
The problem is when I click send button, I'm getting 404 error in firebug console.
In template (with ajax code) I use this call:
$.ajax({
type: "POST",
url: "<?php echo get_permalink(11); ?>",
data: {
name: $('.enquiryName').val(),
email: $('.enquiryEmail').val(),
comments: $('.enquiryComments').val()
}
}).done(function(msg) {
if (msg=='1') {
alert('<strong>Your enquiry has been sent successfully.</strong>');
$('.enquiryName').val('');
$('.enquiryEmail').val('');
$('.enquiryComments').val('');
} else {
$('.errorBox').html(msg);
}
});
Target page is just another page created in wordpress, with very basic template. When I put to browser url bar this page address and press enter I get message Nothing to send., which is correct.
What might be wrong? In ajax I get 404 error, in browser it's fine.
You need to use a relative URL in an Ajax call... replace <?php echo get_permalink(11); ?> with the actual relative URL and see if it works..
Replace
url: "<?php echo get_permalink(11); ?>",
with
url: '<?php echo admin_url('admin-ajax.php'); ?>'
also you must pass an 'action' param in your data which can then be attached to callback function
must see this :
http://codex.wordpress.org/AJAX_in_Plugins
You will need to get an instance of the Ajax URL in frontend.
To do that you need to enqueue your script and use the WP function wp_localize_script
so in your functions.php
function enqueue_AjaxURL() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/jmy-Yourscript.js', array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_AjaxURL' );
and in your JS file you can use the object:
url: ajax_object.ajax_url,