0

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?

1
  • 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
    Mar 10 at 23:39

1 Answer 1

1

You 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');
1
  • Perfect, thank you
    – user13286
    Mar 11 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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