Problems getting AJAX working in Wordpress - php

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

Related

Wordpress admin plugin AJAX call (ajaxurl) keeps returning 0

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' );

how i can use wordpress function and plugin shortcut in ajax.php

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]'); ?>

How to access WC() inside a PHP callback file with jQuery and .get

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.

Undefined index in Wordpress plugin when call AJAX

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.

Querying a function in functions.php?

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.

Categories