简体   繁体   中英

Vanilla Javascript and Ajax - $_POST is empty

I send data with ajax using the POST method.

Once the data are sent $_POST['my_value'] remains empty.

However the expected value is in $_GET['my_value'].

Here is my ajax call:

loadAjaxDoc( 'https://www.mypage.com/?my_value=test', 1000, initGame );

function loadAjaxDoc( url, timeout, cFunction ) {

    var xhr;

    setTimeout(function() {

        xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function() {

            elements.interludeCountdownDiv.innerHTML = '[[%doodles.game_loaded]]';

            if ( this.readyState == 4 ) { 

                elements.interludeCountdownDiv.innerHTML = '[[%doodles.game_loading_state4]]';

                if ( this.status === 0 || ( this.status >= 200 && this.status < 400 ) ) {

                    if ( this.status == 200 ) {

                        cFunction( this );

                    }

                }

            }

        };

        xhr.open( 'POST', url, true );
        xhr.timeout = timeout;

        setTimeout( function() {

            xhr.send( null );

        }, 1000 );

    }, 1000 );

}

Am i doing something wrong?

Can someone give a hand for this? Any help appreciated:)

The PHP superglobals $_POST and $_GET are not directly related to the HTTP request method.

$_GET is populated with data from the URL's query string.

$_POST is populated with data from the request body (if it uses a supported encoding like application/www-url-encoded ).

We can't see what URL you are passing, but since you say the data is showing up in $_GET you must have put the data there.

We can see what you put in the request body — null — so the body will be empty.


If you want to populate the body you could do something like:

const body = new FormData();
body.append('my_value', "some value");
xhr.send(body);

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