0

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.

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. update my js code. i can see 'in js!' in console. but on click doesn't seem to be triggered, cant see 'clicked!' that i have printed. any idea?
replace $('#testDiv').on('click', '#test', function() { console.log('clicked!'); By $('#testDiv').on('click', function() { console.log('clicked!'); I remove the '#test' in your event.
add die(); after echo "in ajax"; in your function my_test()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.