0

I had a few functions I was calling with ajax...basically, everything was working as expected and now it's not. I'm not sure what could be causing this problem.

I have a button on my page like so:

<p class='form-submit' method='post'>
    <input id='$message_id' name='message_read' type='button' onclick=hideMessage($message_id) class='submit button mark-as-read' value= 'Mark as read' />
</p>

When I click the button, the following ajax code executes from js/wp-ajax-calls.js

    jQuery(document).ready(function() { 

       jQuery(".mark-as-read").click(function () {
          console.log('mark as read ajax called');
         jQuery.ajax({
             type: "POST",
             url: "/wp-admin/admin-ajax.php",
             data: {
                action: 'mark_message_as_read',
                message_id: this.id
                 }
             success: function (msg) {
                  console.log('action was successful');
                  console.log(msg);
             },
             error: function (errormessage) {
                  console.log(errormessage);
              }
        });
    });
});

I see the console message I put in there when I click the button.

In my functions.php I have the following function:

add_action('wp_ajax_mark_message_as_read', 'mark_message_as_read');
function mark_message_as_read() {
    echo "<script>console.log('the message function is called');</script>";
    //do stuff
}

I do not see the second console message.

When I check the network tab on my browser, I can see that the ajax requests are generating a 302 response.Interestingly enough, when I log in to my site as the admin user, I get a 200 response and the site behaves exactly as I expect with no issues. I only get the 302 response when I am logged in as a subscriber.

Here are the response headers when I'm logged in as a subscriber:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://localhost
Cache-Control: no-cache, must-revalidate, max-age=0
Connection: Keep-Alive
Content-Length: 1
Content-Type: text/html; charset=UTF-8
Date: Wed, 31 Oct 2018 05:32:40 GMT
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Keep-Alive: timeout=5, max=100
Location: https://localhost/
Referrer-Policy: strict-origin-when-cross-origin
Server: Apache/2.4.18 (Ubuntu)
Strict-Transport-Security: max-age=63072000; includeSubdomains
X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
X-Robots-Tag: noindex

The 'success' always callback gets called from the original ajax request, no matter who I am logged in as.

Happy to provide more info if needed.

Thanks!

14
  • Have you considered using the REST API instead? Easier URLs, and if you do something wrong it tells you in plain english instead of failing mysteriously. Also you shouldn't return <script> tags like that, just return a true or false to indicate if the message was read, and handle the response in the code that made the request in the first place
    – Tom J Nowell
    Commented Oct 24, 2018 at 20:20
  • @TomJNowell I just added the <script> stuff temporarily to see if the function was getting called. I will remove it once the issue is fixed.
    – ellen
    Commented Oct 24, 2018 at 20:51
  • In your jQuery.ajax() call, you're not actually doing anything with the AJAX response.. I.e. You don't have a "success" callback — e.g. jQuery.ajax( {...}).done( function(res){ alert(res); })
    – Sally CJ
    Commented Oct 24, 2018 at 21:52
  • @SallyCJ I have added some callback functions...I will update my post
    – ellen
    Commented Oct 30, 2018 at 22:54
  • @ellen, I believe your AJAX is actually working; however, if you're actually trying to execute the script in the AJAX response (that's coming from your mark_message_as_read() function), then in your $.ajax()'s success callback, append the msg to the DOM and the script would be automatically executed. See this Pen where I got $('body').append(msg); in the success callback.
    – Sally CJ
    Commented Oct 31, 2018 at 2:43

1 Answer 1

0

I figured it out using this previous post:

Issue with front-end ajax, getting a 302 redirect when accessing wp-admin/admin-ajax.php

Basically, I had added an action to prevent subscribers from seeing certain wordpress pages.

  function limit_subscriber_access() {
    $redirect = home_url( '/' );
    if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'edit_posts' ) ))
        exit( wp_redirect( $redirect ) );
}

This was causing the 302 redirect and preventing the $wpdb related code from executing. Here is what I added:

  function limit_subscriber_access() {
    $redirect = home_url( '/' );
    if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'edit_posts' ) ) && !defined('DOING_AJAX'))
        exit( wp_redirect( $redirect ) );
}

I tested and it seems to be working how I wanted.

Thanks to everybody who helped me try to figure it out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.