0

I developed my ajax functionality while using a WordPress admin account and everything worked correctly. Testing as a user, however, I cannot get the functionality to call - and pressing the "submit" button of my form can cause the page to timeout and throw a 503 error. (I only want users to be able to access the call.)

I have tried all user roles other than admin, but none work properly. My ajax functionality queries my database and also inserts a new record.

I believe I must be calling on ajax incorrectly for any role other than admin - and that the fault must lie in my script, prior to reaching my success or error alerts.

I have embedded my php/html onto my page.

What have I done incorrectly?

HTML/JS

<!DOCTYPE html>
<html>
  <title>Withdraw Credit</title>
  <body>
    <form id="requestcreditform">
      <h1>Withdraw Credit</h1>

      <div class="formcontainer">
      <div class="container">
        <label for="credit_requested"><strong>Credit Requested</strong></label>
        <input type="number" name="creditreq" placeholder="5000" id="creditreq" required>
        <p>This change will be reflected to your account upon submission and your credit will be processed shortly afterwards.  All loans begin with a 20% interest rate, which compounds annually.  Please verify the requested credit is correct prior to hitting the "Submit" button.  Thank you.
        </p>
      </div>
      <button id="submit_button" type="submit"><strong>Submit</strong></button>
      </div>
    </form>
  </body>
</html>

<script>

(function($){
  $('#requestcreditform').submit( function(event) {
  
    event.preventDefault();
    
    var endpoint = '<?php echo admin_url('admin-ajax.php');?>';
   
    var form = $('#requestcreditform').serialize();
    
    var formdata = new FormData;
    
    formdata.append('action', 'requestcredit');
    formdata.append('requestcredit', form);
    
    $.ajax(endpoint, {
      type: 'POST',
      data: formdata,
      processData: false,
      contentType: false,
 
      success:function(res) {
        alert(res.data);
        location.reload();
      },
      
      error: function(err) {
       
      }
    
    })
  })
})(jQuery)

</script>

Functions.php

add_action("wp_ajax_requestcredit", "request_credit1");
function request_credit1() {
    include ('wp-load.php');
    global $current_user;
    global $wpdb;
  
    //pull user data
    $current_user = wp_get_current_user();
  
    $name = $current_user->firstname . " " . $current_user->lastname;
    $email = $current_user->user_email;
    $phone = $current_user->phone;
    $approved_credit = $current_user->approved_credit;
    
    //POST
    $formdata = [];
    
    wp_parse_str($_POST['requestcredit'], $formdata);
    
    $credit_requested = "";
    foreach($formdata as $index => $field) {
        $credit_requested = $field;
        
    }
    
    //TRANSACTION TABLE
    //remaining credit
    $credit_total = $wpdb->get_var("SELECT SUM(credit_amount) AS total FROM transaction_history WHERE user_id = ".$current_user->id." AND (is_paid <> 1 OR is_paid IS NULL)"); 
    $remaining_credit = $current_user->approved_credit - $credit_total;
    
     if ($credit_requested > $remaining_credit) {
        wp_send_json_success('Request failed.  Please ensure you have entered a number within your remaining credit');
        exit;
    }
    //if requested amount is allowed
    else {
        //insert withdrawn credit into transaction history
        $wpdb->insert('transaction_history', array(
            'user_id' => $current_user->id,
            'credit_timestamp' => current_time( 'mysql' ),
            'credit_amount' => $credit_requested
        ));
        
        //MAIL
        //admin email - dynamic
        $admin_email = get_option('admin_email');

        //headers
        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        $headers[] = 'From:' .$admin_email;

        //Set the recipient email address.
        $recipient = "[email protected]";

        //Set the email subject.
        $subject = "New Request from $name";

        // Build the email content.
        $email_content = 'Name: '.$name.'<br /><br />';
        $email_content .= 'Email: '.$email.'<br /><br />';
        $email_content .= 'Phone #: '.$phone.'<br /><br />';
        $email_content .= 'Approved Credit: '.$approved_credit.'<br /><br />';
        $email_content .= 'Total Remaining Credit: '.$remaining_credit.'<br /><br />';
        $email_content .= 'Requested Credit: '.$credit_requested.'<br /><br />';

        try {
          if (wp_mail($recipient, $subject, $email_content, $headers)) {
            wp_send_json_success('Credit Request for $'.$credit_requested. ' sent.');
          }
          else {
             wp_send_json_success('Credit Request failed.  Please ensure you have entered a number within your remaining credit');
          }
        } catch (Exception $e) {
           wp_send_json_success($e->getMessage());
        }
     }
}
7
  • Please edit your question to include the code you've used to load the JS code in WordPress.
    – Pat J
    Commented Apr 14, 2023 at 3:21
  • Thanks, Pat. I also included the relevant functions.php code. Also, while I added this to my post, I only want users to be able to make this call - hence why I didn't add a no_priv action.
    – jgdhnds
    Commented Apr 14, 2023 at 3:56
  • include ('wp-load.php'); - why did you add that, and what file is that? Because WordPress will automatically load itself, so no need to manually load it. Also, I don't see why would you need to call .serialize(), because you could just do var form = $('#requestcreditform')[0]; var formdata = new FormData( form ); (and remove the formdata.append('requestcredit', form);), and in PHP, use $_POST['creditreq'] to get the credit requested. And, "cause the page to timeout and throw a 503 error" - are you sure it's caused by your script, and what exactly is the response headers and body?
    – Sally CJ
    Commented Apr 14, 2023 at 7:26
  • Have you also considered using the modern REST API instead, e.g. by using a custom endpoint like my-plugin/v1/request-credit?
    – Sally CJ
    Commented Apr 14, 2023 at 7:29
  • 1
    The issue is jQuery was not loading for non-admins. Should anyone encounter the same issue, I was able to find the problem by looking at my inspection console (in my browser) and resolve the issue by adding the following code to my functions.php file function add_jquery() { wp_enqueue_script( 'jquery' ); } add_action('init', 'add_jquery');
    – jgdhnds
    Commented Apr 18, 2023 at 21:12

2 Answers 2

0

There are several potential reasons for this issue:

Permissions: Non-admin users may not have the necessary permissions to access the admin-ajax.php file, which is being called in your AJAX request. Make sure that the required permissions are set for the user roles other than admin.

Authentication: Non-admin users may not be authenticated to access the admin-ajax.php file. You may need to check if the user roles other than admin have the necessary authentication to access the AJAX endpoint.

Capability check: You may have implemented a capability check in your server-side code that restricts the AJAX functionality to only admin users. Make sure that the capability check allows the required user roles to access the AJAX endpoint.

URL issue: The URL used in your AJAX request () may not be correct for non-admin users. Make sure that the URL is valid and accessible for all user roles.

Error handling: Your error handling in the AJAX request is incomplete (alert statement is incomplete). Make sure that you have proper error handling in place, such as logging errors to the server or displaying meaningful error messages to users, to help diagnose and resolve the issue.

Plugin/Theme conflict: It's possible that there could be a conflict with a plugin or theme that is affecting the AJAX functionality for non-admin users. Try deactivating plugins or switching to a default theme to see if the issue persists.

You may need to investigate and debug further to identify the specific issue. Checking server-side code, permissions, authentication, capability checks, URLs, and error handling can be helpful in resolving this issue.

0

The issue is jQuery was not loading for non-admins.

Should anyone encounter the same issue, I was able to find the problem by looking at my inspection console (in my browser) and resolve the issue by adding the following code to my functions.php file:

function add_jquery() {
    wp_enqueue_script( 'jquery' );
}
add_action('init', 'add_jquery');
1
  • Glad you could find the problem source and a solution as well, however, you should not use the init hook and instead, use the wp_enqueue_scripts hook. BTW, you should've tagged my username, @jgdhnds, so that I get notified when you replied to my comment :)
    – Sally CJ
    Commented Apr 21, 2023 at 16:15

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.