Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. function aj_ajax_demo_shortcode() {
  2. return '<h4>Shortcode</h4>';
  3. }
  4. add_shortcode( 'ajax_demo', 'aj_ajax_demo_shortcode' );
  5.  
  6. add_action( 'wp_ajax_nopriv_aj_ajax_demo', 'aj_ajax_demo_process' );
  7. add_action( 'wp_ajax_aj_ajax_demo', 'aj_ajax_demo_process' );
  8. function aj_ajax_demo_process() {
  9. wp_send_json((object) array('msg' => 'hello world'));
  10. }
  11.  
  12. add_action( 'wp_enqueue_scripts', 'aj_enqueue_scripts' );
  13. function aj_enqueue_scripts() {
  14. wp_enqueue_script(
  15. 'aj-demo',
  16. plugin_dir_url( __FILE__ ) . 'aj-demo-ajax-code.js'
  17. );
  18.  
  19. wp_localize_script(
  20. 'aj-demo',
  21. 'aj_ajax_demo',
  22. array(
  23. 'ajax_url' => admin_url( 'admin-ajax.php' ),
  24. 'aj_demo_nonce' => wp_create_nonce('aj-demo-nonce')
  25. )
  26. );
  27. }
  28.  
  29. fetch(aj_ajax_demo.ajax_url, {
  30. method: 'POST',
  31. data: {
  32. action : 'aj_ajax_demo',
  33. nonce : aj_ajax_demo.aj_demo_nonce,
  34. }
  35. }).then(response => {
  36. if (response.ok) {
  37. response.json().then(response => {
  38. console.log(response);
  39. });
  40. }
  41. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement