Ajax w Wordpressie - VanillaJS zamiast jQuery

0

Dzień dobry,

Dlaczego poniższy kod w jquery działa

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: 'action=blog_1&blog_posts_type=' + blog_posts_type + '&nonce=' + nonce + '&page=' + page,
            success:function(data) {
                console.log(data);
            },
            error: function(errorThrown){
                console.log(errorThrown);
            }
        }); 

a kod w JS nie działa

var request = new XMLHttpRequest();

request.open('POST', ajaxurl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
    if (this.status >= 200 && this.status < 400) {

           console.log(this.responseText);

    } else {
        // Response error
    }
};
request.onerror = function() {
    // Connection error
};
request.send('action=blog_1&blog_posts_type= + blog_posts_type + &nonce= + nonce + &page= + page');

Po pierwsze wyskakuje błąd jakby token nonce był zły, a gdy wpiszę w request.send odpowiedni token dla nonce to console.log wraca pustą linię a console.log(request); zwraca

XMLHttpRequest
​
mozAnon: false
​
mozSystem: false
​
onabort: null
​
onerror: function onerror()
​
onload: function onload()
​
onloadend: null
​
onloadstart: null
​
onprogress: null
​
onreadystatechange: null
​
ontimeout: null
​
readyState: 4
​
response: ""
​
responseText: ""
​
responseType: ""
​
responseURL: "http://localhost:8080/wordpress/wp-admin/admin-ajax.php"
​
responseXML: null
​
status: 200
​
statusText: "OK"
​
timeout: 0
​
upload: XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, … }
​
withCredentials: false
​
<prototype>: XMLHttpRequestPrototype { open: open(), setRequestHeader: setRequestHeader(), send: send(), … }
functions.js:392:12

Wordpress to bardzo popularny CMS więc mam nadzieję że ktoś miał podobny problem i podzili się rozwiązaniem.

0

Jeśli użyję jakiejkolwiek adresu strony w request.open() i wyświetlę to przy użyciu console.log(request.response); to działa tak jak powinno. Z jakichś powodów request.send nie wysyła danych do kodu PHP

function blog_1() {
$blog_posts_type = secure_clean( $_POST['blog_posts_type'] );
$page = secure_clean( $_POST['page'] );
$nonce = secure_clean( $_POST['nonce'] );

if ( !wp_verify_nonce( $_REQUEST['nonce'], "blog_1")) {
    exit("Illegal request");
}

if ( $blog_posts_type == 1 ) {
.....
0

Kurcze, powodem problemu był sposób łączenia ciągów

1 użytkowników online, w tym zalogowanych: 0, gości: 1