0

I am trying to use wp-ajax inside another sub-domain, but I am getting a CORS error. To solve this I used add_action with the send_headers hook:

function cors_header () {
    header('Access-Control-Allow-Origin: *');
}
add_action('send_headers', 'cors_header');

But this didn't work either. This is all my code:

function get_user_id () {
    $email = $_POST['email'];
    if (!$email) {
        status_header(401, 'Unauthorized Request');
        exit();
    }
    $form_id = 25;
    $search_criteria = array(
        'status'     => 'active',
        'field_filters' => array(
            array(
                'key' => '2', 'value' => $email,
            )
        )
    );
    
    $entries = GFAPI::get_entries($form_id, $search_criteria);
    
    add_action('send_headers', 'cors_header');
    
    echo json_encode($entries[0]['created_by']);
    exit();
}

function cors_header () {
    header('Access-Control-Allow-Origin: *');
}
add_action("wp_ajax_nopriv_user_id", "get_user_id");
add_action("wp_ajax_user_id", "get_user_id");

1 Answer 1

0

The send_headers hook is not fired during an (admin) AJAX request (because there is no "main WordPress query", so the wp() function doesn't run and therefore that hook doesn't get fired either), hence if you want to send the CORS header (and any other headers), then just call header() from within your AJAX callback, like so:

function get_user_id() {
    header( 'Access-Control-Allow-Origin: *' );

    // ... the rest of your code
}

And BTW, "get_user_id" is a very generic name, so use a unique one like prefixing it with "my_plugin_ajax_" as in my_plugin_ajax_get_user_id.

Also, there is wp_send_json() that you can use to send a JSON response from your AJAX callback.

And last but not least, consider using the REST API instead which has CORS enabled by default and the response is also in JSON (so you basically would only need to return your output, e.g. return $entries[0]['created_by'];). See the REST API handbook for more details.

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.