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
Related
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’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')); ?>';
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.
I'm trying to do a custom AJAX action on WordPress but it isn't working. I have the following form:
<form method='post' name='form-bid-<?php echo get_the_ID() ?>' class="bid-form">
<input type='submit' name='<?php echo get_the_ID()?>' value='Licitar' class='bidvalue'>
<?php wp_nonce_field('ajax-bid-nonce', $post->ID); ?>
</form>
The form is this way because it's generated inside a loop, one for every post on the site, therefore I use the post ID as the unique name for the input.
Then, I capture the form submit on a custom JavaScript file:
jQuery(document).ready(function($) {
// Perform AJAX bid on form submit
$('form.bid-form').on('submit', function(e) {
var action = 'ajaxbid';
var auction_id = e.target.name.substring('form-bid-'.length);
var security_container = "#".concat(auction_id);
var security = $(security_container).val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_bid_object.ajaxurl,
data: {
'action': action,
'id': auction_id,
'security': security
},
success: function(data) {
console.log(data);
}
});
e.preventDefault();
});
});
This part works, and it prints 0 on the console upon success.
Finally, I have a PHP file where I register the script and have the function I want to call upon the form submission:
function ajax_bid_init() {
wp_register_script('ajax-bid-script', get_template_directory_uri() .'/js/ajax-bid-script.js', array('jquery') );
wp_enqueue_script('ajax-bid-script');
wp_localize_script( 'ajax-bid-script', 'ajax_bid_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// Enable the user with no privileges to run ajax_bid() in AJAX
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
}
add_action('init', 'ajax_bid_init');
function ajax_bid() {
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-bid-nonce', 'security');
echo json_encode(array('message'=>__('SUCCESS')));
die();
}
For now, all I wanted was the function to return that array and display it on console. However, the code never seems to run through here, and the AJAX response is always 0.
I have done a quite similar approach to both login and registration on the website and they both work. I've compared the 3 endless times and I cannot seem to find what I'm missing here.
Found the issue! I forgot to mention I was trying to do this with a logged user, so the problem was this line:
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
It should be this instead:
add_action( 'wp_ajax_ajaxbid', 'ajax_bid' );
I copied the first from my login and register forms, which made sense to be only available for non-logged users. The bids however are the exact opposite.
Just for future reference, you can register both (wp_ajax and wp_ajax_nopriv) for the same function if you want it to be executable for both logged and non-logged users.