0

I'm collecting data in a form and calling this js:

fetch('process.php', {
    method: 'POST',
    body: formData,
}).then(response => alert( response ) );

process.php gets called correctly; i perform my ops and then i try to return a confirmation message, or a failure message like this:

 echo json_encode('Upload completato correttamente');

But i can't get the message to show in the alert: i only get "[object promise]" and playing around with the response i can't seem to read the message.

Any help?

Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50
  • Does this answer your question? [fetch function return Promise ](https://stackoverflow.com/questions/54656223/fetch-function-return-promise-pending) – Krzysztof Krzeszewski Mar 18 '20 at 12:27
  • 1
    What's the point of `json_encode` if you're just intending to return a plain string? Don't bother with JSON, just return it as text. – ADyson Mar 18 '20 at 12:32
  • @ADyson if i return plain text, the alert says "[object Response]" – Mauro Sampietro Mar 18 '20 at 12:36
  • 1
    Oh boy, there’s still people who use `alert` as a debugging tool these days? Log this stuff to console, then you can inspect it there and see what _kind_ of object it actually is. – CBroe Mar 18 '20 at 12:39
  • @MauroSampietro because it _is_ an object, not just text. The response to a HTTP request is not just the body text alone. https://developer.mozilla.org/en-US/docs/Web/API/Response – ADyson Mar 18 '20 at 12:40
  • I want to keep things as simple as possible to get a quick answer. I know the resturn object it's not just the plain text. But how to get to payload message? – Mauro Sampietro Mar 18 '20 at 12:44
  • Assuming you changed `echo json_encode('Upload completato correttamente');` to `echo 'Upload completato correttamente';` in the PHP, then `fetch('process.php', { method: 'POST', body: formData }).then(response => response.text() ).then(result=>{ alert(result); });` should do it. There are lots of examples of this kind of thing online. Here's a simple demo (using a different endpoint, but the principle is the same: https://jsfiddle.net/1r79evup/) – ADyson Mar 18 '20 at 12:46
  • thanks, problem solved thanks to all of the advises console etc. – Mauro Sampietro Mar 18 '20 at 12:55

2 Answers2

1

you need to parsing your result like this

fetch('process.php', {
    method: 'POST',
    body: formData,
}).then(response => response.json() ).then(result=>{
 alert(result);
});

hope this work

JuNas
  • 432
  • 2
  • 7
  • 16
1

There was a problem in the php code i could spot via console. It was preventing the following correct code to work correctly:

fetch('process.php', { method: 'POST', body: formData })
  .then(response => response.text() )
  .then(result=>{ alert(result); });

Thank you all

Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50