I created 3 files (html, js and php) to call a restAPI from the js. But it is not working and I found zero clue on the web. It just does not work
Step 1 - HTML - for now, I use it to call the js script at the click on the button in this first moment I just try to call the js with the rest calling.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>
Web 2 Case - Abertura de Chamados
</title>
</head>
<body style="text-align:center;" id="body">
<!-- Button to send data -->
<button onclick="sendJSON()">Send JSON</button>
<!-- For printing result from server -->
<p class="result" style="color:green">
2 - Then I have index.js
function sendJSON(){
let result = document.querySelector('.result');
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "**The endpoint url**";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
xht.setRequestHeader("Authorization","00Df0000003dGUH!AQUAQLpQJlcqfKpqZUW9KZjwubQi4YcV7IrfZrw_Y53X_adKMCBHVXzblySCHtYfwO5YLh1EBcUTrX7qxp9EkSjhKvBfzl4M");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify({"Fields":["requestDefinitionId": "a3Hf0000000lTNaEAM", "client": "0053j00000A7rWLAAZ"],["Answers":{"a3Df0000000qI63EAE":[ "Reclamação" ],"a3Df0000000qHvsEAE":[ "Solicitação de Serviço aberta por qualquer integração web","a3Df0000000qHwREAU":["Web"] ]}]});
// Sending data with the request
xhr.send(data);
}
I believe that my var data is not good. When I call the endpoint from postman, I wrote the body
{
"Fields": [
{
"Name": "requestDefinitionId",
"Value": "a3Hf0000000lTNaEAM"
},
{
"Name": "client",
"Value": "0053j00000A7rWLAAZ"
}
],
"Answers": [
{
"QuestionId": "a3Df0000000qI63EAE",
"Values": [ "Reclamação" ]
},
{
"QuestionId": "a3Df0000000qHvsEAE",
"Values": [ "Solicitação de Serviço aberta por qualquer integração web" ]
},
{
"QuestionId": "a3Df0000000qHwREAU",
"Values": ["Web"]
}
]
}
illustrating the body I paste above
If you copy the contents of the JSON.stringify() argument into this validator, https://jsonformatter.curiousconcept.com/#, you will see that the "Fields" array is not formatted correctly; I think you want it's contents to be an object within curly brackets. So that would be why index.js does not work correctly.
Related
I am making a post request using XHR javascript as showing below:
let postObj = {
"Key": 1167722112,
"Remark": "",
"Total": 2,
"TotalTransferred": 0,
"SODTL": [
{
"Dtl": 11678,
"Code": "Screw Hex",
"Detail": true,
"DTL": []
}
]
}
let post = JSON.stringify(postObj)
const url = "http://example/api/Order/"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader("Authorization", "eyJhbGciOiJoAKk8b8ToV7HFcg");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!")
}
}
and the above request is working fine but i want to get the data from form instead of being hard coded
how can i assign each field from the API to specific input?
for example:
let postObj = {
"Key": => input name from form
"Remark": input name from form,
"Total": input name from form,
"TotalTransferred": input name from form,
"SODTL": [
{
"Dtl": input name from form,
"Code": input name from form,
"Detail": input name from form,
"DTL": []
}
]
}
and as you can see there is an array inside the call, is it gonna be the same when i assign it to input name? like name="field name" or name="[]field name"?
Note: English isn't my mother tongue so please do let me know if you need more explanation
The solution to assign a specific data from API to a specific input name inside a form
"Key": $('input[name="Key"]').val(),
I have a file with data in it that I am needing to parse and store in a DB. Below, is an example of 2 entries in the file. I'm not quite sure what the structure is (although it looks to be ndJSON). I am trying to parse the data in to a JSON object in order to store it in a DB, but cannot seem to figure it out. Here is what I have so far
var ndjson = {
"sequence-num": "0123456789",
"version": "N1.4",
"record-type": "R",
"session-id": "197-30760303",
"date": "2021-07-23 15:00:53",
"passport-header": { "alg": "ES256", "ppt": "test", "typ": "passport", "x5u": "https://cr.com" },
"passport-payload": { "attest": "A", "dest": { "tn": ["0123456789"] }, "iat": 0123456789, "orig": { "tn": "0123456789" }, "origid": "c699f78a-ebc6-11eb-bfd8-bec0bbc98888" },
"identity-header": "eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cHM6Ly9jci5zYW5zYXkuY29tL1RvdWNodG9uZV82ODNBIn0.eyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMjUeyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMj;info=<https://google.com/>;alg=ES256;ppt=\"test\""
}
{
"sequence-num": "0123456788",
"version": "N1.4",
"record-type": "R",
"session-id": "214-30760304",
"date": "2021-07-23 15:00:53",
"passport-header": { "alg": "ES256", "ppt": "test", "typ": "passport", "x5u": "https://cr.com" },
"passport-payload": { "attest": "B", "dest": { "tn": ["0123456788"] }, "iat": 0123456788, "orig": { "tn": "0123456788" }, "origid": "c69d0588-ebc6-11eb-bfd8-bec0bbc98888" },
"identity-header": "eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cHM6Ly9jci5zYW5zYXkuY29tL1RvdWNodG9uZV82ODNBIn0.eyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMjUeyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMj;info=<https://google.com/>;alg=ES256;ppt=\"test\""
};
let result = ndjson.split(',').map(s => JSON.parse(s));
console.log('The resulting array of items:');
console.log(result);
console.log('Each item at a time:');
for (o of result) {
console.log("item:", o);
}
When I run this, I get Uncaught SyntaxError: Unexpected token ':' error on line 12 at the 2nd node of "sequence-num": "0123456788",.
Any help is appreciated, thank you!
If you actually have ndJSON(newline-delimited JSON) then each line in the file is valid JSON, delimited by newlines. A simple file would look like this:
{"key1": "Value 1","key2": "Value 2","key3": "Value 3","key4": "Value 4"}
{"key1": "Value 5","key2": "Value 6","key3": "Value 7","key4": "Value 8"}
This differs from the formatted data you've posted here, and the difference is important since once you've formatted it, the valid JSON objects cannot simply be distinguished by the presence of newlines.
So, on the assumption that you do have valid ndJSON, in its original form, you can extract it by using split() on newLines and using JSON.parse() on the resulting array.
This snippet adds a little file handling to allow a file to be uploaded, but thereafter it uses split() and JSON.parse() to extract the data:
"use strict";
document.getElementsByTagName('form')[0].addEventListener('submit',function(e){
e.preventDefault();
const selectedFile = document.getElementById('inputFile').files[0];
let fr = new FileReader();
fr.onload = function(e){
let ndJSON = e.target.result; // ndJSON extracted here
let ndJSONLines = ndJSON.split('\n');
// Process JSON objects here
ndJSONLines.forEach(function(el){
let obj = JSON.parse(el);
Object.keys(obj).forEach(key=>{
console.log(`Key: ${key}, Value: ${obj[key]}`);
});
});
}
fr.readAsText(selectedFile)
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Parsing ndJSON</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="inputFile" id="inputFile">
<input type="submit">
</form>
</body>
</html>
Output, based on the sample file above:
Here is what I do
const end_point_url = 'https://ipfs.io/ipfs/bafkqap33ejwgs3tfgerduitomrvhg33oebtg64tnmf2c4lroej6qu6zcnruw4zjsei5ce5dinfzsa2ltebqsa43fmnxw4zbanruw4zjcpufa';
let json = await fetch(end_point_url).
then( resp => resp.text() ).
then( buf => { // NDJSON format ...
return buf.slice(0,-1).split('\n').map(JSON.parse);
}).
catch(console.error);
Im trying to POST an entry to Strapi through Postman. I have three fields in my endpoint, which are boxname + boxlocation + boxnumber. Two first are string and the last is integer. But for some reason my values doesnt get posted, they all turn up as null.
Any idea why? I ended up using Postman to try, because my Javascript wouldn't work either:
async function pushToStrapi(token, boxname, boxlocation, ownerid) {
var xhr = new XMLHttpRequest();
var url = "http://localhost:1337/boxes";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
}
};
var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" }});
xhr.send(data);
}
Theres a syntax error. Change:
var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" }});
To:
var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" });
If you prefer to use shorthand, you can do something like this:
var data = JSON.stringify({boxname, boxlocation});
You can't do this kind of request.
You will have to click on "body" then select the "raw" format and choose "JSON" in the format drop down.
Then in write your JSON object w/ your key values.
You can not send params in query parameters.
I have had this issue too, I'm learning Strapi, and in my case I was sending the ID in the JSON Object, wich is managed by Strapi, then I removed the ID (autoincremental value) and send only the data. In your example I see that you don't send the ID field, but this point maybe can help you or others who read.
This is my request:
{
"post_name": "raw postman post",
"post_description":"raw postman post",
"post_content": "raw postman post",
"post_category": 1 }
And this is the response that worked:
{
"id": 9,
"post_name": "raw postman post",
"post_description": "raw postman post",
"post_content": "raw postman post",
"post_category": {
"id": 1,
"category_name": "Climate",
"category_desc": "Climate",
"published_at": "2020-10-16T11:37:11.931Z",
"created_at": "2020-10-16T11:35:01.418Z",
"updated_at": "2020-10-16T11:37:11.950Z"
},
"published_at": "2020-10-22T11:35:59.714Z",
"created_at": "2020-10-22T11:35:59.722Z",
"updated_at": "2020-10-22T11:35:59.731Z"}
Afternoon all,
I'm trying to parse data from a nested json object.
For example: member.accuracy
Currently, it's returning the result undefined.
My code:
JSON (places.json):
{
"request_time": "2019-05-30T13:48:39+01:00",
"source": "Network Rail",
"acknowledgements": "Contains information of Network Rail Infrastructure Limited. License http://www.networkrail.co.uk/data-feeds/terms-and-conditions/",
"member": [
{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}
]
}
HTML:
<html>
<head>
<meta content="text/html; charset=utf-8">
<title>AJAX JSON by Javatpoint</title>
<script type="application/javascript">
function load()
{
var url = "http://myurl.places.json?";
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();//for Chrome, mozilla etc
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only
}
request.onreadystatechange = function(){
if (request.readyState == 4 )
{
var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
document.getElementById("date").innerHTML = jsonObj.request_time;
document.getElementById("time").innerHTML = jsonObj.member.accuracy;
}
}
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body onload="load()">
Date: <span id="date"></span><br/>
Time: <span id="time"></span><br/>
</body>
</html>
Any help would be much appreciated!
Thanks,
Brad
As you can see in the json file, the member property holds an array, containing one object. To get accuracy, you must access it with an index:
var jsonObj = {
"member": [{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}]
}
console.log(jsonObj.member[0].accuracy)
Be aware that if you're fetching this data from some sort of API, there may be more than one object present in this array in future fetches, and the first element (index 0) may not be the one you're looking for.
I would like to get JSON Array from a cross domain without using JQuery. The data from cross domain is like this:
{
"transactionid": "LBS_48550801",
"status": 0,
"countrylist":
[
{ "id": 1, "name": "France", "latitude": 37.00039, "longitude": 35.31411, "extent": { "minlatitude": 36.53888499, "minlongitude": 34.76786904, "maxlatitude": 38.37851496, "maxlongitude": 36.40534884 }},
{ "id": 2, "name": "Germany", "latitude": 37.76454, "longitude": 38.27645, "extent": { "minlatitude": 37.40771898, "minlongitude": 37.43326512, "maxlatitude": 38.21203404, "maxlongitude": 39.24767592 } },
//... .... ....
//... .... ....
//... .... ....
{ "id": 98, "name": "Belgium", "latitude": 38.75754, "longitude": 30.5387, "extent": { "minlatitude": 37.78126803, "minlongitude": 29.68963308, "maxlatitude": 39.27915099, "maxlongitude": 31.71549708 } },
{ "id": 99, "name": "England", "latitude": 39.71812, "longitude": 43.03345, "extent": { "minlatitude": 38.96877501, "minlongitude": 42.28340184, "maxlatitude": 40.031208, "maxlongitude": 44.61092892 } },
]
}
After getting the data, I need to parse it to get "countrylist" list.
I searched for solving this issue but the examples are all with JQuery. I dont want to use it. As you see, I have transactionid, status parameters in the input. So, after importing the data, I need to parse it to get the countrylist array. I know how to parse it, but I couldnt get the whole data from the service.
I need to get the data by Javascript methods. The server supports retrieving data well.
The steps to be taken are:
1- Get the whole data (Here is where I got stuck)
2- Parse it as Json Object (I know how to parse the data)
How can I get the whole data without using any JQuery or other prepared libraries?
You can use XMLHttpRequest for ajax and JSON.parse for parse json :)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '//example.org', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
var countryList = obj.countrylist;
}
}
};
xmlhttp.send(null);
You should never use eval! Eval is evil! You can read about it on mdn
UPD:
If there is no CORS header, you can use JSONP. Just add &callback=getJSONP to your URL. Try it on jsfiddle: http://jsfiddle.net/VmBF7/3/
since your operation involving cross domain requests, i suggest you to use jsonp request.
this question has what you wanted.
Could you try to download the data to a hidden iframe and then parse the content of its document.body?
In my case, since the server require a ajax request or it will give you a 404(to prevent csrf), so based on what the accepted answer, you need one extra line to complete the getJSON ajax version like this:
<script type="application/javascript">
var request = new XMLHttpRequest();
request.open('GET', '/your/url', true);
// this following line is needed to tell the server this is a ajax request
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
var json = JSON.parse(this.response);
// this is where you can do something with the json response
}
};
request.send();
});
</script>