I've been googling this for a while and have tried a number of things (for example nesting my formName and formData in the 'data:' attribute, but that resulted in parseerrors, so I'm guessing I'm pretty close to having this working! I've also removed those attributes and hard coded the items in my function, but the problem remains the same.
Everything appears to be OK and I get by success alert, but when I check my database the usermeta hasn't been updated. I don't know the best way to debug the PHP function either so any tips on that would be handy for the future!!
This is my ajax function which get's fired on blur:
function storeData(data) {
$.ajax({
type: 'POST',
formData: data,
formName: 'Testform',
action: 'storeApplicationData',
success:function( data ) {
console.log('stored form');
},
error: function(xml, error) {
console.log(error);
}
});
return false;
}
This is my PHP code in my functions file, I've hard-coded the values I'm passing in to update_user_meta for now, just to ensure that isn't the issue:
function storeApplicationData(){
update_user_meta('15', 'Testform', '12345678');
}
add_action('wp_ajax_storeApplicationData', 'storeApplicationData');
add_action('wp_ajax_nopriv_storeApplicationData', 'storeApplicationData');
I'm checking the database directly, the meta field doesn't get updated...
Any help would be appreciated!
I figured this out, I was missing the proper enqueing for my ajax url:
function theme_enqueue() {
$theme_url = get_template_directory_uri(); // Used to keep our Template Directory URL
$ajax_url = admin_url( 'admin-ajax.php' ); // Localized AJAX URL
// Register Our Script for Localization
wp_register_script( 'applications', "{$theme_url}/applicationform.js", array( 'jquery' ),'1.0', true);
// Localize Our Script so we can use `ajax_url`
wp_localize_script('applications','ajax_url',$ajax_url);
// Finally enqueue our script
wp_enqueue_script( 'applications' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue' );
I also added:
url: ajax_url,
to my ajax!
Related
I'm currently developing a plugin. In the plugin's main.php file, I have the following code to do an ajax post request:
main.php
<?php
add_action( 'admin_footer', 'first_ajax' );
function first_ajax() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#mybutton').click(function(){
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
action : 'second_ajax'
},
success: function(response) {
console.log("successful");
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
<?php } ?>
But on the browser console, I see an error object.
Screenshot 1
Screenshot 2
I wrote this function taking as reference: https://codex.wordpress.org/AJAX_in_Plugins.
Any help is appreciated.
You're calling javascript from a php function tho your javascript is "raw" and not wrapped in a php variable. We're also missing a bunch of information in regard to the ajax action function (the php part which is supposed to answer to the request).
An ajax request need two things to be able to work properly.
The javascript call to action function and the backend php action function.
It a standard to use anonymous php functions as action functions.
Ajax action functions hooks are prepended with a wp_ajax_{$action} for public function (non-logged-in users) and wp_ajax_nopriv_{$action} for logged-in users. A logged-in user won't be able to use a public ajax function same goes for non-logged-in users.
The {$action} part is set in your javascript call to action function.
It is standard to pass a nonce as well as the ajax admin url through the localize_script() function. Localizing data only works if the script has already been registered.
An example of registering/enqueuing a script and localizing varaibles: functions.php
<?php
wp_enqueue_script( 'my-ajax-script', trailingslashit( get_template_directory_uri() ) . 'assets/js/my-ajax-script.js', array(), wp_get_theme()->version, true );
wp_localize_script( 'my-ajax-script', 'localize', array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );
(The Object's name localize and variables _ajax_url and _ajax_nonce used in wp_localize_script() are just a personal preference).
A basic javascrip ajax call to action function looks like this: my-ajax-script.js
$( '#selector' ).click( function ( event ) {
$.ajax( {
type: 'POST',
url: localize._ajax_url,
context: this,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73933867', //where this match {$action} from wp_ajax_{$action} in our php action function.
},
success: function ( response ) {
console.log( response );
//...
},
} );
} );
Where we use are localized variables: localize._ajax_url and localize._ajax_nonce (best practices).
A basic php ajax action function looks like this: functions.php
<?php
add_action( 'wp_ajax__wpso_73933867', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
//...
wp_send_json_success();
} else {
//...
wp_send_json_error();
};
wp_die();
} );
If the function is intended to be use by a non-logged-in user wp_ajax_nopriv should be prepended instead of wp_ajax_. Vice versa. If both case are supposed to be used, the function should be doubled.
I have been troubleshooting this for hours now and I am stumped as to why this error is occurring.
in my JS I have the following ajax:
var $ = jQuery; // define jquery
let name = "Mark";
let pies = "cherry";
$(document).ready(function(){
$.ajax({
type : 'POST',
dataType : 'json',
url : ajaxurl,
nonce: nonce,
data : {
action: 'myfunction',
name: name,
pies: pies,
nonce: nonce
}
}).done(function(response) {
console.log(response);
});
}); // end document ready
and in my plugin's PHP, I have
function myfunction() {
if ( wp_verify_nonce( $_POST['nonce'], 'registration_nonce')) {
$name = $_POST['name'];
$pies = $_POST['pies'];
file_put_contents('debug_output.txt', $pies);
die();
}
}
add_action( 'wp_ajax_myfunction', 'myfunction' );
add_action( 'wp_ajax_nopriv_myfunction', 'myfunction');
This gives me a 400 every single time. This should be a simple thing and I normally do this all of the time but for some reason, I am seriously missing something. Any ideas anyone? I whittled it done to the bare minimum and still no luck. Both the ajax URL and nonce are fine. Did something in WP change?
There are some things that maybe you should fix/check:
in your PHP action end with something like echo json_encode($myDataArray) where $myDataArray is something like array("key" => "value") ecc..
Your last function call inside the PHP action should always be "die" or "exit" or just use the WP wp_send_json(); (you have alternatives for success/errors)
Double check that ajaxurl actually points to admin_url( 'admin-ajax.php' )
Double check that your add_action hooks get called somewhere in your page before the AJAX call actually occours
Typo?
add_action( 'wp_ajax_nopriv_myactiont', 'myaction');
// should be
add_action( 'wp_ajax_nopriv_myaction', 'myaction');
// final result
function myaction(){
echo "success";
exit;
}
add_action( 'wp_ajax_myaction', 'myaction' );
add_action( 'wp_ajax_nopriv_myaction', 'myaction');
Diego's answer has some good points to check too.
First time posting to StackOverflow. (upvotes appreciated to help me get included in the community)
Despite being new to coding in general, I've been able to work out the following steps in Wordpress thanks to Zac Gordon's very helpful video https://youtu.be/Z0Jw226QKAM?t=216 and demo files https://github.com/zgordon/wordpress-ajax following the steps he outlines:
Pass Nonce and AJAX URL via wp_localize_script
Make AJAX call with Nonce and URL in JavaScript
Hook PHP AJAX Function into Wordpress AJAX Hooks
Use JavaScript to Handle AJAX Response
Although I am able to return the expected result with the AJAX response (which I can print to console) and I am now able to retrieve a value to pass to another function, I am unable to update the value in advance of passing it to other functions.
Based on other StackOverflow conversations (JQuery - Storing ajax response into global variable) I am thinking this is probably an issue with Asynchronous vs Synchronous AJAX calling. However I've further read that setting "async: false" should be avoided at all costs and seems to be deprecated at this point (and didn't help when I tried) so I'm trying to find the proper way to pass this variable from one function to another. Answers I read were not specific to Wordpress which left me at a loss for solving on my own.
The goal is fairly straightforward: get the $(window).height() using AJAX, store as a variable, pass variable into another function in PHP which transforms that variable and adjusts the height of a map Plugin (hook: storymap_heights ).
For starters: I'm currently just trying to get this to work with initial page load, but I would also be curious if it's possible to rerun the functions every time the browser window is resized?
The following code gets me close: I have to refresh twice for the global variable $heights {and/or "get_option( 'jsforwp_heights' )" } to update and properly set the "new" browser window size (so it seems to be storing the variable but not until after it runs through at least once before). The code is currently stored in a Wordpress Snippets plugin, but should work the same as being placed in Functions.php:
<?PHP
global $heights;
if ( null == $heights ) {
add_option( 'jsforwp_heights', 100 );
}
$heights = get_option( 'jsforwp_heights' );
function my_theme_scripts() {
wp_enqueue_script( 'my-great-script', get_template_directory_uri() . '/assets/js/my-great-script.js', array( 'jquery' ), '1.12.4', true );
wp_localize_script(
'my-great-script',
'jsforwp_globals',
[
'ajax_url' => admin_url('admin-ajax.php'),
'total_heights' => get_option('jsforwp_heights'),
'nonce' => wp_create_nonce('nonce_name')
]
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
function screen_height_is(){
check_ajax_referer('nonce_name');
global $heights;
$heights = $_POST['height'];
update_option('jsforwp_heights',$heights);
// set_map_height($heights); //test
$response['success'] = true;
$response['height'] = $heights;
$response = json_encode($response);
echo $response;
wp_die();
}
add_action('wp_ajax_screen_height_is','screen_height_is',1);
add_action( 'wp_ajax_nopriv_screen_height_is', 'screen_height_is',1 );
function set_map_height(){
global $heights;
$testA = get_option('jsforwp_heights');
$testB = "px";
$height = $testA. $testB;
echo $height;
return $height;
}
add_filter('storymaps_heights','set_map_height',10);
//tests for function above
//function set_map_height($heights){
//$testA = '300'; //static option
//$testA = $heights; //works with same loading delay problem
//$testA = $response['height']; //doesn't work even if $response set as global
I have tried nesting the functions without success and calling the set_map_height($heights) from within the screen_height_is() function without success. I also have tried setting #Priority within add_action and add_filter (1 for add_action, 10 for add_filter) to try to get them to wait to run but this also does not seem correct.
The following code is stored in my js file: my-great-script.js:
jQuery(document).ready(function($){
var myResponse;
$.ajax({
type: 'post',
dataType: 'json',
url: jsforwp_globals.ajax_url,
async: false,
data: {
action : 'screen_height_is',
_ajax_nonce : jsforwp_globals.nonce,
width : $(window).width(),
height : $(window).height(),
screen_width : screen.width,
screen_height: screen.height
},
success: function( response ) {
// if( 'success' == response) {
if( response['success'] == true) {
alert("Something went right");
}
else {
alert("Something went wrong");
}
}
})
.done(function(response) {
console.log(response);
})
.fail(function(error) {
alert(error);
})
.always(function() {
console.log("complete");
});
});
Console log prints:
{height: "598", success: true}
complete
I am a little unclear if/how I should be modifying the Success callback to reach my overall goal? Or if the wp_enqueue_script() dependencies need to be modified?
In case this helps, the following filter in PHP hooks into the storymaps-core.php file:
add_filter('storymaps_heights','set_map_height',10);
Where the following wp_enqueue_script resides:
function storymap_external_resources() {
wp_enqueue_style( 'storymap-stylesheet', 'https://cdn.knightlab.com/libs/storymapjs/latest/css/storymap.css' );
wp_enqueue_script( 'storymap-javascript', 'https://cdn.knightlab.com/libs/storymapjs/latest/js/storymap-min.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'storymap_external_resources' );
Any help on what to try next is much appreciated!
I'm trying to do some basic stuff but my php code seems not to be called.
I have a button with an onclick event with points to a js function
<button type="button" onclick="tryphp()">go!</button>
and this is in my index.php file.
Then I have a subfolder called js with inside my js file and the function is as follows
function tryphp() {
jQuery.ajax({
url: 'php/try.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert('success!!!!');
}
});
}
finally, I have another subfolder "php" with inside my try.php
<?php
echo 'hello';
?>
I expect the button to fire a "success!!!!" when clicked but nothing happens.
I'm trying to figure out if the error is in the "url" paramether of the ajax call?
The file structure is as below
/main/index.php
/main/js/file.js
/main/php/try.php
Any help would be great!
Last but not least, my functions.php file is as follows
<?php
function newtheme_script_enqueue() {
wp_enqueue_style('style1', get_template_directory_uri() . '/css/newtheme.css', array(), '1.0.0', 'all');
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array(), '1.0.0', TRUE);
wp_enqueue_script('script1',get_template_directory_uri() . '/js/jquery.js', array(), '1.0.0', TRUE);
}
add_action('wp_enqueue_scripts','newtheme_script_enqueue');
and inside jquery.js I have downloaded the compressed version of jquery.
thanks in advance!
-----------UPDATE------------
SOLVED!
There were 2 mistakes:
-i did not specify the dependency in the script enqueue
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array('jquery'), '1.0.0', TRUE);
-the path to the php file was missing the "template directory" part
Thanks everybody!
First of all you have to know that Wordpress integrate ajax as well.
On file functions.php you must have the function that fires out results to ajax calls
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
And on your javascript file there should be something like:
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
Please read reference at this link that's made for plugins but works for themes as well.
If you make a lot of ajax requests, you might want to use something like this to help find problems:
jQuery.ajax({
url: 'php/try.php',
dataType: 'text',
success: function (response) {
console.log('Success: ' + response);
},
error: function (x) {
//loop though error response
$.each(x, function(y, z){
console.log('Error: ' + y + ' ' + z);
});
},
});
If you have an error somewhere in your php file you should see it after "Success" response in your console.log. If your url is incorrect you should see the error somewhere in the "Error" response - it's usually towards the end of the responses. (Unless you love the sound of your browser's alert, I would give your responses to console.log as the error response will produce quite a few alerts.)
I have searched for this a lot but still didn't found any solution for this . I want to call an ajax action after submission of post comment . How can I do this with WordPress ?
Without code, I cannot give you the following steps with code myself:
Track the event that triggers comment submission and on which DOM element it happens.
In the event handler, send an XMLHTTPRequest to server using jQuery.ajax.
Make sure you create the ajax call in the Wordpress way, and so by sending requests to wp-admin/admin-ajax.php and puting logic under functions.php. Add the die() function.
I would filter the comment with a WordPress filter. You may not need an AJAX request at all. But I'm not exactly sure why you need AJAX. To learn more about this filter.
function preprocess_comment_handler( $commentdata ) {
//some code
return $commentdata;
}
add_filter( 'preprocess_comment' , 'preprocess_comment_handler' );
If you do need AJAX, here's how to make it run in WordPress. You'll need to use wp_localize_script() to get your AJAX to admin-ajax.php.
//add wp_localize_script to your functions.php
//make sure to enqueue the js file you are writing to and it's dependencies
function acarter_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script('your-script', get_template_directory_uri() . '/js/theme.js');
wp_localize_script('your-script', 'your_script_vars', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
add_action( 'wp_enqueue_scripts', 'acarter_enqueue_scripts' );
//do your AJAX call in the file you just enqueued
jQuery( document ).ready( function($) {
//Ajax Form Processing
var $form = $( '#button' )
$form.submit( function (e) {
e.preventDefault();
$.ajax({
type: '',
url: your_script_vars.ajaxurl,
data: {
action: 'function_name_of_the_callback',
//key : values of stuff you want in the php callback
},
dataType: 'json',
success: function (response) {
if ( true === response.success ) {
console.log( 'success!!' );
});
} else if ( false === response.success && response.data ) {
window.alert( 'doing it wrong' );
}
}
});
});
});
You maybe able to send the data to the aforementioned filter, thus using the filter as the callback, but, I've never tried this. At the least you'll know how to setup AJAX in WordPress.