简体   繁体   中英

Wordpress Ajax Call successful (200) but no response message

I'm using Wordpress, sending an AJAX request from a form on my website to my server but can't see a response message despite status 200. What is missing?

JS in footer

var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
var data = [somedata]

fetch(ajaxurl, {
    method: 'POST',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    dataType:'json',
    credentials: 'include',
    body: 'action=process_request&data='+data
}).then(function (result) {
    console.log(result);
});

PHP

add_action('wp_ajax_process_request', 'process_request');
add_action('wp_ajax_nopriv_process_request', 'process_request');

function process_request() {

    header("Content-type: application/json");
    //do something with data
    echo json_decode('my_response');
    die();
}

Server's response

Response {type: "basic", url: "https://myserver.xyz/wp-admin/admin-ajax.php", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "https://myserver.xyz/wp-admin/admin-ajax.php"
__proto__: Response

You have response body in response.body . Now you have all information about response.

var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
var data = [somedata]

fetch(ajaxurl, {
    method: 'POST',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    dataType:'json',
    credentials: 'include',
    body: 'action=process_request&data='+data
}).then(result => result.json())
  .then(function (result) {
    console.log(result);
});

and sending response function:

add_action('wp_ajax_process_request', 'process_request');
add_action('wp_ajax_nopriv_process_request', 'process_request');

function process_request() {
    //do something with data
    echo json_decode('{"a":1,"b":2,"c":3,"d":4,"e":5}', true);

    wp_die();
}

You can't set headers in this place, this dosen't work. WordPress have a special hook.

In your case:

add_action( 'send_headers', 'addHeader' );
function addHeader() {
    header("Content-type: application/json");
}

In previous I forgot about convert value to a JSON, so I edited answer!

Greetings, plum!

Sources:

WordPress headers hook: https://codex.wordpress.org/Plugin_API/Action_Reference/send_headers

Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Fetch response docs: https://developer.mozilla.org/en-US/docs/Web/API/Response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM