aiiwa
aiiwa

Reputation: 611

wordpress adding plugin for ajax

i am new to wordress. trying to test creating a plugin to combine my js and ajax for a module. I did the following:

[Not sure if i need to add anything in admin-ajax.php.]

  1. created my new plugin under wp-content/pluging/test-plugin
  2. created 2 files: test.php and test.js
  3. test.php content as the following:

    /** * Plugin Name: Test */

    add_action("wp_ajax_my_test", "my_test");
    
    add_action("wp_ajax_nopriv_my_test", "my_test");
    
    function my_test()
    {
    echo "in ajax";
    }
    add_action( 'init', 'test_script_enqueuer' );
    
    
    function test_script_enqueuer() {
    
        wp_register_script( "test", WP_PLUGIN_URL.'/my_plugin/test.js', array('jquery') );
        wp_localize_script( 'test', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'test');
    }
    
  4. test.js code as the following:

    $(document).ready(function()
            {    
    console.log('in js!');
    

    $('#testDiv').on('click', '#test', function() { console.log('clicked!');

    jQuery.ajax( { type: 'POST', url: myAjax.ajaxurl, data: {
    action: 'my_test' }, dataType: 'json', cache: false, success: function(response) { alert(response); }, error: function(xhr, textStatus, errorThrown) { alert('error'); } }); })

        });
    

Note that I can't even see the "in js!" message in my console.

Upvotes: 0

Views: 44

Answers (1)

Nozifel
Nozifel

Reputation: 545

Change

add_action( 'init', 'test_script_enqueuer' );

to

add_action("wp_enqueue_scripts", "test_script_enqueuer");

But first, try to echoes something from your php file. If nothing happened your file isn't call.

Try then tell me.

Upvotes: 0

Related Questions