I created plugin for Wordpress and am now trying to learn Ajax in plugin.
When I call my function:
wp-admin/admin-ajax.php?action=my_action
I get this error:
Notice: Undefined index: whatever
This is my function
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here
function my_action_javascript() { ?>
<script type="text/javascript" >
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
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script> <?php
}
and function call back
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
}
What's causing this error and how can I fix it?
When you make a request to wp-admin/admin-ajax.php?action=my_action it only includes the action query string parameter and not the whatever parameter that the callback function in WordPress is expecting.
If you want this to work in a browser test from the address bar replace $_POST['whatever'] with $_REQUEST['whatever'] and use this in your browser wp-admin/admin-ajax.php?action=my_action&whatever=1234 - this will pass whatever as a GET whereas in your ajax it is a POST, but $_REQUEST will see both.
That said, your example code is correct - I even tested it on a local install. When your JavaScript executes it will include both parameters as part of the data object, which can then be process in the ajax handler. Just load your site in a browser and the code should alert unless you have other JavaScript errors.
Related
I referred to some examples online and modified functions.php and the front end template to fire an ajax call to fetch some data. But I've hard time understanding on hoe the data is returned from the requested url.
At the end of functions.php, I added,
wp_enqueue_script('jquery');
function myFunction(){
echo "hi";
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
In my custom template page, I added,
var datavalue = 'test data string';
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: { 'datavar' : datavalue }
}).success(function(data) {
console.log("successfully run ajax request..." + data);
}).done(function(){
console.log("I am from done function");
}).fail(function(){
console.log("I am from fail function.");
}).always(function(){
console.log("I am from always function");
});
});
After running it, I get these response.
I am from fail function.
I am from always function
I don't understand how to fetch data from a specific url and display the result in ajax's success function.
I don't even know how the function defined in function.php would be called by this ajax call? How are they related?
Please explain. Also I would like to fire ajax call to query database by passing keyword, how can I do that in wordpress?
Your AJAX function should include an action parameter to tell admin-ajax which function you would like to execute.
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
}
(or, if you are set up for it, then you can include it in your url, as below)
url: "/wp-admin/admin-ajax.php?action=myFunction"
Also, your function in functions.php should be written in PHP:
function myFunction(){
echo 'hello';
die();
}
You have to use a action on ajax like.
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
'datavar' : datavalue,
}
});
PHP function need to edit.
function myFunction(){
echo 'success calling functions';
wp_die();
}
you are not passing the "action" parameter in "data". Which contains callback function's name. Please check the attached link.
https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/
In this you've to make a callback functions.
Wordpress dsnt work with the specific url.
But if you still want to use the specific url. Follow the steps:-
1. Make a wordpress template.
2. Add your specific url code there.
3. Make a page in the admin panel and assign the template you've created above.
4. Now the permalink of that page can be used as a specific url in the jQuery ajax.
In addition to above answers, in your function.php, make use of $_REQUEST. The $_REQUEST contains all the data sent via AJAX from the Javascript call. Something like this
function myFunction() {
if ( isset($_REQUEST) ) {
{
global $wpdb;
$keyword = $_REQUEST["keyword"];
if($keyword){
$query = "
SELECT `$keyword`, COUNT($keyword) AS Total
FROM `profileinfo` GROUP BY `$keyword`
";
$result = $wpdb->get_results($query);
$data = array();
foreach($result as $row)
{
$data[] = $row
}
echo json_encode($data);
}
}
}
die();
}
add_action( 'wp_ajax_myFunction', 'myFunction' );
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
function scroll_load(){
var num_next=current_company()
//alert(num_next)
$('#loading').css('display', 'block')
$.ajax({
url: '<?php echo get_stylesheet_directory_uri().'/ajax.php?id=';?>'+num_next,
data:{year:current_year},
dataType: 'html',
success: function(html) {
$('#posts').append(html);
$('#loading').css('display', 'none')
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
this is my function i get data from ajax.php but when i use wordpress functions like get_header of short cut of plugins it say fatal error any one help me thanks
First off, take a look at https://codex.wordpress.org/AJAX_in_Plugins as it provides a good overview of how to use AJAX with WordPress.
So, you'll need to add two things to your AJAX call:
The AJAX URL for WordPress. An easy way to get this is, if you're enqueuing your Javascript with wp_enqueue_script(), you can then use wp_localize_script to get the the AJAX URL as a variable in the footer.
wp_localize_script( 'the-name-of-your-enqueued-script', 'ajax_url', admin_url( 'admin-ajax.php') );
Add a parameter to your data called action that WordPress will use to connect it to some action on the server. I'll call it more_posts
Then, in your functions.php file in your theme (or in your plugin), include some add_action's to...
add_action( 'wp_ajax_more_posts', 'more_posts_callback' );
add_action( 'wp_ajax_nopriv_more_posts', 'more_posts_callback' );
You need both the "nopriv" and regular version so logged in and not logged in users get the same functionality.
Next, write your more_posts_callback() function to do whatever you need done. You can grab your year variable from $_GET['year'] (assuming you're doing a GET request over AJAX)
Finally, to get your return value, echo your results, and then make sure to run wp_die(). Or, if you want to return a JSON object, simply write wp_send_json($return) where $return is whatever you want returned from the server.
function more_posts_callback(){
$year = $_GET['year'];
..... // Your code to generate $return
echo $return;
wp_die();
}
Now, what this doesn't include is any data validation or authentication, such as nonces or checking that $year is an integer.
Wow here is the answer if found it
For using WordPress functions like do_shortcut() the wp_load.php must be loaded in ajax url php file
Here is the code should be use for example in my code in ajax.php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );enter link description here
To be able to use <?php echo do_shortcode('[ssba]'); ?>
I need to set a WC()->set inside a php jquery .get function. What do I need to do inside of the php file to get access to the WC(). Right now it is telling me that WC is undefined.
This is inside my cart.php file that displays the cart and shows two radio buttons for a delivery options.
Here is the script that handles the RB change (I've simplified just to get the function to execute the reload upon return from the php query):
<script>
jQuery(document).ready(function($){
$("#myid").change(function(){
console.log("RB Changed!");
passed_variable = "1";
$.get('http://www.example.com/test.php',
{pass_var: passed_variable},
function(data, status) {
console.log("returned");
location.reload();
});
});
});
</script>
And here is the PHP query:
<?php
global $woocommerce;
echo "START<BR>";
$temp = $_GET["pass_var"];
WC()->session->set('_delivery_loading', $temp);
// or
$woocommerce->session->set('_delivery_loading', $temp);
echo "DONE[" . $temp . "]";
?>
Why do you need to call test.php? If you use a wp_ajax_$action callback you will be within the WP framework and WC() will be loaded. here's an example cobbled together from the codex and jQuery .ajax().
Enqueue the script you will be making the ajax calls from:
function so_34107959_enqueue_script(){
wp_enqueue_script( 'so_34107959_script', plugins_url( '/js/so_34107959.js' , __FILE__ ), '1.0b', array('wc-add-to-cart'), true );
}
add_action( 'wp_enqueue_scripts', 'so_34107959_enqueue_script' );
Note that the wc-add-to-cart script is a dependency. I'm only doing that so we can use WooCommerce's localized script variables. If you need to use this somewhere that the add to cart script isn't used then you will need to wp_localize_script() and pass in the admin ajax url yourself.
Your script file so_34107959.js:
jQuery(document).ready(function($){
$("#myid").change(function(){
var passed_var = "1";
$.ajax({
url: wc_add_to_cart_params.ajax_url, // here's the ajax url from WooCommerce
data: { action: "add_foobar", pass_var: passed_var } // the action must match up to wp_ajax_$action
})
.done(function( data ) {
if ( console && console.log ) {
// should return either success or fail
console.log( data );
}
});
});
});
And finally this code is the callback for your ajax "action":
function so_34107959_ajax_add_foobar() {
$temp = isset( $_REQUEST["pass_var"] ) ? $_REQUEST["pass_var"] : '';
if( $test ){
WC()->session->set('_delivery_loading', $temp);
echo 'success';
} else {
echo 'fail';
}
die();
}
add_action( 'wp_ajax_add_foobar', 'so_34107959_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'so_34107959_ajax_add_foobar' );
Untested, so watch out for typos.
Further explanations:
The PHP code assumes that you are writing a plugin. You could cheat and put it in your theme's functions.php but I think the theme should be kept for presentation and any functionality should be in plugins.
The codex has this explanation for the wp_ajax_$action hook:
This hook allows you to create custom handlers for your own custom AJAX requests. The wp_ajax_ hook follows the format "wp_ajax_$youraction", where $youraction is your AJAX request's 'action' property.
This means that if you pass an "action" to the "data" in your .ajax() that same action will wind up as the tail end of your wp_ajax_$youraction callback.
In my example therefore here's the data bit from the .ajax() script:
data: { action: "add_foobar", pass_var: passed_var }
The action is "add_foobar". It can be whatever.
Then you append that action "add_foobar" to the end of "wp_ajax_" so that add_action() looks like:
add_action( 'wp_ajax_add_foobar', 'so_34107959_ajax_add_foobar' );
This is for the admin/logged in users. The "nopriv" in:
add_action( 'wp_ajax_add_foobar', 'so_34107959_ajax_add_foobar' );
means that the ajax hook is available to non-logged in users.
Lastly, so_34107959_ajax_add_foobar() is the the server-side function that will handle your ajax request.
I am pretty sure that this is something really basic I am missing, but it's driving me nuts. Please help me out :-)
I am trying to get a basic AJAX call to work from within my own wordpress plugin.
I have two files:
bha-class.php
<?php
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
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
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?
}
?>
and bha-class-xhr.php
<?php
global $wpdb;
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;
die(); // this is required to return a proper result
}
?>
Things are working and the AJAX call is launched and `bha-class-xhr.php called.
However I get the error:
Got this from the server: <br />
<b>Fatal error</b>: Call to undefined function add_action() in <b>/var/www/institutforgestaltanalyse.dk/public_html/wp-content/plugins/bha-member-system/include/bha-class-xhr.php</b> on line <b>4</b><br />
So it seems the xhr file I am calling is not recognized within the Wordpress framework.
What did I miss?
It looks like you are calling your bha-class-xhr.php file directly from javascript. That is not the right file to call if you need WordPress.
Instead you should make your ajax call to the admin-ajax.php adding an action and other parameters if necessary.
Something like (depending on your installation and I am using GET here instead of POST):
/wp-admin/admin-ajax.php?action=my_action_callback
I have a jQuery code that is going to check when the user is near the bottom of the page. That's not the problem though. This jQuery is going to send a AJAX request, giving it some details on what to load when the user is near the bottom of the page. The code looks a bit like this at the moment:
$("<div>").load('?ajax=y&offset=something', function() {
$(".empty-div").append($(this));
setTimeout(function(){ console.log('after', $(document).height()); }, 0);
setTimeout(function(){ console.log('after', $(window).height()); }, 0);
});
My main problem is that I don't know what to query or how to go about sending the information to the PHP function in functions.php. For example, I have at the moment this as my PHP function (until it's working):
function get_posts_page() {
if(isset($_GET['offset'])) {
echo"Hello!";
}
}
I'm aware the wordpress has add_action and all that but I have no idea what I would apply as an action to either function to make the PHP recieve the data the Javascript is sending. Is there a URL where all functions are parsed or something? Thanks for any help in advance. So how do I get the data from the Javascript to the PHP function in functions.php, in my theme directory?
I just made a video to show you how to use the add_action request in WordPress. You can watch it here.
Here's my javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
$('#branding img').click(function() {
$.post('<?php bloginfo('siteurl') ?>/wp-admin/admin-ajax.php', {
action: 'my_unique_action',
offset: 5
}, function(data) {
$('#content').prepend('<p>' + data + '</p>');
});
});
</script>
And the php that I used in functions.php
// Make sure it runs when the user is logged in,
// and when they are not.
add_action('wp_ajax_my_unique_action', 'get_offset');
add_action('wp_ajax_nopriv_my_unique_action', 'get_offset');
function get_offset() {
if( isset($_POST['offset']) ) {
echo 'Your ajax request was successful. Here was your offset: <strong>' . $_POST['offset'] . '</strong>';
}
die;
}
Reference: http://codex.wordpress.org/AJAX_in_Plugins
You're trying to call a PHP function from Javascript, correct?
You'll need some logic on some page which calls get_posts_page(). Either you can create a new page getPostsPage.php?offset= or you can put some logic in functions.php, something like
if(isset($_GET['function']) {
switch($_GET['function']) {
case 'get_posts_page':
get_posts_page();
}
}
However, the former approach is recommended; you don't want someone to be able to modify the function parameter and access deleteAllPosts() maliciously.
Therefore:
// getPostsPage.php
require PATH . 'functions.php';
get_posts_page(); //checks $_GET['offset']
And remember to fail gracefully (do not expose an error message) if 'offset' is not set, or whatever.