WordPress plugin development ajax url not working

jQuery(document).ready(function(e) {
jQuery('#m').click(function()
{
    //jQuery(this).fadeOut();
    var d='<?php echo $plugins;?>';
    jQuery.ajax({url:d,data:{q:10},type:GET,success: function(msg)
    {
        alert(msg);
    }
}
)
});

I have to develop my own plugin, basically WordPress has an admin-ajax file which handles this type of request, so how can I make it request using its own file to handle an Ajax request?

Related posts

Leave a Reply

1 comment

  1. for that you need to do it like this:

    jQuery(document).ready(function($) {
        var data = {
            action: 'my_action',
            whatever: ajax_object.we_value      // We pass php values differently!
        };
        // We can also pass the url value separately from ajaxurl for front end AJAX implementations
        jQuery.post(ajax_object.ajax_url, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
    

    and in your handler file :

    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
    }
    

    add_action( ‘admin_enqueue_scripts’, ‘my_enqueue’ );
    function my_enqueue($hook) {
    if( ‘index.php’ != $hook ) return; // Only applies to dashboard panel

    wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));
    
    // in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
    wp_localize_script( 'ajax-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $email_nonce ) );
    

    }
    And Do not forget to enqueue your script :

    add_action( 'admin_enqueue_scripts', 'my_enqueue' );
    function my_enqueue($hook) {
        if( 'index.php' != $hook ) return;  // Only applies to dashboard panel
    
        wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));
    
        // in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
        wp_localize_script( 'ajax-script', 'ajax_object',
                array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $email_nonce ) );
    }