L.C.J
L.C.J

Reputation: 3253

Cannot post form data to API

I have an app where I need to submit form data to an API. It's not working, whether I use JQuery or Axios or Fetch, no matter what API I request, no matter what client is performing the request. I decided to start from scratch using Typicode JSONPlaceholder, copy-pasting much of their own example code, and I still can't query a goddamn API. Somebody please point something out.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Post Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>    
    <script>
        $(() => {
            $('button').on('click', () => {
                let formData = {
                    title: $('#title').val(),
                    body: $('#body').val(),
                    userId: 0
                };
                fetch('https://jsonplaceholder.typicode.com/posts', {
                    method: 'POST',
                    body: JSON.stringify(formData),
                    headers: {
                        "Content-type": "application/json; charset=UTF-8"
                    }
                })
                .then(response => 
                {
                    response.json()
                })
                .then(json => console.log(json))
            });
        });
    </script>
</head>
<body>
    <form>
        <input placeholder="Title" id="title" />
        <textarea placeholder="Body" id="body" rows="4" cols="12"></textarea>
        <button>Submit</button>
    </form>

</body>
</html>

Edited for more information: It seems that JQuery is selecting the elements, and saving their values to the formData object. The debugger assures me this. And I'm quite certain the servers are receiving the browser's request. I can't speak for the JSONPlaceholder server, but when I used my own server the API always seemed to recognize the request. In fact, when I test my API using Postman it always responds with the proper data. But when I try to build a Javascript client to send the request, the data is never displayed in the console like I ask. And no errors are shown.

Upvotes: 0

Views: 1590

Answers (2)

Twisty
Twisty

Reputation: 30883

Tested with the following. This appears to work as expected.

$(function() {
  $('button').click(function(e) {
    var myData = {
      title: $('#title').val(),
      body: $('#body').val(),
      userId: 1
    };
    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify(myData),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        }
      })
      .then(response => response.json())
      .then(json => console.log(json));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<h3>Add Item</h3>
<label>Title</label> <input type="text" id="title" /><br/>
<label>Body</label>
<textarea id="body"></textarea><br/>
<button>Send</button>

More details at https://github.com/typicode/jsonplaceholder

Upvotes: 0

Titus
Titus

Reputation: 22474

The callback function that you pass to the first .then call doesn't return anything

.then(response => {
    response.json()
})

Change that to .then(response => response.json()) or .then(response => {return response.json()}) and it should work.

let formData = {
    title: "title",
    body: "body",
    userId: 0
};
fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify(formData),
    headers: {
        "Content-type": "application/json; charset=UTF-8"
    }
})
.then(response => 
{
    return response.json()
})
.then(json => console.log("response",json))

Upvotes: 1

Related Questions