简体   繁体   中英

Ajax not working in front end of wordpress plugin shortcode

Hi this my code for wordpress plugin

function my_action_callback() {
      check_ajax_referer( 'my-special-string', 'security' );

      $whatever = intval( $_POST['whatever'] );
      $whatever += 10;
      echo $whatever;
      die(); 
    }
    add_action( 'wp_ajax_my_action', 'my_action_callback' );
    add_shortcode('my_products','my_shortcode');

        function my_shortcode($atts)
        {
            extract(shortcode_atts(array(
                'id'=>''       
            ), $atts));
         ob_start();

         wp_enqueue_script( 'my-script', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
         wp_localize_script( 'script-name', 'MyAjax', array(
             'ajaxurl' => admin_url( 'admin-ajax.php' ),
             'security' => wp_create_nonce( 'my-special-string' )
          ));
        }

example.js code

jQuery(document).ready(function($) {

  var data = {
    action: 'my_action',
    security : MyAjax.security,
    whatever: 1234
  };

  $.post(MyAjax.ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
  });
});

It does not alert any values. why? my shortcode [my_products]

You need to localize the script first before enqueuing it, also you are currently localizing script-name whilst enqueueing my-script .

Try this:

function my_shortcode($atts)
        {
            extract(shortcode_atts(array(
                'id'=>''       
            ), $atts));
         ob_start();
         // Register the script first.
         wp_register_script( 'script-name', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
         // Now localize it.
         wp_localize_script( 'script-name', 'MyAjax', array(
             'ajaxurl' => admin_url( 'admin-ajax.php' ),
             'security' => wp_create_nonce( 'my-special-string' )
          ));
          // Now enqueue the script
          wp_enqueue_script( 'script-name')
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM