Get Json Array with pure JS - javascript

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>

Related

How to assign form inputs to API Post request with javascript XHR?

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(),

Values not being sent in POST request to API (Postman + Strapi)

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"}

I am not get value which is sent in request body in specific json format

I need help in my one issue. I have write the program in that I am use map in node.js.
I am testing this program using postman by sending JSON structure, however I am not get specific value in console which I am printing.
Please see below code .
async CreateProduceMVPRateAsset(data, callback) {
// Create a new file system based wallet for managing identities.
var ProducePRICE = {};
var MVPRATE = new Map();
var MVPPRICE =[];
var MVPPRICE_BS ={};
var MVPPRICE_LB ={};
var PRODUCENAME = data.PRODUCE
console.log('PRODUCENAME', PRODUCENAME);
var COUNTRY = data.COUNTRY;
console.log('COUNTRY', COUNTRY);
var STATE = data.STATE;
console.log('STATE', STATE);
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', MVPRATES); // not getting value of MVPRATES from request body
}
JSON structure which is sending using POSTMAN
{
"username": "admin2",
"PRODUCE": "Apple",
"STATE": "MI",
"COUNTRY": "US",
"MVPRATES": {
"fuji": {
"VARIETY": "fuji",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
},
"gala": {
"VARIETY": "gala",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
}
}
}
output
Any help very appreciable
Thanks
Abhijeet
That's how logs will show up for the non-primitive type of data. Try stringifying the response like:
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', JSON.stringify(MVPRATES));
This will help you in printing actual values to the logs. A better approach will be to use a logging module like winston and configure all such things and many more.
Sorry to waste you all time I think I miss the var in front of MVPRATES. It should be
var MVPRATES = data.MVPRATES;

Display nested JSON data using Javascript

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.

AngularJs Multipart $http Request Issue

For some reason I can't get [object Object] out of the form. I'm using hte method found here:
http://badwing.com/multipart-form-data-ajax-uploads-with-angularjs/#comment-431
The JSON i'm sending is pretty complicated (sample):
{
"challenge_id": 262,
"priority": "0",
"cause_id": "29",
"timestamp": "2013-11-29 12:06:01",
"translations": {
"en": {
"name": "asdfgsfd",
"description": "sdfghfs"
}
},
"actions": {
"1": {
"type": "chek",
"step": "1",
"translations": {
"en": {
"description": "adsfas"
}
}
},
"2": {
"type": "chek",
"step": "2",
"translations": {
"en": {
"description": "fsdgsd"
}
}
}
}
}
My response looks like this:
Content-Disposition: form-data; name="challenge_json"
[object Object]
My request looks like this:
return $http.post( REQUEST_URL + '/ENDPOINT', {challenge_json:data}, {
transformRequest: function(data) {
console.log(data);
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
console.log(fd);
return fd;
}
Im modifying the headers with a httpProvider configuration change. But have tried doing it in line and am getting the same result.
any help would be appreciated.
It seems you were close to the solution, but needed to unset the 'content-type' header in the options passed to $http, so that the xmlhttprequest object can add it automatically when it gets a formdata on its send method.
https://groups.google.com/d/topic/angular/MBf8qvBpuVE/discussion
see a playground here http://jsfiddle.net/Lv1n55db/1/
(providing FormData object directly and a no-op transform, or your way of providing a normal data object and transforming it to FormData in transformRequest is no significant difference, the key is in the headers option)
headers:{'Content-Type':undefined},
It may vary with differnt browsers and different angularjs versions too.
A more certain and stable approach, at least if you do not need file fields and such, could be to not use native FormData but implement the serialization to string yourself, as FormData polyfills do it.

Categories