Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax in Wordpress plugin

I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.

<script type="text/javascript" >
jQuery(document).ready(function($) {

var data = {
    action: 'my_action',
    whatever: '1234'
};


jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data,   function(response) {
    alert(response);
});
});
 </script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' ); 




function my_action_callback() {

echo "test";
die();

}

what am I doing wrong?

like image 991
Waqar Avatar asked Jul 12 '11 03:07

Waqar


People also ask

Can I use AJAX in WordPress?

How AJAX Works In WordPress Natively # Because AJAX is already used in WordPress' back end, it has been basically implemented for you. All you need to do is use the functions available. Let's look at the process in general before diving into the code.

Where do I put AJAX code in WordPress?

Here's what the process for using Ajax in WordPress looks like: The user triggers an Ajax request, which is first passed to the admin-ajax. php file in the wp-admin folder. The Ajax request needs to supply at least one piece of data (using the GET or POST method).

How do I get AJAX data in WordPress?

In WordPress, we send all AJAX request to a common URL, then wordpress internally calls the corresponding method according to the parameters which we have sent with the request. You can use the admin_url( 'admin-ajax. php' ) function of WordPress to get this url.

How can I tell if WordPress AJAX is working?

To see if the current request is an AJAX request sent from a js library ( like jQuery ), you could try something like this: if( ! empty( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) == 'xmlhttprequest' ) { //This is an ajax request. }


2 Answers

You have to put the add_action at the complete bottom of your file or else it won't find the callback function

like image 122
Alexcp Avatar answered Oct 16 '22 22:10

Alexcp


Try to change :

jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data,   function(response)

To :

jQuery.post(ajaxurl, data, function(response) 

And check if it is working on the admin side first. It should work fine.

like image 25
Obmerk Kronen Avatar answered Oct 16 '22 23:10

Obmerk Kronen