rob.m
rob.m

Reputation: 10581

How to load wp ajax for not logged users?

I understand I should be using wp_ajax_nopriv as per the doc says but I am not sure how tho.

On the front end I do:

var ajaxscript = { ajax_url : '<?php echo admin_url("admin-ajax.php"); ?>' };   
$.ajax({
  url: ajaxscript,
  type: 'post',
  dataType: 'json',
  data: { action: 'data_fetch', dates: datesSearch },
  success: function(data) {
    ...
  }
});

I know I could define the url in function like:

  function myAjaxUrl() {
     echo '<script type="text/javascript">
             var ajaxurl = "' . admin_url('admin-ajax.php') . '";
           </script>';
  }
  add_action('wp_head', 'myAjaxUrl');

And that would make the ajax call on the front end like:

$.ajax({
  url: ajaxurl...

But how would I use the wp_ajax_nopriv in order to be able to access wp-ajax for not logged in users?

Upvotes: 0

Views: 1753

Answers (2)

gjzim
gjzim

Reputation: 643

All you need to do is just register your function to a hook named as wp_ajax_nopriv_{your_function_name}

So, for your case, add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' ); should do the trick.


Registering an ajax function in WordPress:

1. Registering an ajax function in WordPress: You can add this in the theme functions.php file.

// Simple Ajax function
add_action( 'wp_ajax_nopriv_simple_ajax_func', 'simple_ajax_func' );
add_action( 'wp_ajax_simple_ajax_func', 'simple_ajax_func' );

function simple_ajax_func() {
  echo json_encode(array('success' => true));

  wp_die();
}

2. Calling that ajax function from JavaScript:

var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';

jQuery.ajax({
  url : ajax_url,
  type : 'post',
  data : {
    action : "simple_ajax_func",
  },
  success : function( response ) {
    console.log('Success');
  }
});

Upvotes: 4

Lincoln Lemos
Lincoln Lemos

Reputation: 428

you misunderstand the wp_ajax action.

You must create a PHP function inside your theme using the wp_ajax filter.

add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'my_ajax_foobar_handler' );

// This is the function that you will fire when your ajax code hits the admin_url('admin-ajax.php')
function my_ajax_foobar_handler() {
   // Make your response and echo it.

   // Don't forget to stop execution afterward.
   wp_die();
}

So, for the WP admin ajax understand that need to fire this function, you must pass it inside your ajax request.

//Note that the action here is what cames after the wp_ajax PHP function
var my_php_ajax_action_name = 'foobar'
$.ajax({
  url: ajaxurl,
  type: 'post',
  dataType: 'json',
  data: { action: my_php_ajax_action_name, dates: datesSearch },
  success: function(data) {
   // ...
  }
});

Upvotes: 0

Related Questions