Using Ajax in a Wordpress Plugin

Using AJAX in a WordPress plugin

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:

  1. wp_register_script(); function
  2. wp_enqueue_scripts hook
  3. wp_enqueue_script(); function
  4. wp_localize_script(); function

In main plugin file, add these.

add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script(
'ajaxHandle',
plugins_url('PATH TO YOUR SCRIPT FILE/jquery.ajax.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 );
}
});
});

Also add below codes to plugin main file.

Finally, on your functions.php file, there should be the function triggered by your AJAX call.
Remember the suffixes:

  1. wp_ajax ( allow the function only for registered users or admin panel operations )
  2. 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
}

How to call AJAX in a WordPress plugin?

If "where to put the AJAX file" means how to include it to the admin page: The easiest way would be to use admin_enqueue_scripts(), for example, if you're implementing it in a theme:

<?php    
function load_ajax_script() {
wp_enqueue_script("ajax-script", get_template_directory() . "/scripts/ajax-script.js");
}
add_action("admin_enqueue_scripts", "load_ajax_script");
?>

Add this code to your functions.php within the active theme directory.

Next step would be the jQuery script. Open the .js script file used with wp_enqueue_script() and add the following:

jQuery(document).ready(function() {
jQuery("#fetch-data").click(function() {
var script_url = "http://www.example.com/wp-content/themes/my-theme/display.php";
var response_container = jQuery("#responsecontainer");
jQuery.ajax({
type: "GET",
url:script_url,
success:function(response) {
response_container.html(response);
},
error:function() {
alert("There was an error while fetching the data.");
}
});
});
});

Note that you have to use a URL when calling the .php file, not the absolute path on the server as you would when using PHP's include(). Depending on where you put the script, use either $(...) or jQuery(...).

Now we have to insert the button that is calling AJAX and of course the container where the returned content is being inserted. Since you didn't say where it is being displayed, I just put it in the top of the admin area for now:

function display_ajax_button() {
?>
<input type="button" value="Fetch data" id="fetch-data" />
<div id="fetched-data-content"></div>
<?php
}
add_action("admin_init", "display_ajax_button");

Finally, we create the PHP script itself. I've just copied your code and saved it in the same directory as defined in the jQuery.ajax() URL parameter:

<?php
global $wpdb;
$rows = $wpdb->get_results("SELECT postid from `wp_school_post`");
echo "<table class='wp-list-table widefat fixed'>";
echo "<tr><th>ID</th><tr>";
foreach ($rows as $row ){
echo "<tr>";
echo "<td>$row->postid</td>";
echo "</tr>";}
echo "</table>";
?>

That should be the simpliest approach. Open the admin page and give it a try. Let me know if it worked or not.

How do I use Ajax in a Wordpress plugin?

Use the native methods that Wordpress provides to you to leverage ajax requests.

In your plugin file, we need to add a couple actions so that we can send ajax requests through and have them parsed by the admin-ajax.php file.

add_action('wp_ajax_nopriv_ajax_request', 'ajax_controller');
add_action('wp_ajax_ajax_request', 'ajax_controller');

Now we build out an ajax controller in our plugin file. The purpose of this is to act as a controller that will switch it's output based on the FN parameter supplied by the ajax request (more on this later)

function ajax_controller(){
$ret = ''; //our return variable
switch($_REQUEST['fn']):
case 'status' :
$ret = update_status($_REQUEST['status']);
break;
endswitch;
echo $ret;
die(); //this makes sure you don't get a "1" or "0" appended to the end of your request.
}

Please note that the update_status() function was created to encapsulate your above php code.

Now we have the actions bound, and a controller that we can use endlessly to retrieve data. We just need to make a couple modifications to the ajax call. First, we can use ternary assignment for the 'rent/sale' switch, as opposed to 2 ajax calls, which will clean things up. Second, we need to change the url address to the /wp-admin/admin-ajax.php file.

var $status = (this.value == "sale") ? this.value : 'rent';
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'ajax_request',
fn : 'status', //this is the $_REQUEST['fn'] from above
status : $status },
success: function(data){
alert('Sale' + data['min']['data'][0]);
}
});

The action parameter is required, the fn is a result of my coding principles. The action attribute must directly match what comes after add_action('wp_ajax_nopriv_ and add_action('wp_ajax_.

This should resolve it.

Converting Javascript data to PHP using ajax in wordpress plugin development

Change add_action('wp_ajax_php_test_num', 'retrieve_test_number'); to add_action('wp_ajax_php_test', 'retrieve_test_number');. check below code.

HTML

<p id="num"></p>

Javascript

jQuery(document).ready(function($){
let numTest = '75';
jQuery.ajax({
url: php_data.ajaxurl,
data: {
'action': 'php_test',
'php_test': numTest
},
success: function(data){
console.log('happy');
$('#num').html(data);
}
});
});

PHP

function retrieve_test_number(){
if (isset($_REQUEST)){
$num = $_REQUEST['php_test'];
echo 'This is our JS variable: ' . $num;
}
die();
}
add_action('wp_ajax_php_test', 'retrieve_test_number');
add_action( 'wp_ajax_nopriv_php_test', 'retrieve_test_number' );

Tested and works.

Sample Image

Wordpress: how to call a plugin function with an ajax call?

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

AJAX Using PHP File in Wordpress Plugin

Doing ajax in WordPress should all be sent to /wp-admin/admin-ajax.php,
to do that, in your plugin's main file or the index.php file,
register your ajax action like this:

// let's do the ajax thing here
add_action( 'wp_ajax_theNameOfMyCustomAjax', 'theFunctionThatMyAjaxWillCall' );

function theFunctionThatMyAjaxWillCall() {
// include your ajax file here, in this case
// I assumed that we placed the gethint.php in
// /wp-content/plugins/yourpluginname/gethint.php
include( plugin_dir_path( __FILE__ ).'gethint.php' );

// don't forget to add "die;" every time you return a response to your ajax
//Example: echo $hint ?? "no suggestion"; die;

// or you can add the termination code right here
die; // this will prevent the ajax response to have 0 in the end.

}

Now, in your javascript, instead of calling the filename of your ajax file, you can now use the global ajaxurl javascript variable like this:

xmlhttp.open("GET", ajaxurl+"?action=theNameOfMyCustomAjax&q=" + str, true);

How to call ajax in Wordpress

In backend there is global ajaxurl variable defined by WordPress itself.

This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

Good way to do this is to use wp_localize_script.

Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:

function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

After localizing your JS file, you can use my_ajax_object object in your JS file:

jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: formData,
success: function(msg){
console.log(msg);
}
});

How to call wordpress plugin function with ajax

To call java script function in hyperlink then below is the simple example;

<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>

<a href="javascript:myFunction('You clicked!')">My link</a>

Simple WordPress Ajax Example: https://gist.github.com/devinsays/69a305053e35a10584f94d6011bba2d6



Related Topics



Leave a reply



Submit