1

I'm trying to send a POST request from react to PHP and this is my code:

function getPhp(){
    var xhr = new XMLHttpRequest()

    xhr.addEventListener('load', () => {
      console.log(xhr.responseText)
    })

    xhr.open('POST', 'http://localhost/anima/index.php')

    xhr.send(JSON.stringify({ dt: 'data' }))
}

PHP:

print_r($_REQUEST);
if (isset($_POST['dt'])) {
  echo $_POST['dt'];
}

However, the only response I get is

Array
(
)

Due to the $_REQUEST. I checked the network in the dev tools andenter image description here everything seems fine.

Jeto
  • 13,447
  • 2
  • 22
  • 39
  • Doesn't `XMLHttpRequest.send()` need an URL query string (`dt=data` in your case), as opposed to JSON? – Jeto Apr 18 '20 at 10:07
  • @Jeto I tried that too, it didn't work. Plus if that was the case, would ```$_REQUEST``` show something? – SIAJSAJ IJSAIJSAJA Apr 18 '20 at 10:09
  • You should check the `Params` tab on the browser's console, instead of `Headers`. Does it show something? – Jeto Apr 18 '20 at 10:11
  • Also, according to the docs, you need to add this: `xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");` if you're passing url-encoded data. This might just be a dupe of https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest. – Jeto Apr 18 '20 at 10:13
  • 1
    @Jeto yep thats right. Thanks a lot – SIAJSAJ IJSAIJSAJA Apr 18 '20 at 12:08
  • @Jeto u finna add it as answer or? – SIAJSAJ IJSAIJSAJA Apr 18 '20 at 12:11
  • Not worth it, I think I'll just mark it as a duplicate of the other one (edit: well scratch that, I messed up). – Jeto Apr 18 '20 at 12:12

0 Answers0