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());
}
}
}
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 dovar form = $('#requestcreditform')[0]; var formdata = new FormData( form );
(and remove theformdata.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?my-plugin/v1/request-credit
?function add_jquery() { wp_enqueue_script( 'jquery' ); } add_action('init', 'add_jquery');