وردپرس

AJAX WordPress JSON response always preceded by data request as array


Hi everyone,

I am new to developing and I am running on a very difficult issue.

I am doing an AJAX call on wordpress.

there are 2 very strange things I notice.

  1. whenever I set content-type to application/json;charset=UTF-8 I always get 400 (bad request) error
  2. Even though setting Content-type to application/x-www-form-urlencoded I get status code success 200 in my response there is something I can’t understand nor fix.

I always get before my JSON response an array of the data I sent from the client to the server.

here is my client ajax call

sendApiRequestButton.addEventListener("click", function () {
            var email = emailInput.value;
  
            
              var xhr = new XMLHttpRequest();
              console.log('ajax_url:', ajax_object.ajax_url);
              xhr.open('POST', ajax_object.ajax_url, true);
              
              xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  
              xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
    
                  console.log(xhr.responseText)
                  
                }
              };
              var requestData="action=send_api_request&data=" + encodeURIComponent(email);
  
            xhr.send(requestData)
            } 
    );

here my server-side ajax action

function send_api_request() {
    
    $email = sanitize_email($_POST['data']);

    $api_endpoint="***";
    $api_key = '***';

    $request_data = array(
        'email' => $email
    );

    $response = wp_safe_remote_post($api_endpoint, array(
        'headers' => array(
            'Content-Type' => 'application/json',
            'X-Auth-Token' => 'api-key ' . $api_key,
        ),
        'body' => json_encode($request_data),
    ));

    if (!is_wp_error($response)) {

        $api_response = wp_remote_retrieve_body($response);
        
    } else {
        $api_response="API request failed";
    }
error_log($api_response);
    wp_send_json($api_response);
}
add_action('wp_ajax_send_api_request', 'send_api_request');
add_action('wp_ajax_nopriv_send_api_request', 'send_api_request');

// Add this code to your theme's functions.php or a custom plugin
function enqueue_get_response_script() {
    wp_enqueue_script('get-response-js', plugins_url('js/get-response-api.js', __FILE__), array(), null, true);
    wp_localize_script('get-response-js', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_get_response_script');

the server receive fine the request with the email field.

and generate a correct JSON response {message: success} that I checked logging the JSON response right before calling wp_send_json

anyway something very strange is happening at line wp_send_json($api_response);

since on my client I receive the JSON message but ALWAYS NO MATTER WHAT preceded by my request data (email) as Array before the JSON as such

“Array
(
[email] => [email protected]
)
{message: success}”

that means that if I try to JSON.parse the response it fails.

I could manipulate the response to get just the JSON but there is something very wrong here I’d like to understand.

why my response has always my data request as array?

and why from the client all request with content-type application/json return 400?

I am developing with Local from Flywheel with nginx web-server PHP version 8.1.9 WordPress version 6.3 on windows 11

I tried to deactivate all my plugins (except mine that I am working on)

I re-installed WordPress

and I am left with trying to get help from you, please, I really don’t understand this.

Thank you

پایان/ مرجع وب و فناوری

مشاهده پاسخ های این مطلب
———————————————
این مطلب از سایت انجمن وردپرس گردآوری شده است و کلیه حقوق مطلق به انجمن وردپرس می باشد در صورت مغایرت و یا بروز مشکل اطلاع دهید تا حذف گردد

منبع: انجمن وردپرس

دکمه بازگشت به بالا