WP functions undefined in plugin - php

I am having trouble with a plugin I am writing, the plugin shows a form and the form submits to ajaxupload.php.
Basically in my plugin file:
add_action('plugins_loaded','add_to_menu');
function add_to_menu(){
add_action('admin_menu', 'test_plugin_setup_menu');
}
function test_plugin_setup_menu(){
add_menu_page( 'Test Plugin Page', 'add new entry', 'manage_options', 'test-plugin-link', 'test_init' );
// ,'dashicons-database-add'
}
function test_init(){
//echo "<h1>Hello World!</h1>";
// do_action( 'admin_init' );
include(ABSPATH."/wp-content/plugins/my-plugin/form.php");
}
In form.php I can call wp functions!
<?php
// this works!
echo wp_get_current_user()->user_login;
?>
<form>
...
</form>
<script>
$(document).ready(function(){
$("#my_form").on("submit",function(e){
e.preventDefault();
var sendData = $( this ).serialize();
$.ajax({
url: "../wp-content/plugins/my-plugin/ajaxupload.php",
type: "POST",
data: new FormData(this),
...
</script>
in Ajaxupload.php I can't use any WP constants or functions before submission...
if( !empty($_POST['imgurl']) || !empty($_FILES['image']) )
{
$someform_field = $_POST["name"];
echo wp_get_current_user()->user_login; //this line fails
//then call to wpdb to add data to DB
What should be the correct sequence to make wp functions usable in the ajaxupload.php file?

You have to load the wp-load.php file in your ajaxload.php, which loads all wordpress functions, because your ajaxload.php file is called directly:
<?php
require_once __DIR__ . '/../../../wp-load.php';
$someform_field = $_POST["name"];
$user = wp_get_current_user()->user_login; // should now work
//then call to wpdb to add data to DB

Related

Ajax in Wordpress to reload a SELECT every second

My target is to take a page of an existent WP theme and customize a full width page, to make that every 1 seconds a MySQL SELECT query is reloaded and the results are shown.
Starting with this snippets I have made the following editing/new files:
template-fullwidth.php
functions.php
my.js (new file)
GetPostDate.php (new file)
What I have done
I started from the template-fullwidth.php of a theme and add the following code between the DIV of the post. The place where I wanted to show the results is between <div id="MaxPostDate"> tags.
</div><!-- .post -->
<!-- START CUSTOM PAGE CODE -->
<?php
if ( is_user_logged_in() ) {
// --- START IF USER LOGGED IN --- //
// Get the current user name and id
?>
<div id="MaxPostDate"></div>
<?php
// --- END IF USER LOGGED IN --- //
} else {
// --- START IF USER NOT LOGGED IN --- //
echo "<p>You have to log-in to see this content</p>";
// --- END IF USER NOT LOGGED IN --- //
}
?>
<div class="result"></div>
<!-- END CUSTOM PAGE CODE -->
<?php comments_template( '', true ); ?>
</div><!-- .posts -->
then I have edited the functions.php file of the theme adding this in the end:
function add_myjavascript(){
wp_enqueue_script( 'ajax-implementation.js', get_bloginfo('template_directory') . "/js/my.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myjavascript' );
function MyAjaxFunction(){
//get the data from ajax() call
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){echo "<h1>" . $Content->MaxDate . "</h1>";}
// Return the String
die($results);
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );
?>
Then, I have made this my.js in the js folder of the theme:
jQuery(document).ready(function refresh_div() {
jQuery.ajax({
url:'/MySite/wp-content/themes/hemingway/GetPostDate.php',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000););
And finally make another file GetPostDate.php
<?php
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){echo "<h1>" . $Content->MaxDate . "</h1>";
?>
The problems
nothing appear inside the DIV id="MaxPostDate"
I have wrote two time the same query (SELECT MAX(post_date) AS MaxDate FROM wp_posts), I would be wrote just one time!
I think the problem is with your AJAX URL.
Execute your AJAX in footer.php like below:
jQuery.ajax({
url:'<?php echo admin_url('admin-ajax.php'); ?>',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
then you don't need GetPostDate.php file either.
this my.js in the js folder of the theme
jQuery(document).ready(function refresh_div() {
jQuery.ajax({
url:'//MySite/mysite/wp-admin/admin-ajax.php',
action:'MyAjaxFunction',
type:'POST',
dataType:json,
success:function(results) {
jQuery(".result").html(results.result);
}
});
}
t = setInterval(refresh_div,1000););
the functions.php file of the theme adding this in the end:
function MyAjaxFunction(){
//get the data from ajax() call
$jsonresult = array();
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){
$jsonresult['result'] = $Content->MaxDate
}
echo json_encode($jsonresult);
die();
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );

Passing ajax variable to more than one wordpress plugin function

I'm trying to get information from the front end of my Wordpress site, I used ajax to do that, it gave me the ability to use the data in one of my plugin functions, but in my case I want to use this data in more than just one function.
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
};
jQuery.post(ajaxurl, data);
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
$whatever = $_POST['whatever'];
}
In other words I need to use $_POST['whatever'] in other functions in my plugin not only my_action() function, I tried using PHP global variables like so , but it didn't workout:
$whatever;
function my_action(){
global $whatever = $_POST['whatever'];
}
function my_other_function(){
global $whatever;
if(isset($whatever)){
echo $whatever;
}
}

How to get wp_ajax to work with jQuery $.post

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.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>
<?php
}
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
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?
Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?

How to send ajax request in wordpress without displaying zero

I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property action as below so that WP knows which action to call.
In your particular case you'll also have to declare ans_name (as opposed to data), so that $_POST['ans_name'] exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used $_POST['ans_name'] in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.
Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
<script type="text/javascript">
function key_press(){
var data = {
url: '<?php echo get_admin_url()?>admin-ajax.php',
type: 'POST',
action: jQuery('[name="ans_name"]').serialize(),
ans_name: jQuery('[name="ans_name"]').serialize()
};
var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
alert('Got this from the server: ' + response);
});
myRequest.done(function(){
alert("success");
});
}
</script>
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax(){
echo $_POST['ans_name'];
die(); // Required for a proper Wordpress AJAX result
}
Addition
To ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to your functions.php file.
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

how to call external php file in WordPress using ajax

I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I'm pretty new to WordPress.
I have solve my problem on my own.First i have define ajaxurl in my themes function.php like below:
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<? }
?>
And I put the below script on the top of my plugin file.
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
var data = {
action: 'my_action',
value: val,
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
and here's the field, for which i am trying to do in my plugin.
<textarea name="custom_text_message" id="custom_text_message"></textarea>
and then I put my action which i m calling to my script in function.php.
add_action('wp_ajax_my_action', 'my_action_session');
function my_action_session() {
global $wpdb; // this is how you get access to the database
session_start();
$_SESSION['cus_msg'] = $_POST['value'];
die(); // this is required to return a proper result
}
and then call my session value in to my function.That's all i do and work for me and i hope this will helps someone else.
Note:
The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action.
In WordPress, Ajax requests should be made to http://your-wordpress-site/wp-admin/admin-ajax.php - which can be obtained using admin_url( 'admin-ajax.php' ) - and you should use action parameter to specify which function to call. You can pass the admin-ajax path to your javascript file via localization.
Add to your plugin PHP file after you enqueue your script:
wp_localize_script( 'your-script', 'js_obj', array('ajax_url' => admin_url( 'admin-ajax.php' ) );
In your javascript:
jQuery.post(js_obj.ajax_url, {value: val, action: 'run-my-ajax'})
Function to process the ajax in your plugin PHP file:
function call_my_ajax(){
// do stuff
exit;
}
add_action('wp_ajax_run-my-ajax', 'call_my_ajax');
add_action('wp_ajax_nopriv_run-my-ajax', 'call_my_ajax');
Read more: https://codex.wordpress.org/AJAX_in_Plugins
<script type="text/javascript">
function setVal()
{
jQuery.ajax({url:"<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php",success:function(result){alert(result);}}
}
</script>
WordPress works on absolute paths, use a complete URL instead of the relative URL:
jQuery.post('session.php', {value: val})
Use something like:
jQuery.post('<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php', {value: val})

Categories