0

I am trying to understand this example for uploading JSON data.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data

I am not sure what is meant to be in the server file ( json-session.php ) so I've left it blank. I feel there must be code missing but I cant see from the Mozilla site what is meant to be here to get this example working. I am getting an error that there's an unexpected end to the JSON.

Ps, this example is a follow on from my previous question below; though I've switched to the PHP version - I am trying to do the first part of floatinglomas answer here by posting data from the client to the server.

Using global variables properly in node.js or is there a better way of doing this?

This is my code that I'm working with

<!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>
    
      <form id="form1">
             <input onclick="clickFunction()" id="new-button" type="submit" value="click">
        </form>
    
      </body>
    
      <script type="text/javascript">
        function clickFunction() {
            const data = { username: 'example' };
    
            fetch('json-session.php', {
              method: 'POST', // or 'PUT'
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(data => {
              console.log('Success:', data);
            })
            .catch((error) => {
              console.error('Error:', error);
            });
        }
    
    
      </script>
    </html>
Lucius
  • 1,246
  • 1
  • 8
  • 21
byronyasgur
  • 4,627
  • 13
  • 52
  • 96
  • I don't know exactly what the author or authors of that `fetch()` example have in mind for the server side of things, but if you are sending json of some sort to the server in this example, I would imagine that the server side would probably want to read your sent json data, perhaps do something with that data ([maybe save it to a database?](https://stackoverflow.com/q/66084792/1167750)), and then return a response which can then be picked up with the `response.json()` part of your code example. Just a possibility. – summea Feb 10 '21 at 03:04
  • 1
    you know i never thought of that - bet your right - will try - thanks – byronyasgur Feb 10 '21 at 12:18

0 Answers0