How to POST data to JsonPlaceholder fake server?

11,885

Solution 1

The issue is the form.

Here's the working code:

<html>

<head>
  <meta http-equiv="Content-Type" charset="UTF-8">
</head>

<body>
  <h1>Please type in new item data:</h1><br>
  <label class="add_label"><b>&nbsp;userId:&nbsp; </b></label>
  <input type="number" class="add_input" id="new_userId" name="new_userId" value="">
  <br>
  <label class="add_label"><b>&nbsp;title:&nbsp;</b></label>
  <input type="text" class="add_input" id="new_title" name="new_title" value="">
  <br>
  <label class="add_label"><b>&nbsp;body:&nbsp;</b></label>
  <input type="text" class="add_input" id="new_body" name="new_body" value="">

  <button id="add_btn2" onclick="New()">Submit</button>
  <script>
    function New() {
      var userid = document.getElementById("new_userId").value;
      var new_title = document.getElementById("new_title").value;
      var new_body = document.getElementById("new_body").value;

      console.log("Input Data: " + userid + " " + new_title + " " + new_body);

      fetch('https://jsonplaceholder.typicode.com/posts', {
          method: 'POST',
          body: JSON.stringify({
            title: new_title,
            body: new_body,
            userId: userid
          }),
          headers: {
            "Content-type": "application/json; charset=UTF-8"
          }
        })
        .then(response => response.json())
        .then(json => {
          console.log('response: ' + JSON.stringify(json));
        })
    }
  </script>
</body>

</html>

Check the console to see the response

Solution 2

  1. First you need to prevent the form from submitting, if not it will refresh the page. You can try this:

    In Form

    ... <button id = "add_btn2" onclick = "New(event)" type = "submit">Submit</button> ...

    In function

    function New(e) { e.preventDefault() ...

  2. As stated here JSONPlaceholder Guide, the resource will not be really created. Successful request will return a json object based on form-data you've sent. Just check your browser log, check if the responses just like what the documentation said.

Share:
11,885
vytaute
Author by

vytaute

IT student

Updated on June 04, 2022

Comments

  • vytaute
    vytaute almost 2 years

    I want to fake new data insertion into a server using https://jsonplaceholder.typicode.com/ fake server. I am trying to send data using this tutorial https://jsonplaceholder.typicode.com/guide.html#Create_a_resource. But how do I know whether data was inserted or not? And am I doing insertion correctly by having a submit button in a form that is calling New() function on click? And form by itself goes to the same page on which it is displayed in (add.html).

    function New()
    {
    	var userid = document.getElementById("new_userId").value;
    	var new_title = document.getElementById("new_title").value;
    	var userid = document.getElementById("new_body").value;
    	
    	fetch('https://jsonplaceholder.typicode.com/posts', {
    		method: 'POST',
    		body: JSON.stringify({
    		  title: new_title,
    		  body: new_body,
    		  userId: userid
    		}),
    		headers: {
    		  "Content-type": "application/json; charset=UTF-8"
    		}
    	  })
    	  .then(response => response.json())
    	  .then(json => console.log(json))
    }
    <html>
    
    	<head>
    	<link rel="stylesheet" type="text/css" href ="style.css">		
    		<meta http-equiv="Content-Type"  charset="UTF-8" > 
    	</head>
      
      <body>
    	<h1>Please type in new item data:</h1><br>
    	
    	<form id = "add_form" method = "POST" action = "add.html">
    					
    	<label class = "add_label"><b>&nbsp;userId:&nbsp; </b></label>
    	<input type = "number" class = "add_input" id="new_userId" name="new_userId" value = "">
    	<br>
    	<label class = "add_label"><b>&nbsp;title:&nbsp;</b></label>
    	<input type = "text" class = "add_input" id="new_title" name="new_title" value = "">
    	<br>	
    	<label class = "add_label"><b>&nbsp;body:&nbsp;</b></label>
    	<input type = "text" class = "add_input" id="new_body" name="new_body" value = "">
    	
    	<button id = "add_btn2" onclick = "New()" type = "submit">Submit</button>
    	</form>	
    			
    	</body>
    
    </html>

    Thank you !

    UPDATE: Thank you all for a help, I am adding a fixed and working code below. Input and labels stil needs to be wrapped into a form but the e.PreventDefault() must be used in a New(e) function.

    <html>
    
    <head>
      <meta http-equiv="Content-Type" charset="UTF-8">
    </head>
    
    <body>
    <form>
      <h1>Please type in new item data:</h1><br>
      <label class="add_label"><b>&nbsp;userId:&nbsp; </b></label>
      <input type="number" class="add_input" id="new_userId" name="new_userId" value="">
      <br>
      <label class="add_label"><b>&nbsp;title:&nbsp;</b></label>
      <input type="text" class="add_input" id="new_title" name="new_title" value="">
      <br>
      <label class="add_label"><b>&nbsp;body:&nbsp;</b></label>
      <input type="text" class="add_input" id="new_body" name="new_body" value="">
    
      <button id="add_btn2" onclick = "New(event)">Submit</button>
      </form>
      
      <script>
        function New(e) {
    	  e.preventDefault() 
          var userid = document.getElementById("new_userId").value;
          var new_title = document.getElementById("new_title").value;
          var new_body = document.getElementById("new_body").value;
    
          console.log("Input Data: " + userid + " " + new_title + " " + new_body);
    
          fetch('https://jsonplaceholder.typicode.com/posts', {
              method: 'POST',
              body: JSON.stringify({
                title: new_title,
                body: new_body,
                userId: userid
              }),
              headers: {
                "Content-type": "application/json; charset=UTF-8"
              }
            })
            .then(response => response.json())
            .then(json => {
              console.log('response: ' + JSON.stringify(json));
            })
        }
      </script>
    </body>
    
    </html>
    • Titus
      Titus over 4 years
      You will need to prevent the form from submitting, you can find examples for doing that HERE
    • vytaute
      vytaute over 4 years
      Thank you, added correct code as an update
  • vytaute
    vytaute over 4 years
    Thank you, I think that worked well! If I get such message in console it means that insertion was successfully faked, right? snipboard.io/TpOwrJ.jpg
  • vytaute
    vytaute over 4 years
    Actually, if I wrap everything into a form and go to function New(e) on form submit (preventing default in a function), I dont get the red error as I showed you before in sang.gy link. I will add my final code in my question as and update. Thank you all for help!
  • saintlyzero
    saintlyzero over 4 years
    @vytaute Yes, the id:101 field from the response is generated by JSONPlaceholder