dimanche 18 octobre 2015

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!'); 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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire