Ajax call on new site with jupiterx theme getting 400 response

Question

You will need to use and pass a nonce when accessing admin-ajax

Enqueue script with nonce:

$params = array(
  'ajaxurl' => admin_url('admin-ajax.php', $protocol),
  'ajax_nonce' => wp_create_nonce('any_value_here'),
);
wp_localize_script( 'my_blog_script', 'ajax_object', $params );

ajaxurl – This is the absolute address, taking into account http:// or https://, to your ajax processing script. This script is in the wp-admin folder, but can be used for front end ajax scripts as well.

ajax_nonce – This is our nonce that we check in our ajax function. Notice how I used the string ‘any_value_here’ within the wp_create_nonce function… You can use any string, but be sure to remember what you use, because we will need to use the same string when we check the AJAX nonce.

Use Ajax Object in AJax Call:

$.ajax({
  type : "post",
  dataType : "json",
  url : ajax_object.ajaxurl,
  data : 'action=get_posts_commented&email="+user_email+"&security='+ajax_object.ajax_nonce,
  success: function(response) {
    // You can put any code here to run if the response is successful.

    // This will allow you to see the response
    console.log(response);
  }
});

Check nonce in php function:

add_action('wp_ajax_get_posts_commented', 'get_posts_commented');
add_action('wp_ajax_nopriv_get_posts_commented', 'get_posts_commented');
function get_posts_commented(){
  check_ajax_referer( 'any_value_here', 'security' );

  $email = urldecode($_POST['email']);

  global $wpdb;
  $results = $wpdb->get_results($wpdb->prepare("
    SELECT
      comment_post_ID
    FROM
      {$wpdb->comments}
    WHERE
      comment_type="" AND comment_approved = 1 AND comment_author_email="%s"";,
    $email), ARRAY_A);

  echo json_encode($results);

  exit;
}

Reference: https://eric.blog/2013/06/18/how-to-add-a-wordpress-ajax-nonce/

Also great tutorial: https://www.youtube.com/watch?v=DNCPX5uuUBk

0
Geoff_S 4 months 2022-03-16T20:18:36-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse