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.)
Related
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'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!
I'm trying to implement basic ajax. I've been following this tutorial. My JS fires when I click the button but I get a 400 from the ajax url: POST http://localhost:8080/wp-admin/admin-ajax.php 400 (Bad Request)
As far as I can tell, I haven't strayed far from the tutorial code. Her is my JS:
jQuery(document).ready(function($){
$('#baa_form').submit(function(){
var data = {
action: 'baa_response'
}
$.post(ajaxurl, data, function(response){
alert('Hello');
});
return false;
});
});
PHP:
<?php
function baa_add_menu() {
global $baa_settings_page;
$baa_settings_page = add_menu_page( 'Basic Admin Ajax', 'Basic Admin Ajax', 'edit_pages', 'basic-admin-ajax', 'baa_render_settings_page', false, 62.1 );
}
function baa_load_scripts( $hook ) {
global $baa_settings_page;
if ( $hook !== $baa_settings_page ) {
return;
}
$path = plugin_dir_url( __FILE__ ) . 'js/basic-admin-ajax.js';
wp_enqueue_script( 'basic-admin-ajax', $path, array( 'jquery' ) );
}
add_action( 'admin_menu', 'baa_add_menu' );
add_action( 'admin_enqueue_scripts', 'baa_load_scripts' );
function baa_render_settings_page() {
?>
<form id="baa_form" method="POST">
<div>
<input type="submit" name="baa_submit_button" id="baa_submit_button" class="button-primary" value="go ajax">
</div>
</form>
<?php
}
function baa_response() {
die( 'I got died' );
}
I've had a look inside admin-ajax.php and the only reason for returning a 400 that I can see is if I've failed to set an action. data['action'] is certainly set, unless I'm crazy.
Am I doing anything that's obviously wrong? What could be causing the 400 response?
update
To clarify, the JS fires but the request to admin-ajax.php receives a 400. You can see where the tutorial make has implemented similar JS here. (I haven't added a nonce yet but the video maker had already demonstrated it working without implementing a nonce.)
edit
I've updated the PHP to show the plugin's entire PHP file.
update 2
I've stripped the JS back to the essentials and followed the top example from Wordpress. The response is still 400. Which leads me to believe that it might be something I've overlooked in the php. At the moment, I don't understand why or what it might be.
jQuery(document).ready(function($) {
var data = {
'action': 'baa_response'
};
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
You missed action, which will fired on your Ajax request. WordPress can't guess which function related to your Ajax call, and that's why just blocking it( 400 Bad Request ).
In the php file add this line:
add_action('wp_ajax_baa_response', 'baa_response');
You may also want to look at the Ajax in Wordpress documentation.
Please try like this,
Add this to your functions.php,
$path = plugin_dir_url( __FILE__ ) . 'js/basic-admin-ajax.js';
wp_enqueue_script( 'basic-admin-ajax', $path, array('jquery'), '1.0', true );
wp_localize_script( 'basic-admin-ajax', 'action_linklist', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
function baa_response() {
echo "something.....";
die();
}
in your JS file,
jQuery(document).ready(function($){
$('#baa_form').submit(function(){
jQuery.ajax({
url: action_linklist.ajax_url,
type: 'post',
data:{'action': 'baa_response'},
success: function (response) {
alert(response);
}
});
return false;
});
});
Hope this will helps you,
For more information, please visit.
Using AJAX with wordpress
AJAX in Plugins
I have been busting my balls for the last week on the issue below. Ofcourse I did search and come across posts of people describing similar issues but none of the answers and solutions discussed seem to solve my problem.
I want my Wordpress plugin to make use of the build-in Wordpress functionalities but my functions keep returning value: 0 in the console. The JS get 'loaded' on the admin_footer add_action and executes when someone hits 'add-row' button. That all seems to be working fine. However the console message keeps returning:
Successful AJAX Call! /// Return Data: 0
So it seems to me that the woosea_ajax function never even gets called? Who can help me out here? Greatly appreciated.
function woosea_ajax() {
$data = "hello world";
echo json_encode($data);
wp_die(); // just to be safe
}
add_action( 'wp_ajax_woosea_ajax', 'woosea_ajax' );
function ajax_js_script() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
jQuery(".add-row").click(function(){
jQuery.ajax({
method: "POST",
url: ajaxurl,
data: {
action: 'woosea_ajax'
}
})
.done(function( data ) {
console.log('Successful AJAX Call! /// Return Data: ' + data);
})
.fail(function( data ) {
console.log('Failed AJAX Call :( /// Return Data: ' + data);
});
});
});
</script>
<?php
}
add_action( 'admin_footer', 'ajax_js_script' );
To give access on the front-end side (anonymous users), you'll need to add the nopriv action too, like:
add_action( 'wp_ajax_nopriv_woosea_ajax', 'woosea_ajax' );
I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.
I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?
(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)
I've got my code[1] set up as follows:
mu-plugins/sample.php:
<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
class SamplePlugin {
function SamplePlugin() {}
function addHeaderCode() {
echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
'/wp-content/mu-plugins/sample/sample.css" />\n';
wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
'/wp-content/mu-plugins/sample/sample-ajax.js.php',
array('jquery'), '1.0');
}
// adds the link to post content.
function addLink($content = '') {
$content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
return $content;
}
function doAjax() { //
echo "<a href='#'>AJAX!</a>";
}
}
}
if (class_exists("SamplePlugin")) {
$sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
add_filter('the_content', array(&$sample_plugin, 'addLink'));
}
mu-plugins/sample/sample-ajax.js.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var aref = this;
jQuery(this).toggleClass('clicked');
jQuery.ajax({
url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
success: function(value) {
jQuery(aref).html(value);
}
});
});
});
mu-plugins/sample/sample-ajax.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
$sample_plugin->doAjax();
} else {
echo "unset";
}
?>
[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));
Use both if you want it to work for everybody.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Sorry, I didn't quite understand the question. I thought you were asking how to do an ajax request. Anyway, two things I'd try:
First, have your function echo just the word AJAX without the a tag. Next, try changing your ajax call so it has both a success and a complete callback:
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var val = '';
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
val = value;
},
complete: function(){
jQuery(this).html(val);
}
});
});
});
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
Please take a look to:
wp_register_script(); function
wp_enqueue_scripts hook
wp_enqueue_script(); function
wp_localize_script(); function
File: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR JS FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
File: jquery.ajax.js
This file makes the ajax call.
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
File: functions.php 2/2
Finally on your functions.php file there should be the function triggered by your ajax call.
Remember the suffixes:
wp_ajax ( allow the function only for registered users or admin panel operations )
wp_ajax_nopriv ( allow the function for no privilege users )
These suffixes plus the action compose the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
Hope it helps!
Let me know if something is not clear.
Just to add an information.
If you want to receive an object from a php class method function :
js file
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var data = {
'action': 'getAllOptionsByAjax',
'arg1': 'val1',
'arg2': $(this).val()
};
jQuery.post( ajaxurl, data, function(response) {
var jsonObj = JSON.parse( response );
});
});
php file
public static function getAllOptionsByAjax(){
global $wpdb;
// Start query string
$query_string = "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";
// Return results
$a_options = $wpdb->get_results( $query_string, ARRAY_A );
$f_options = array();
$f_options[null] = __( 'Please select an item', 'my_domain' );
foreach ($a_options as $option){
$f_options [$option['id']] = $option['name'];
}
$json = json_encode( $f_options );
echo $json;
wp_die();
}