I’m new to WP and not overly familiar with AJAX either but I’m trying to get a very simple AJAX call to work, I think I’m nearly there but I can’t get any results to return back from the AJAX call, I’ve stripped everything down to the bare bones to get it working and am just returning the string ‘This is AJAX data results’ from the PHP Ajax function but even that does not appear to be working. At the moment I get my test alerts…
alert('jquery step 1'); - Works OK
alert('jquery step 2'); - Works OK
alert('ajax result: '.response); - ** NOT DISPLAYED **
alert('jquery step 3'); - Works OK
I've created a custom plugin and custom js and php files as follows...
********* c4l-custom-functions.php ********
<?php
/**
* Plugin Name: C4L Custom Functions Plugin
* Description: This plugin contains C4l custom functions, scripts and css styles.
* Author: C4L
* Version: 1.0
*/
function c4l_custom_script_and_style_includer() {
wp_enqueue_script( 'c4l-js', plugins_url( 'js/c4l-custom-scripts.js' , __FILE__ ) );
wp_enqueue_style( 'c4l-css', plugins_url( 'css/c4l-custom-styles.css' , __FILE__ ) );
}
add_action( 'wp_enqueue_scripts', 'c4l_custom_script_and_style_includer' );
add_action( 'wp_ajax_wps_get_time', 'wps_get_time' );
add_action( 'wp_ajax_nopriv_wps_get_time', 'wps_get_time' );
function wps_get_time() {
// $format = $_POST['format'];
echo('This is AJAX data results');
//echo date($format);
die();
}
?>
********* c4l-custom-scripts.js ********
document.addEventListener("DOMContentLoaded", function(event) {
jQuery('#pulldown1').change(function(){
alert('jquery step 1');
var timeformat = 'U';
alert('jquery step 2');
jQuery.ajax({
type: "POST",
url: "admin-ajax.php",
data: { action: 'wps_get_time', format: timeformat },
success: function ( response ) {
alert('ajax result: '.response);
}
});
alert('jquery step 3');
});
});
Try changing the ajax function url with this:
ajaxurl = '<?php echo(admin_url('admin-ajax.php')); ?>';
Related
in simple words: Ajax is called from Javascript file, but php function doesn't 'hear' the call.
In my case PHP and Javascript are in separate files. I proved that they are loaded correct in functions.php by:
function LoadScriptsOnSpecificPages(){
global $wp_query;
$page_id = intval($wp_query->queried_object->ID);
// Page ID 2614 = Buchung Auswahl Raum, Page ID 2654 = Buchung abschließen
if (($page_id = 2614) or ($page_id = 2654)) {
include get_stylesheet_directory() . '/custom/booking.php';
wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom/booking.js', array( 'jquery' ), 1.1, true);
}
}
add_action('template_redirect', 'LoadScriptsOnSpecificPages');
In "booking.php" at the top:
//Define AJAX URL and requests
function define_ajax_url() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'define_ajax_url');
// Action hooks that work with the WordPress AJAX functionality
// wp_ajax_nopriv_ action Hooks bewirken, dass der Ajax-Request auch bei Website-Besuchern läuft,
// die nicht eingeloggt sind.
add_action( 'wp_ajax_AjaxSessionIDerzeugen', 'AjaxSessionIDerzeugen' );
add_action( 'wp_ajax_nopriv_AjaxSessionIDerzeugen', 'AjaxSessionIDerzeugen' );
Problem: Also in the file "booking.php" the function that should be called, but unfortunately is never called:
// Ajax Session ID erzeugen
function AjaxSessionIDerzeugen() {
$ip_adresse = $_SERVER["REMOTE_ADDR"];
global $wpdb;
$wpdb->show_errors();
// $_REQUEST contains the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {
$session_id = substr(md5(time()), 0, 10);
$strsql = sprintf("INSERT INTO tbl_buchungen (session_id) VALUES session_id= '%s'",$session_id);
$wpdb->query($strsql);
// Callback
callback:
$arr = array();
$arr['pruefergebnis'] = "ok";
$arr['session_id'] = $session_id;
$antwort_json = json_encode($arr);
echo $antwort_json;
}
// Always die in functions echoing AJAX content
die();
}
In the file "booking.js" there is the Ajax-Call that doesn't work.
Error: Failed to load resource: the server responded with a status of 400 (Bad Request)
if ((session_id == '') || (session_id == null)) {
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'AjaxSessionIDerzeugen', // PHP function
},
// Callback
success:function(antwort) {
let object = JSON.parse(antwort);
pruefergebnis = object.pruefergebnis;
if (pruefergebnis == 'ok') {
session_id = object.session_id;
document.cookie = "session_id=" + session_id + "; expires=3600000; path=/";
} else {
window.alert(pruefergebnis);
}
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
}
I checked the network tab for the Ajax URL. It seems to be ok. Am I right?
The admin-ajax URL is available on admin side, for the front end you need to define it, I correct some small error and tested on my local it is working
$.ajax({
type: "POST",
url: ajaxurl, //you need to point to correct URL if you are working on frontend
data: {
action:'AjaxSessionIDerzeugen', // PHP function
},
// Callback
success:function(antwort) {
let object = JSON.parse(antwort);
pruefergebnis = object.pruefergebnis;
if (pruefergebnis == 'ok') {
session_id = object.session_id;
document.cookie = "session_id=" + session_id + "; expires=3600000; path=/";
} else {
window.alert(pruefergebnis);
}
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
The reason why it didn't work was, that - in functions.php of the theme - I restricted the loading of files booking.php and booking.js to the pages where I need it (by Page ID). This was a mistake.
My code in the functions.php that works now is:
include get_stylesheet_directory() . '/custom/booking.php';
function LoadScript() {
wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom/booking.js', array( 'jquery' ), 1.1, true);
}
add_action('template_redirect', 'LoadScript');
I'm trying to add jQuery to the javascript.js file for a child of woodmart theme, but I keep getting "javascript.js:131 Uncaught ReferenceError: jQuery is not defined".
javascript.js
(function($){
jQuery(document).ready(function($) {
//cart_actions parent container
//for POST requests when user saves a cart
clickparent = document.querySelector(".cart-actions");
clickparent.addEventListener("click", function(e) { // e = event object
let carts = JSON.parse(window.localStorage.getItem('yithPOS_carts'));
if (e.target && (e.target.className == "cart-action cart-action--suspend-and-save-cart cart-action--with-icon") || e.target.className == "cart-action__icon yith-pos-icon-saved-cart") {
// Use ajax to do something...
var postData = {
action: 'wpa_49691',
my_var: 'carts',
}
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
console.log("Cart saved to database.");
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
//pos_current_Cart_buttons parent container
//for GET requests when user views saved carts
viewcartparent = document.querySelector(".yith-pos-cart__buttons");
viewcartparent.addEventListener("click", function(e) { // e = event object
if (e.target && (e.target.className == "yith-pos-cart__buttons-saved-carts")) {
// Use ajax to do something...
var getData = {
action: 'wpa_49692',
my_var: 'my_data',
}
$.ajax({
type: "GET",
data: getData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
let total;
for(item in response){
total += item[lineTotal];
}
$(".yith-pos-cart__savedcarts").append('</div><i class="yith-pos-cart__savedcart"></i><div class="cart-saved__name"><div class="cart-saved__name__id">' + response['id'] + '</div><div class="cart-saved__name__customer">' + response['cartitems']['names'] + '</div></div><div class="cart-saved__num_of_items">' + response['cartitems'].size + '</div><div class="cart-saved__status">Pending Payment</div><div class="cart-saved__total">'+ total + '</div><button class="btn btn-primary"><i class="yith-pos-icon-refresh"></i> load</button></div>');
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
// Handler for .ready() called.
});
})(jQuery);
I've also tried enqueuing jquery with wp_enqueue_script and passing jquery in an array to the javascript file, neither changed anything.
functions.php:
wp_enqueue_script('jquery');
//First enqueue your javascript in WordPress
function save_cart_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'javascript.js', plugins_url('https://cigarchiefstg.wpengine.com/wp-content/themes/woodmart-child/yith-pos-additions/javascript.js', dirname(__FILE__) ), array( 'jQuery' ));
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'javascript', 'javascript_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'javascript_vars.ajaxurl' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'save_cart_enqueue_scripts' );
//This is your Ajax callback function
function cart_save_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
update_option('saved_carts', $my_var);
//Create the array we send back to javascript here
$return_array = array();
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $return_array );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49691', 'cart_save_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49691', 'cart_save_callback_function' );
function cart_view_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
//Create the array we send back to javascript here
$carts = get_option('saved_carts');
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $carts );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49692', 'cart_view_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49692', 'cart_view_callback_function' );
Edit: Issues with POS items:
first check if jquery is correctly loaded on you wp website.
I suggest using this syntax for jQuery:
(function($){
$(document).ready(function(){
//your code
})(jQuery);
Hi I am following a tutorial on Ajax calls in wordpress. The example has all the code in functions.php but I want to be more organised and include the javascript in a js file.
Here is what I have so far
functions.php
//The PHP
function example_ajax_request() {
// The $_REQUEST contains all the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// This bit is going to process our fruit variable into an Apple
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now let's return the result to the Javascript function (The Callback)
echo $fruit;
}
// Always die in functions echoing AJAX content
die();
}
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
and in the Javascript file test.js:
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
// This is the variable we are passing via AJAX
var fruit = 'Banana';
// This does the ajax request (The Call).
$( ".banana" ).click(function() {
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'fruit' : fruit // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$(".banana").text(data);
window.alert("here");
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
How can: 'action':'example_ajax_request', // This is our PHP function below
be accessed from the functions.php file?
I would like to pass a variable to a specific page. I found a simple example explaining how to use ajax with wordpress.
JavaScript:
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
Piece of PHP to insert in functions.php
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
Unfortunately I cannot pass the variable. I inspected the code and I get this error:
Error: ajax_object is not defined
Do you maybe know another way to obtain the same result?
You are very near, but there is some little things missing…
What I mean in my comment, is that you need to use it this way using 'ajax-script' in both:
add_action('wp_enqueue_scripts', 'add_js_scripts');
add_js_scripts(){
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
Changed $_REQUEST to $_POST:
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_POST) ) {
$fruit = $_POST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_POST
// print_r($_POST);
}
// Always die in functions echoing ajax content
die();
}
Added add_action( 'wp_ajax_nopriv_ … ):
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' ); // <= this one
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
For your jQuery script script.js file, there is 2 important missing little things:
jQuery(document).ready(function($) {
/* We'll pass this variable to the PHP function example_ajax_request */
var fruit = 'Banana';
/* This does the ajax request */
$.ajax({
url: ajax_object.ajaxurl, /* <====== missing here */
type : 'post', /* <========== and missing here */
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
/* This outputs the result of the ajax request */
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
This should work now…
References:
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?
You are using wp_localize_script wrong. In the PHP code, remove the wp_localize_script line.
Optionally you can (and should) add the following
// this line is for users who are not logged in
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Everything is correct except you have to add
ajax_object.ajax_url rather than ajaxurl in url: parameter of $.ajax function as
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: **ajax_object.ajax_url**,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
copy and paste above script in place of your $.ajax function
If you want to see what is ajax_object.ajax_url then
alert it inisde your code and it will alert path to your admin ajax file
which is required for using ajax in wordpress
It is a Wordpress installation using Gravity Forms which I know pretty well, however what I am trying to do is get the value of a hidden input and use it in a PHP script to get more data about.
JS CODE: http://pastebin.com/5FFf4ESb
jQuery(function($){
$(document).bind('gform_post_render', function(event, form_id){
if (form_id == 1) {
var uploader = $("#gform_drag_drop_area_1_1");
var uploads = $("#gform_uploaded_files_1").val();
alert(uploads);
uploader.on("drop", function() {
$.ajax({
url: mp3_object.ajaxurl,
async: true,
type: "POST",
data: {
action : 'ajax_mp3',
files : uploads,
},
success: function(response) {
//results = jQuery.parseJSON(response);
alert(response);
}
});
});
}
});
});
PHP CODE: http://pastebin.com/H2Cd1Dfd
function enqueue_mp3_scripts_init($form, $is_ajax) {
if ( $is_ajax ) {
wp_enqueue_script( 'mp3-script', plugin_dir_url(__FILE__) . 'js/scripts.js', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'mp3-script', 'mp3_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
}
}
add_action('gform_enqueue_scripts', 'enqueue_mp3_scripts_init', 10, 2);
function ajax_mp3_func() {
if( isset($_POST['files']) ) {
echo $_POST['files'];
}
die(); // stop executing script
}
add_action( 'wp_ajax_ajax_mp3', 'ajax_mp3_func' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_mp3', 'ajax_mp3_func' ); // ajax for not logged in users
The issue I am having is that the file upload uses plupload AJAX request and it is performing asynchronously with my JS code so my code fires before the value of the hidden field var uploads is set and it returns empty before being sent via my AJAX request to the PHP File.
I don't know enough about AJAX to know how to isolate and run my AJAX request after the hidden value is set.