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);
}
});
ajax call in wordpress
this is demo of Custom AJAX
with WordPress..
Bellow script is HTML
<div class="ajax-column">
<div class="options">
<select id="custom-change">
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
<option value="val4">Val 4</option>
</select>
</div>
<div id="ajax_result_form">
<div id="ajax_text_result"></div>
<div class="row">
<div class="" id="ajax_result"> </div>
</div>
</div>
</div>
This is JS Script as my-ajax-script.js
jQuery(document).ready(function(e) {
jQuery('#custom-change').change(function(e) {
var text = jQuery('#custom-change').val();
jQuery.ajax({
type: "POST",
url: admin_url,
dataType:"json",
data: {
action: 'data_custom_ajax',
text: text,
},
cache: false,
success: function(data){
if(data['data_result']==''){
jQuery('#ajax_result').hide();
}
else{
jQuery('#ajax_result').css('display','block');
jQuery('#ajax_result').html(data['data_result']);
}
}
});
});
});
This is WordPress script as theme's functions.php file.
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' );
/* Custom Ajax */
function data_custom_ajax(){
$custom_val = $_POST['text'];
$testdomin_query = new WP_Query($testdomin_args_search);
$testdomin_result='';
if(!empty($custom_val)){
$testdomin_result = _e('Your Action hear','textdomin');
}
else
$testdomin_result = _e('Not found','textdomin');
echo json_encode(array("data_result"=>$testdomin_result));
die;
}
add_action('wp_ajax_nopriv_data_custom_ajax', 'data_custom_ajax');
add_action('wp_ajax_data_custom_ajax', 'data_custom_ajax');
Calling a function from ajax in WordPress
The action you're calling should have the same name as the action you set in your function.php (wp_ajax_category_select_list
, without the prefix wp_ajax_
). The action in your js should be: action: 'category_select_list'
You should also use the function wp_die()
instead of the exit()
.
More on the subject: https://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Administration_Side
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.
Call any Wordpress PHP function via AJAX
Okay, let's write simplified example for this.
Here is a sample for functions.php:
add_action('wp_ajax_nopriv_sayhello', 'say_hello_function');
add_action('wp_ajax_sayhello', 'say_hello_function');
function say_hello_function(){
echo 'hello';
exit();
}
And this is front-end part:
<button class="my_button" type="button" role="button">Click Me</button>
<script>
jQuery(".my_button").click(function(){
jQuery.get(ajaxurl,{'action': 'sayhello'},
function (msg) { alert(msg);});
});
</script>
UPD:
To display returned data in your website content:
<script>
jQuery(".my_button").click(function(){
jQuery.get(ajaxurl,{'action': 'sayhello'},
function (msg) { jQuery(".result_area").html(msg);});
});
</script>
To get above code working you need to have a div with "result_area" class.
<div class="result_area"></div>
Ajax call include not works in Wordpress
You should use relative includes from their own file, otherwise, it will run from the current path. To force this you can use __DIR__
and start with a slash
plugin.php
function process(){
include_once(__DIR__.'/processes/process.php' );
}
add_action('wp_ajax_process', 'process' );
process.php
include_once(__DIR__.'/../snippets.php');
//here not includes 'snippets.php'
Also, you forgot the semicolumn ;
in process.php
Ajax with wordpress, 400 bad request
I was posting files and there were to big,
So in /etc/php/7.0/apache2/php.ini
increase
upload_max_filesize = 13M
post_max_size = 27M
Related Topics
How to Call PHP Functions by JavaScript
Retrieve the Position (X,Y) of an HTML Element
Get Element from Within an Iframe
Onclick to Get the Id of the Clicked Button
Disabling Browser Print Options (Headers, Footers, Margins) from Page
How to Check Whether Google Maps Is Fully Loaded
Launch Bootstrap Modal on Page Load
Show Datalist Labels But Submit the Actual Value
Get Page Generated With JavaScript in Python
Selecting All Text in HTML Text Input When Clicked
Html Text Input Allow Only Numeric Input
How to Get the Selected Radio Button'S Value
Submit Two Forms With One Button
How to Check If a Specific Pixel of an Image Is Transparent
How to Get the Entire Document HTML as a String
JavaScript; Communication Between Tabs/Windows With Same Origin
Persisting the Changes of Range Objects After Selection in Html