Avatar of FSAAdmin
FSAAdmin
Flag for United States of America asked on

POSTING JSON TO API

Looking for an example of passing JSON to a server API.  I've had help getting the JSON created from HTML Form Elements, now I need to pass this on to the API.
HTMLJSON

Avatar of undefined
Last Comment
FSAAdmin

8/22/2022 - Mon
leakim971

https://api.jquery.com/jquery.post/

var yourjson = {
    n: 1,
    b: true,
    s: "hello" 
};
$.post( "/path/to/api", yourjson, function( data ) {
}, "json);

Open in new window

Zvonko

Here an example without jQuery:

<html> 
<head> 
<title>JSON API</title> 
<style> 
input, select { 
	width: 300px; 
} 
</style> 
<script> 
var req = { 
	"request": { 
        "subject": "Unable to fetch mails", 
        "description": "I am unable to fetch mails from the mail server", 
        "requester": { 
            "id": "4", 
            "name": "administrator" 
        }, 
        "impact_details": "Routine tasks are pending due to mail server problem", 
        "resolution": { 
            "content": "Mail Fetching Server problem has been fixed" 
        }, 
        "status": { 
            "name": "Open" 
        } 
    } 
} 
var fldMap = { 
	"request.subject":"subject", 
	"request.description":"description", 
	"request.requester.id":"requester_id", 
	"request.requester.name":"requester_name", 
	"request.resolution.content":"resolution", 
	"request.status.name":"status" 
} 
 
window.onload = function(){ 
	var elements = document.forms[0].elements; 
	for(var item in fldMap){ 
		elements[fldMap[item]].value = getObjVal(req, item);	 
	} 
} 
 
function getObjVal(oBase, oPath){ 
	var oElem = oPath.split('.'); 
	if(oElem.length == 1){ 
		return oBase[oElem[0]]; 
	} 
	oBase = oBase[oElem[0]]; 
	oElem.shift();  
	return getObjVal(oBase, oElem.join('.')); 
} 
 
 
function setObjVal(oBase, oPath, oValue){	 
	var oElem = oPath.split('.'); 
	if(oElem.length == 1){ 
		oBase[oElem[0]] = oValue; 
	} else { 
		oBase = oBase[oElem[0]]; 
		oElem.shift();  
		setObjVal(oBase, oElem.join('.'), oValue); 
	} 
} 
 
function callJsonAPI(theForm){ 
	var elements = theForm.elements; 
	for(var item in fldMap){ 
		setObjVal(req, item, elements[fldMap[item]].value);	 
	} 
	fetch('https://jsonplaceholder.typicode.com/posts', { 
		method: 'POST', 
		body: JSON.stringify(req), 
		headers: { 
			"Content-type": "application/json; charset=UTF-8" 
		} 
	}) 
	.then(response => response.json()) 
	.then(json => theForm.result.value="Response from typicode.com:\n"+JSON.stringify(json).replace(/\,/g,',\n')) 
} 
</script> 
</head> 
<body> 
<form> 
<h1>JSON form</h1> 
<table> 
<tr><th>Subject:</th><td><input type="text" name="subject" ></td></tr> 
<tr><th>Description:</th><td><input type="text" name="description" ></td></tr> 
<tr><th>Requester ID:</th><td><input type="text" name="requester_id" ></td></tr> 
<tr><th>Requester Name:</th><td><input type="text" name="requester_name" ></td></tr> 
<tr><th>Resolution:</th><td><input type="text" name="resolution" ></td></tr> 
<tr><th>Status:</th><td><input type="text" name="status" ></td></tr> 
<tr><td></td><td><input type="button" value="Submit" onClick="callJsonAPI(this.form)" ></td></tr> 
</table> 
<textarea name="result" cols="80" rows="12" > 
</textarea> 
</form> 
<body> 
</html>

Open in new window

Zvonko

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
FSAAdmin

ASKER
I'm having to build for two different versions of the API as we have two different instances.  

They both require paramaters to be inserted into the URL and an additional header for authtoken

version 1: authtoken, scope, OPERATION_NAME (value is ADD_REQUEST) and INPUT_DATA (value is JSON)
Expected: http://someserver/sdpapi/request?OPERATION_NAME=ADD&TECHNICIAN_KEY=11111&INPUT_DATA=(json)

version 2: authtoken, and input_data
Expected: http://someserver/api/v3/requests?input_data=(json) 

So it seems like the body of the json can be empty and everything is embedded in the URL.
ASKER CERTIFIED SOLUTION
Zvonko

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Chinmay Patel

I would strongly recommend going with Fetch. It can get tricky but it is one of the best thing that I have come across.

Zvonko

...and if you get old IE9 users tell them there is Edge Chromium out  :  )

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Chinmay Patel

Zvonko :P If you have IE9 users... well.. time to quit :D and find other job / client :P

Zvonko

I am retiered  <|:-)

Chinmay Patel

Aahhh.. the sweet joy... but do we really ... truly retire... ever? :)

Your help has saved me hundreds of hours of internet surfing.
fblack61
Zvonko

That was what my colleagues told me: you will see, only the management changes  :  )

FSAAdmin

ASKER
Thank you Zvonko.  I'm working through some issues on the server side and believe you have helped me out
FSAAdmin

ASKER
Thank you Zvonko.  I'm working through some issues on the server side and believe you have helped me out
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.