My theme uses a custom action which expects two arguments. I am trying to call the function in an AJAX call but because I am not passing those arguments I end up getting a 500 error.
The action is formatted like this:
function newsletterSignup($id, $source) {
// code here
}
add_action('wp_ajax_nopriv_newsletter_signup', 'newsletterSignup');
add_action('wp_ajax_newsletter_signup', 'newsletterSignup');
My ajax call looks like this:
$('form').on('submit', function(e) {
e.preventDefault();
var $form = $(this),
fd = new FormData($form[0]);
fd.append('action','newsletter_signup');
fd.append('source','homepage');
$.ajax({
type: 'POST',
url: user_object.ajaxurl,
data: fd,
processData: false,
contentType: false,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
// registered
},
error: function (request, status, error) {
//error
}
});
});
As mentioned, I am getting a 500 error on this request because the action does not include the $id
and $source
arguments. Is it possible to pass arguments into the action via JavaScript?
My theme uses a custom action which expects two arguments. I am trying to call the function in an AJAX call but because I am not passing those arguments I end up getting a 500 error.
The action is formatted like this:
function newsletterSignup($id, $source) {
// code here
}
add_action('wp_ajax_nopriv_newsletter_signup', 'newsletterSignup');
add_action('wp_ajax_newsletter_signup', 'newsletterSignup');
My ajax call looks like this:
$('form').on('submit', function(e) {
e.preventDefault();
var $form = $(this),
fd = new FormData($form[0]);
fd.append('action','newsletter_signup');
fd.append('source','homepage');
$.ajax({
type: 'POST',
url: user_object.ajaxurl,
data: fd,
processData: false,
contentType: false,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
// registered
},
error: function (request, status, error) {
//error
}
});
});
As mentioned, I am getting a 500 error on this request because the action does not include the $id
and $source
arguments. Is it possible to pass arguments into the action via JavaScript?
- a 500 error is a generic something went wrong message from the server, it's not the actual error. You need to look in your PHP error log to find the error message. Also, is there a reason you used the old legacy AJAX API instead of the modern REST API for your AJAX requests? – Tom J Nowell ♦ Commented Mar 10, 2022 at 23:39
1 Answer
Reset to default 1You can't pass arguments to wp_ajax_
callbacks. You need to pass the data via the data
property of the AJAX request. Then you get those values with $_POST
and pass them to a function:
function newsletterSignupAjax() {
$id = $_POST['id'];
$source = $_POST['source'];
/* Make sure to validate and sanitize those values. */
newsletterSignup( $id, $source );
}
add_action('wp_ajax_nopriv_newsletter_signup', 'newsletterSignupAjax');
add_action('wp_ajax_newsletter_signup', 'newsletterSignupAjax');