-1

I have this code which works for me but when I try to actually use the form data in PHP I cant get it working. I've tried a number of snippets from stack overflow and the web but nothing seems to work. I did a reduced test case and discovered that I wasn't able to use var_dump($_POST) because I must have some misunderstanding of how fetch works because when I replace the php file with nothing but var_dump($_POST) or even echo("test") I'm not seeing anything.

Can anyone help me get at the data sent to the php file?

checkout.html ( this works fine )

<!DOCTYPE html>
<html>
  <head>
    <title>Buy cool new product</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <section>
      <form id = "myForm">
        <input type="text" name="">
        <input type="submit" name="">
      </form>
    </section>
  </body>
  <script type="text/javascript">
    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe("pk_9999999999999999999");
    
const myForm = document.getElementById('myForm');


    myForm.addEventListener("submit", function (e) {
      e.preventDefault();

      const formData = new FormData(this);

      fetch("/create-checkout-session-dump.php", {
        method: "POST",
        body: formData
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
  </script>
</html>

creatch-checkout-session-dump.php ( this is just in place of the regular file as a reduced test case - the original file works for what i want it for but i need to be able to see the form contents here somehow but as it is I cant even get it so print "hello world")

<?php
echo('test');
byronyasgur
  • 4,627
  • 13
  • 52
  • 96
  • Are you looking for `$_POST` ? – Evert Mar 03 '21 at 21:32
  • Your form inputs have no names. Unnamed inputs aren't sent. – Tangentially Perpendicular Mar 03 '21 at 21:34
  • `return response.json()` is going to error if you give it a `var_dump` instead of JSON. – Quentin Mar 03 '21 at 21:40
  • "I cant even get it so print "hello world"" — Where do you expect it to print it **to**? Where are you looking? – Quentin Mar 03 '21 at 21:51
  • quentin i thought echo would print to the screen like a normal echo - i dont really understand how this is different – byronyasgur Mar 03 '21 at 22:12
  • tangentially thanks - didnt know that will try – byronyasgur Mar 03 '21 at 22:12
  • @byronyasgur - `echo` in PHP run by a web server never prints to the screen. It prints to the HTTP output stream. If that stream is loaded as an HTML document by a browser because you typed it into the address bar or clicked a link to it then it would render on the page. You aren't doing that though, you are fetching it with JavaScript. – Quentin Mar 03 '21 at 22:14
  • what i dont understand is how to read the data in the php file - is there any way to do it – byronyasgur Mar 03 '21 at 22:14
  • maybe what i'm trying to do is not possible – byronyasgur Mar 03 '21 at 22:15
  • also is there any way I can see the contents of $_POST by way of doing diagnosis since I cant echo it – byronyasgur Mar 03 '21 at 22:16
  • I think you need to start with an introductory Ajax guide. You seem to be trying to modify some relatively complex code here without having grasped some of the fundamentals (such as basic debugging: since you are echoing stuff which isn't JSON you *should* be getting error messages when you try to call `response.json()` which suggests you either don't know to look at the browser's dev tools Console to see error messages or you're not editing the right PHP file in the first place). – Quentin Mar 03 '21 at 22:18
  • You *can* see the contents of `$_POST` by echoing it, you just need to look somewhere that shows what the PHP is outputting (such as the Network tab of the browser's developer tools). – Quentin Mar 03 '21 at 22:19
  • got it working - thanks so much everybody - been stumped on this for weeks - ended up having to do a job I was very rusty with ( programming ) – byronyasgur Mar 03 '21 at 22:25

1 Answers1

0

I'm going to answer you again here.

In your PHP file you should ideally use the $_POST super global.

<?php

$data = $_POST['test'];

?>

This 'test' key tag is directly related to whatever you named your input/value in the form. Try this:

<input type="text" name="test" />

<script>

fetch("/create-checkout-session-dump.php",{
    type: "POST",
    body: formData
    })
    .then( response => response.ok ? response.json() : "ERROR LOADING" )
    .then( data => console.log(data) )
    .catch( err => console.error(err) );

</script>
bartholomew
  • 102
  • 8
  • this was basicly what i did in the end so giving you the tick – byronyasgur Mar 03 '21 at 22:26
  • this was what I said earlier, but someone got really upset I added more information. Keep in mind you can refactor this a bit and cut out the console.log(data) return into just data so you can manipulate the fetch return in a more robust fashion. – bartholomew Mar 03 '21 at 22:26