-1

I’m trying to use fetch instead of xmlhttprequest but fetch isn’t working the way the comparable ajax system does, or, at least, I can’t get it to work the same way. I have the following code:

addAction("pressBTN", "click", function() {
  const data = new FormData();
  data.append('dset1', theElement("dataINP1").value);
  data.append('dset2', theElement("dataINP2").value);
  /* for (var pair of data.entries()) {
  console.log(pair[0]+ ', '+ pair[1]); 
  } */
  fetch('./files/php/scripts/dataEntery.php', {
      method: 'POST',
      body: data
    })
    .then(response =>
      if (!response.ok) {
        throw new Error('Unknown Error #4: nice way to mess it up');
      } else {
        console.log(response);
      }
    }).catch((err) => {
  console.log(err);
});
}, true);

Note that theElement and addAction just keep me from having to type out

document.getElementById

and

document.addEventListener

over and over.

This process returns and ok response. Cool! Except nothing in the php file gets ran at all.

With the previous system xmlhttprequest, it called the php file, ran its contents and returned. In that PHP, I could check the values against a database and you know do server stuff.

I’ve tried moving the php file to the same location as the javascript file. Nothing. I made sure the data values were formed correctly which is still there in the commented code.

I’ve tried json because every tutorial out there shows json. It still hasn’t worked. Not even the simplest command like

<?php
   print_r($_POST);
   echo “balls!”;
?>

works in the php file. I honestly don’t know why. It looks like the code should work to me. Perhaps I am missing something here.

Except for the HTML that sets up two inputs as text and a button there is no other code in the project. This LOOKS like it shoukd work. The console returns the following when it logs the response:

body: ReadableStream
statusText: “OK”
json: (function)
redirected: false
text: (function)
status: 200
bodyUsed: false
url: “goodurlpath/files/php/scripts/dataentry.php”
type: “basic”
blob: (function)
arrayBuffer: (function)
formData: (function)
headers: Headers
value: (function)
keys: (function)
delete: (function)
forEach: (function)
entries: (function)
get: (function)
append: (function)
set: (function)
has: (function)
clone: (function)
ok: true

I’m wondering if the PHP is even supposed to run with fetch!?

Any help with why the php isn’t running here would be appreciated.

Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • Is this ReactJS? If so, you should tag it as such. – Patrick Q Oct 14 '19 at 21:12
  • Try use `$data = file_get_contents("php://input"); print_r($data);` https://stackoverflow.com/questions/8893574/php-php-input-vs-post – Felippe Duarte Oct 14 '19 at 21:13
  • Can you paste the PHP code? The one that worked with XMLHttpRequest? – Kostas Minaidis Oct 14 '19 at 21:18
  • 2
    From the server's perspective there's not much difference between XHR and `fetch()`; they both send ordinary HTTP requests. You should be using diagnostic tools on the server and in your browser to verify that the HTTP request is being issued with expected parameters (etc) and also what the server response contains. – Pointy Oct 14 '19 at 21:18
  • @TheAmazingNeckbeard Okay, that's why I asked instead of just tagging it myself. The syntax that you're using is often seen in react. – Patrick Q Oct 14 '19 at 21:31
  • Patrick Q: I don’t know what reactjs is. Felippe Duarte: nothing in PHP is being run at all. I just tested your code on my phone and no readout to the console except for the response log. KostasX I did post my php code. You all have all of it like I said except for the html which is two input text tags and a button. I will post the xmlhttprequest a little later, yes. Pointy: umm... okay? Thanks for all the help everyone! – The Amazing Neckbeard Oct 14 '19 at 21:34

1 Answers1

2

What you have logged above is the Response object. There is another step required to actually take the stream and read it to completion.

If you update your fetch request to the following it should work:

fetch('./files/php/scripts/dataEntery.php', {
  method:'POST',
  body: data
}).then(response => {
   return response.text();
}).then(response => {
   console.log(response);
});
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • This worked. But still don’t understand why. Any chance you can give me a little more detail as to why it was broken and why this fixed it? I worry that if I don’t learn that part, then asking this will have been in vain. What do you mean by I wasn’t waiting for the fetch to finish? – The Amazing Neckbeard Oct 14 '19 at 22:10
  • 1
    @TheAmazingNeckbeard you will see there are 2 `then` blocks. The first block takes the `Response` object which is what you had logged above. Then if you use the `.text()` method it will read this stream to completion. It is all based on the asynchronous nature of js fetch requests. Read this page - https://developer.mozilla.org/en-US/docs/Web/API/Response - along with `Promises` for more detail – Paul Fitzgerald Oct 14 '19 at 22:17
  • So then fetch doesn’t work like xmlhttprequest? I can’t run php and then return? It all has to wait until the end? alert('Hello World');" ?> For example won’t ever work with fetch, then? – The Amazing Neckbeard Oct 14 '19 at 22:34
  • @TheAmazingNeckbeard that wouldn't have worked with XMLHTTPREQUEST either I'm pretty certain. But it makes no sense to do so anyway... with an Ajax request you're returning data into JavaScript which can then do whatever it wants. No need to include separate JS blocks in the response as well, that just duplication, and it won't be treated as code anyway. Fetch and XHR both implement Ajax. The spec hasn't changed, just the code interface. In either case, you have to wait for the request to complete before you can do anything – ADyson Oct 15 '19 at 06:21
  • I'm having a similar problem. My chat system used to work well with php 5.6, but now, after updating to php 7.3, it stopped working. – Peristilo peris Mar 15 '23 at 16:52