how to use ajax in plugin admin area?

Please, avoid the use of require(‘../../../wp-load.php’); and things like that as suggested in other answers. You should always use the WordPress AJAX way. It is really easy and you will have all WordPress engine loaded in your PHP script.

Just three considerations:

  1. You have to send the ajax request to …wp-admin/admin-ajax.php. ajaxurl is a javascript var that is always defined in the admin area and it contains the correct url to the admin-ajax.php file in the current WordPress instalation. You can use ajaxurl directly in your javascript in the admin area. I’ve seen that you send the ajax request to a different URL.
  2. In the sent data you have to inclue the action var. The action var contains the name of a previously registered PHP function by your plugin/theme. This function will handle the ajax request. I’ve read your code and you defined the ajax function in your PHP but the action is missed in your javascript.
  3. The example bellow is for the admin area as you asked about admin area. In the frontend is a little different but still really easy; if you need a example to make the ajax request in the frontend just say and I will post it.

Example:

In your PHP (plugin/theme):

add_action('wp_ajax_my_action', 'my_ajax_action_function');

function my_ajax_action_function(){
  
    $response = array();
    if ( ! empty($_POST['param'] ) ) {
         $response['response'] = "I've get the param and its value is " . $_POST['param'] . ' and the plugin url is ' . plugins_url();
    } else {
         $response['response'] = "You didn't send the param";
    }

    header( "Content-Type: application/json" );
    echo json_encode($response);
 
    // Don't forget to always exit in the ajax function.
    exit();

}

Your backend javascript should be something like this (remember that ajaxurl is always defined by WordPress in the admin area):

jQuery.ajax({
    type: "POST",
    url: ajaxurl,
    data: { action: 'my_action' , param: 'st1' }
  }).done(function( msg ) {
         alert( "Data Saved: " + msg.response );
 });

Leave a Comment