I am new to wordpress and I need to call a php function from ajax but my code is not working. I was reading about the ajax standard in wordpress, but I don't know what happens, I have followed several tutorials and answers in this blog and they all talk about the action to enqueue the javascript file, but the problem continues and I don't know what I'm doing wrong. To continue I share my code.
This is my function to enqueue my javascript file:
function enqueue_script() {
$ajax_script = 'popup';
$uri = get_stylesheet_directory_uri() . '/assets/front/js/popup.js';
wp_register_script($ajax_script, $uri);
wp_localize_script( $ajax_script, 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( $ajax_script, $uri, array('jquery'), rand(111,9999), 'all');
}
add_action( 'wp_enqueue_scripts', 'enqueue_script' );
My php function to call, this is in an update_request_status.php file:
function update_status(){
echo "<script>alert('I am update function!!!!');</script>";
}
This is my js action, :
$('.btn-confirm').click(function(){
var url_string = window.location.href;
var url = new URL(url_string);
var request_id = url.searchParams.get("request_id");
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
cache: false,
data: { "request_id": request_id } + '&action=change_status',
success:function(data){
alert("YEs I doing");
},
error:function(){
alert("¡Error en el servidor, contancte al administrador!");
}
});
window.location.href = "http://localhost:8081/megafrescos/pendientes";
$('#msg-remove-request').css('display', 'none');
});
And finally, this is my modal with the button that triggers the action to call my php function:
<div class="warning-msg" id="msg-remove-request">
<button class="btn-close" id="btn-close">×</button>
<h5>¿Dar por concluida esta solicitud ? </h5><hr>
<?php echo fix_request()?>
<div class="confirm-btns">
<button class="btn-confirm">Aceptar</button>
<button class="btn-close">Cancelar</button>
</div>
<div class='update-status'></div>
</div>
Can somebody help me?
There are multiple ways to do it. First I'll show the one you were working on.
You'll need to define two actions with wp_ajax_{action} and wp_ajax_nopriv_{action}, where {action} is a placeholder for a keyword to identify the function that needs to be called. The former is only works when users are logged in. The latter is for request from unauthenticated users.
Both hooks should refer to the same function that you are trying to call.
The example below returns either the request_id that has been sent or a string with 'Nothing' as a response, just to test things out.
add_action( 'wp_ajax_nopriv_update_status', 'update_status' ) ;
add_action( 'wp_ajax_update_status', 'update_status' );
function update_status() {
$request_id = isset( $_POST[ 'request_id' ) ) ?
$_POST[ 'request_id' ) :
'Nothing';
echo $request_id;
}
The other, and more modern approach is using the REST API. This enables you to create an endpoint where you get more controls over de URL and sanitizing.
Your endpoint would look something like this
https://yourwebsite.com/wp-json/api/v1/update. You can get the static URL to the REST endpoint by using get_rest_url(), like you did with admin_url( 'admin-ajax.php' ) and should add that to your wp_localize_script function in the enqueue file.
The endpoint checks the methods allowed and calls the callback specified in the options array. From there you can access the $request object which contains info like the given arguments from your request.
Then return a response to read on the frontend.
add_action( 'rest_api_init', 'register_update_endpoint' );
function register_update_endpoint() {
// Register new route to get data from
register_rest_route( 'api/v1', // Mandatory prefix with version
'/update/', // Name of the route, can be anything.
array(
'methods' => array( 'POST' ), // Allowed methods.
'callback' => 'update_status' // Function to call when URL is called.
)
);
function update_status( WP_REST_Request $request ) {
$request_id = $request->has_param( 'request_id' ) ?
$request->get_param( 'request_id' ) :
'Nothing';
$response = new WP_REST_Response( $request_id; );
return $request_id;
}
}
Related
In a template file, I need to get the new data from the frontend when a user double-clicks and changes the record on a table. I tested and the console shows that the request is correct, however whatever I tried the admin-Ajax returns always Bad Request!
The PHP code waiting for the request in the template file is:
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_please_login", "please_login" );
function update_records(){
global $wpdb;
$colName = "'" . $_POST['upd_column'] . "'";
$wpdb->update('Reservations',
array(
$colName => $_POST['upd_value']
),
array( 'ReservationID' => $_POST['record_id'] )
);
wp_die();
};
function please_login() {
echo "You must log in to work";
die();
}
The jQuery code sending the request is:
jQuery('#work td').dblclick(
function dolly_script() {
var text = jQuery(this).text();
var headerName = jQuery(this).attr('headers');
jQuery(this).text('');
jQuery('<input />').appendTo(jQuery(this)).val(text).select().blur(
function() {
var newVal = jQuery(this).val();
var selectionID = jQuery(this).closest("tr").children("td[headers='ReservationID']").text();
jQuery(this).parent().text(newVal).find('input').remove();
jQuery.ajax({
url: '../wp-admin/admin-ajax.php',
type: 'POST',
dataType : "json",
data: JSON.stringify({
action: 'update_records',
record_id: selectionID,
upd_column: headerName,
upd_value: newVal
})
})
})
});
I tried also without JSON.stringify and without datatype.
In functions file I have also added:
wp_register_script( 'dolly_script', '/wp-content/themes/bootcms/work.js');
$myAjax = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'dolly_script', 'ajax_url', $myAjax );
wp_enqueue_script( 'dolly_script' );
Inside the "add_action( 'wp_enqueue_scripts', 'myfunction' );" declaration.
If anyone could help is hugely appreciated, I spent a whole day but I found no solution.
I solved the problem. Here is the solution in case it helps others:
I moved the PHP function into the functions.php file.
I'm trying to make some SQL queries using PHP in Wordpress, to auto populate and check values on a gravity form against the existing database.
To do that however, I'm going to need to pass some javascript variables to php, then use that to interact and pull that data back to the form. As someone with minimal web dev background, easier said then done.
My main issue is with an AJAX call that properly carries over a value, but only to the action function. All other calls will show null (I assume due to scoping, but globals don't seem to help).
The main relevant PHP is in a custom plugin as follows:
$address = 0;
function my_enqueue() {
wp_register_script( 'lead-scheduler', null);
wp_enqueue_script( 'lead-scheduler', plugins_url( '/lead_ajax.js', __FILE__ ), array('jquery') );
wp_localize_script( 'lead-scheduler', 'leadajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'jquery' );
wp_register_script( 'lead_ajax', null);
wp_enqueue_script( 'lead_ajax' );
}
add_action( 'init', 'my_enqueue' );
function handle_request(){
//Check post address, then apply to global variable
echo $_POST['address'] . "\n";
global $address;
$address = $_POST['address'];
echo $address . "\n";
wp_die("RIP");
}
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
function functionCaller() {
if (is_page ('')) {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function(){
var addressField = document.getElementById('input_22_2');
var temp;
//Set up event listener
addressField.onchange = addressCheck;
function addressCheck(){
//Get foreign script
$.getScript("/wp-content/plugins/lead-scheduler/lead_ajax.js", function(){
//Wait until done to execute console.log
$.when(adrCheck()).done(function(){
console.log("Logging: " + "<?php global $address; echo $address ?>");
});
});
}
});
});
</script>
<?php
}
}
add_action('wp_head', 'functionCaller'); ?>
The AJAX call comes from a JS file that I call to:
//AJAX
function adrCheck(){
jQuery(document).ready( function() {
console.log("called")
var addressField = document.getElementById('input_22_2').value;
jQuery.ajax({
type : "post",
url : leadajax.ajax_url,
data : {action: "handle_request", address: addressField},
success: function(response) {
console.log(response)
},error: function(response){
console.log(response);
}
})
})
}
The call seems to work, as the echo in handle_request() works fine. But calling that variable anywhere else returns null. $.when.done doesn't seem to do much, nor does anything synchronous.
I'm sure there's something super elementary that I'm missing, but I can't seem to find it.
-- Edit 1 --
Found out some new things. I'm adding them on top since they might be more relevant than the code below.
I've rerun the scripts a few times. I now get different findings actually.
Running var_dump($wp_query->query); right after $the_query = new WP_Query($queryArgs);In the first render of the post loop gives me the query vars of the page the loop is rendered on. Calling it with ajax it reruns the same part of the code, right? So than it returns empty.
My thoughts:
Pages is called, runs funtions.php.
Runs the part of the wp_enqueue_script('rtt_scripts');
This is the moment it gets the current $wp_query values. Which are the values of the page.
Than renders the page with the post loop.
This is the moment the post loop runs $the_query = new WP_Query($queryArgs);
On press of the load more the ajax than calls it to rerun the post loop. With the query vars set with wp_enqueue_script('rtt_scripts');
This made me think. Am I running the code in a wrong order? Are the query vars for ajax set on the wrong moment? Other thought. Should I focus on how to get the query vars on the first post loop to the ajax query vars?
-- End Edit --
I’m having trouble with a load more button in Wordpress. The code below is the basic code I have right now.
As far as I can see this should be a working code :) Problem is though that this doesn’t work.
My problem is that I don’t know where to start debugging. Closest I know where the problem lies is this:
In rtt_loadmore_ajax_handler() there is the var $queryArg
When var_dumping the var $queryArg in both rtt_post_grid() and rtt_loadmore_ajax_handler()
It gives different results. Here I would expect the same results. In the Ajax call it returns the arguments
of the current rendered page and not of the post query on this page.
Would the global $wp_query; be the problem? And how do I go from here?
The basic post code:
function rtt_post_grid()
{
$queryArgs = Array(
"post_type" => Array(
'news',
'agenda'
),
'posts_per_page' => 4,
'post_status' => 'publish',
'paged' => 1
);
// post grid wrap
echo '<div id="rtt_posts_wrap" >';
rtt_post_grid_query($queryArgs);
echo '</div>';
// load more button
echo '<form>';
echo '<button id="rtt_loadmore" class=" button">Load more post</button> ';
echo '<input type="hidden" name="action" value="loadmore" />'; // this line might be obsolete
echo '</form>';
}
function rtt_post_grid_query($queryArgs)
{
// The Query
$the_query = new WP_Query($queryArgs);
// The Loop
if ($the_query->have_posts()) {
echo '<ul>';
while ($the_query->have_posts()) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
echo 'no posts found';
}
}
Setting the JS:
if(!has_action('rtt_post_grid_script_and_styles')) {
add_action('wp_enqueue_scripts', 'rtt_post_grid_script_and_styles', 1);
function rtt_post_grid_script_and_styles()
{
global $wp_query;
wp_register_script('rtt_scripts', plugin_dir_url( __FILE__ ) . 'js/script.js', array('jquery'), time());
wp_enqueue_script('rtt_scripts');
wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode($wp_query->query_vars), // everything about your loop is here
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
));
wp_enqueue_script('rtt_scripts');
}
}
The JS/Ajax:
jQuery(function($){
$(window).ready(function() {
$('#rtt_loadmore').click(function () {
$.ajax({
url: rtt_loadmore_params.ajaxurl,
data: {
'action': 'loadmore', // the parameter for admin-ajax.php
'query': rtt_loadmore_params.posts, // loop parameters passed by wp_localize_script()
'page': rtt_loadmore_params.current_page, // current page
},
dataType: 'json',
type: 'POST',
beforeSend: function (xhr) {
$('#rtt_loadmore').text('Bezig met laden...'); // some type of preloader
},
success: function (data) {
if (data) {
$('#rtt_loadmore').text('More posts');
$('#rtt_posts_wrap').append(data.content); // insert new posts
rtt_loadmore_params.current_page++;
if (rtt_loadmore_params.current_page == rtt_loadmore_params.max_page){
$('#rtt_loadmore').hide(); // if last page, HIDE the button
}
} else {
$('#rtt_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
});
});
The Ajax handler:
add_action('wp_ajax_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
function rtt_loadmore_ajax_handler(){
$postData = $_POST;
// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';
ob_start();
rtt_post_grid_query($queryArgs);
$output = ob_get_contents();
ob_end_clean();
global $the_query;
echo json_encode( array(
'posts' => serialize( $the_query->query_vars ),
'max_page' => $the_query->max_num_pages,
'found_posts' => $the_query->found_posts,
'content' => $output
) );
die;
}
So, I've figured it out. I'll explain for it might be useful to somebody else.
The reason it did not work is because the code above is more useful in a template. But I use it in a shortcode. The wp_localize_script() was run on rendering the page and not on running the shortcode. That's why it didn't had the right variables.
I've moved the code below inside the shortcode. Right after the new WP_query:
// The Query
$the_query = new WP_Query($queryArgs);
// The Loop
if ($the_query->have_posts()) {
wp_enqueue_script_ajax_vars($the_query);
Than passed the new query
function wp_enqueue_script_ajax_vars($the_query)
{
wp_register_script('rtt_scripts', plugin_dir_url(__FILE__) . 'js/script.js', array('jquery'), time());
wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode($the_query->query_vars), // everything about your loop is here
'query_vars' => json_encode($the_query->query),
'current_page' => $the_query->query_vars['paged'] ? $the_query->query_vars['paged'] : 1,
'max_page' => $the_query->max_num_pages,
));
wp_enqueue_script('rtt_scripts', '', '', '', true); // note the last 'true' this sets it inside the footer
}
Resulting in wp_localize_script() creating the variable in the footer. It was in the header before. But by getting it within the shortcode, sending the new query arguments and putting them inside the footer (since the header is already rendered by then) I have set the JS var for Ajax.
Add the two order arguments to $queryArgs.
// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';
$queryArgs['orderby'] = 'date'; // add this to order by date
$queryArgs['order'] = 'DESC'; // add this to display the most recent
My ajax call output is always showing 0 as output don't know why
In functions.php I have this code
function get_data() {
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And my ajax call is in a javascript
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "GET",
dataType : "json",
url : "/wp-admin/admin-ajax.php",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.
In backend there is global ajaxurl variable defined by WordPress itself.
This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.
Good way to do this is to use wp_localize_script.
Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
After localizing your JS file, you can use my_ajax_object object in your JS file:
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: formData,
success: function(msg){
console.log(msg);
}
});
Actually, WordPress comes with a handy function to access admin-ajax.
Requirements
In wp-admin you do not need to do anything, the js library is always loaded
In the front-end you need to enqueue the script wp-util, like this:
add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
function my_enqueue_function() {
// Option 1: Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
// Option 2: Make wp-util a dependency of your script (usually better).
wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
}
The JS Library
The wp-util script contains the wp.ajax object that you can use to make ajax requests:
wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )
Your example:
wp.ajax.post( "get_data", {} )
.done(function(response) {
alert("Your vote could not be added");
alert(response);
});
PHP code
Of course, you still need to create the wp_ajax_* hooks in your PHP script.
add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );
function my_ajax_handler() {
wp_send_json_success( 'It works' );
}
Tip:
For Ajax responses WordPress provides two functions:
wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (i.e., they exit;)
I had the same problem. I was new to WordPress. Therefore, I am explaining here so that every new learner can understand how ajax is calling in WordPress.
First, create a function in function.php file that resides under wp-content/theme/selected_theme folder. Here, selected_theme maybe your theme name.
In the above question, a function is created with the name get_data();
function get_data() {
echo "test";
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
in the above two lines,
The add_action method is used to implement the hook. Here, I am passing the two parameters, first is wp_ajax_nopriv_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
In the second add_action, I am passing the two parameters, first is wp_ajax_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
Here, wp_ajax_nopriv call if the user is not logged in and wp_ajax called when the user is logged in.
jQuery.ajax({
type: "post",
dataType: "json",
url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
data: {
action:'get_data', //this value is first parameter of add_action
id: 4
},
success: function(msg){
console.log(msg);
}
});
Add admin-ajax.php by using admin_url('admin-ajax.php');
<script type="text/javascript">
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "POST",
dataType : "json",
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
</script>
<form type="post" action="" id="newCustomerForm">
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email">Email:</label>
<input name="email" type="text" />
<label for="phone">Phone:</label>
<input name="phone" type="text" />
<label for="address">Address:</label>
<input name="address" type="text" />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>
functions.php
wp_enqueue_script('jquery');
function addCustomer() {
global $wpdb;
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if ( $wpdb->insert( 'customers', array(
'name' => $name,
'email' => $email,
'address' => $address,
'phone' => $phone
) ) === false ) {
echo 'Error';
} else {
echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
javascript
<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success: function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
If you are getting 0 in the response, it means your ajax call is working correctly.
But, you have not defined $wpdb as a global variable in your function get_data.
Check your error log, you must be seeing error there.
Try:
function get_data() {
global $wpdb;
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
Step 1: Add ajax 'wp_enqueue_script' file in function file where you have to add other 'wp_enqueue_script' or 'wp_enqueue_style' files
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax- script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
Step 2:Now you need to create function, where you want to get response, using ajax
e.g below
add_action('wp_footer','add_ajaxex_in_footer');
function add_ajaxex_in_footer()
{ ?>
<script type="text/javascript">
jQuery('#sbmtbtn').click(function(){
jQuery.ajax({
type:"POST",
url:my_ajax_object.ajax_url,
data: {action:'my_special_ajax_call_enroll_cours'},
success:function(res){
console.log(res);
}
});
});</script><?php
}
Step 3: Now you have to create function where you have to write query,
add_action('wp_ajax_my_special_ajax_call_enroll_cours', 'enroll_cours');
add_action('wp_ajax_nopriv_my_special_ajax_call_enroll_cours', 'enroll_cours');
function enroll_cours()
{
echo "Here you van write Query or anything";
exit;
}
=> If you want to fire ajax request after onClick button, just pass the button ID
<input type="button" id="sbmtbtn" name="Save">
Here how to make in plain vanilla js the AJAX call in WordPress.
var urlToajax=jsajaxe_S.ajaxurl;
function P_lifg(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
document.getElementById("demo2").innerHTML = urlToajax+ "?action=testfirst";
}
};
xmlhttp.open("GET", urlToajax+ "?action=testfirst", true);
xmlhttp.send(0);
}
See on this blog, what to add functions.php and template html to get this work, also reasonings why there is no data in vanilja js unlike jQuery, but just action
Here add_actions in functions.php:
add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');
Add this function over that, here now this function:
function FunctionTF(){
exit( "Hola hola" );
}
See explanation why? code in "exit" in my blog
Here add this html on some wp-template
<div id="demo"></div>
<div id="demo2"></div>
<button id="spesial_button" onclick="P_lifg()">I am spesial</button>
See rest in: https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html
Can somebody help me? I'm feeling so stupid. I took example code from WordPress codex, made a example plugin in my webpage, but there no respond...
PHP code is here:
/**
* Plugin Name: Ada Ajax Test
* Description: WP Codex based ajax example
* Version: 1.0.0
* Author: M. A. Tomas
* Author URI: http://www.matomas.cz
* License: GPL2
*/
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_callback' );
function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
return $whatever;
wp_die();
}
// shortcode pro zobrazeni na strance
add_shortcode( 'ajax-zkouska', 'my_action_callback' );
and Javascript code in external file is here:
// JavaScript Document
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);
});
});
Where I mistake?
You have a few things mixed up.
Front End
If you are targeting the frontend, then you need to use this hook:
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
This allows you to add the needed scripts to the front end and not the admin side.
Ajax Calls
All ajax calls are executed within the admin context. So you will need to test for it and add the ajax hooks accordingly.
if ( is_admin() ) {
add_action( 'wp_ajax_my_frontend_action', 'my_frontend_action_callback' );
add_action( 'wp_ajax_nopriv_my_frontend_action', 'my_frontend_action_callback' );
add_action( 'wp_ajax_my_backend_action', 'my_backend_action_callback' );
// Add other back-end action hooks here
} else {
// Add non-Ajax front-end action hooks here
}
No Priv
The no_priv hook is meant for users that are not logged in. Add it if that's your intention.