L
L
LYTK42020-11-04 01:06:20
PHP
LYTK4, 2020-11-04 01:06:20

PHP not seeing JSON (POST) request?

I send a request from JS:

// DEVELOPED BY https://github.com/lytk4dev

window.onload = function() {
    checkAdBlock();
};

const curl = 'http://localhost/check.php';
var xml = new XMLHttpRequest();   
xml.open("GET", url);


function checkAdBlock() {
    try {
        if (ads === true) {}
            ad = false;
            showInfoAdBlock(false);
    }
    catch (err) { 
        ad = true;
        showInfoAdBlock(true);
    }
};
 
function sendReq(method, url, body = null) {
    return new Promise((resolve, reject) => {
        const xml = new XMLHttpRequest();   
        xml.open(method, url)
        xml.responseType = 'json'

        xml.onload = () => {
            if (xml.status >= 400) {
                reject(xml.response)
            } else {
                resolve(xml.response)
            }
        }

        xml.onerror = () => {
            reject(xml.response)
        }

        xml.send(JSON.stringify(body))
    })
}

let sd;

function showInfoAdBlock(IsExistAdBlock) {
    if (IsExistAdBlock) {
       // alert("Блокировщик рекламы работает"); // Here add what happens if AdBlock is enabled 
        sendReq("POST", curl, {
            status: ad
        });
    }
    else if (!response.ok){ 
       // alert("Блокировщик рекламы работает"); // And here
       // document.body.innerHTML += `<pre>${sd}</pre>`;
    } 
    else if (!IsExistAdBlock) {  
       // alert("Блокировщик не работает"); // Don't touch this!
      // let sd = xmlhttp.send(JSON.stringify(jsonData, null, 4));
       // document.body.innerHTML += `<pre>${sd}</pre>`;
    }
};


It is in the Network tab, but PHP writes: Notice: Undefined index: status in C:\xamppq\htdocs\index.php on line 9
{"ans":null}array(0) { }

PHP code:
<?php
           $phpVar = $_POST["status"];
           $ans = array(
               "ans" => $phpVar
           );
           echo json_encode($ans);
           var_dump($_POST);
        ?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zoryamba, 2020-11-04
@LYTK4

Php parses only FormData by default. Json needs to be parsed manually. Something like
$json = json_decode(file_get_contents(' php://input '));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question