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?
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);
jquery.js?ver=1.12.4-wp:4
POST https://xyz/update.php 500 (Internal Server Error)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
myFunction # 6011c7fbf.min.js?ver=1600216310:3
onclick # (index):453
I am getting a 500 error above from the console. What I dont know is whether the error is in my PHP in trying to update the row or elsewhere.
PHP below is contained inside my update-file.php file
function function_1() {
global $wpdb;
$wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
}
JAVASCRIPT contained on the page
function myFunction() {
jQuery.ajax({
type: 'post',
url: '/wp-content/themes/yummy/update-file.php',
success: function(data){
// callback function
}
});
alert("I've been clicked!!");
}
HTML
Go!
EDIT 1
As per suggestions I have updated as such:
JAVASCIPT
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
action: 'function_1',
success: function(data){
// callback function
}
});
Thinking the above was not correct I also tried :
jQuery.ajax({
type: 'post',
url: my_ajax.https://myurl.com/wp-content/themes/yummy/update-waitinglist.php, // this is the location of the update php below
action: 'function_1',
success: function(data){
// callback function
}
});
PHP below is contained inside my update-file.php file
add_action('wp_ajax_function_1', 'myfunctionname'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'myfunctionname'); // non logged in user can make a call
function myfunctionname() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
die($results);
}
ADDED TO FUNCTIONS FILE
wp_localize_script('myfunctionname', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
With the EDIT 1 in place, I also get an error - Notice: wp_localize_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 wait list_update handle. Please see Debugging in WordPress for more information. www.xyz.com/wp-includes/functions.php on line 5225 . I must have misunderstood something in the suggestion.
EDIT 2 Got everything else working but the button doesnt seem to update anything.
PHP from functions file -
function my_scripts() {
wp_enqueue_script( 'waitlist_update_call', get_template_directory_uri().'/assets/js/waitlist_update_call.js', array('jquery'), null, true );
wp_localize_script('waitlist_update_call', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
echo getcwd();
//calls Waitinglist data and creates table
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action('wp_ajax_waitlist_update_function', 'waitlist_update_function'); // logged in user can make a call
function waitlist_update_function() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'mytablename' SET `currentstatus` =
'myupdate1' WHERE ID = '1'"));
die($results);
}
JS
// JavaScript Document
function update() {
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
// add your action inside data object
data: {
action: 'waitlist_update_function'
},
success: function(data){
// callback function
}
});
}
HTML
Go!
The issue should be with the URL, it must be absolute I think.
jQuery.ajax({
//....
url: 'http://yourwebsite.com/wp-content/themes/yummy/update-waitlist.php'
// ...
The WordPress way
You must enqueue your JS file script.js before with same handle
and then localize after it
Localize the script to pass generic data. We will pass the ajax_url with my_ajax object.
functions.php
wp_localize_script('your-script-handle', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
Then in your script file, you can use the my_ajax object to get the AJAX URL. Define a action function_1 which will be executed when this AJAX call is requested.
script.js
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
data: {
action: 'function_1',
}
success: function(data){
// callback function
}
});
Define a function and attach it with Ajax action that will query the database & returns the result.
functions.php
add_action('wp_ajax_function_1', 'function_to_execute_some_query'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'function_to_execute_some_query'); // non logged in user can make a call
function function_to_execute_some_query() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'wp_wpdatatable_4' SET `currentstatus` =
'myupdate1' WHERE wdt_ID = '1'"));
die($results);
}
I have to select a file locally and use it in a python script.
I can't get the filename in order to have it in my ajax script that i use to call a php function.
This is my javascript, called onclick over Ok button:
function myAjax () {
$.ajax( { type : 'POST',
data : {},
url : 'action.php',
success: function ( data ) {
alert( data );
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
},
complete: function (data) {
setImg();
}
});
}
This is the php script used to call python script:
<?
function bb(){
$out = shell_exec( 'python heatmap.py');
echo "ok";
$fp = fopen('log.txt', 'w');
fwrite
($fp, $out);
fclose($fp);
}
bb();
?>
I have to take filename from Browse button and send it to ok button, where the python is called.
What is the correct way to exchange data from input="file" html, javascript and php?
I'm making a lot of assumptions here as the question is not entirely clear...
But presumably you're wanting the name of a file that has been selected from the OS. In JS you can do this using the following.
var fileName, oForm = document.getElementById('my-file');
oForm.onchange = function(){
fileName = this.files[0].name;
}
Then in your AJAX call, add the fileName variable to your data property.
data : {"filename":fileName},
And then in your PHP access it via the $_POST variable. So...
echo $_POST['filename'];
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.