As I am new with json can you guys please help me out? My data file is at this url - http://www.thedailystar.net/json/category
Now I want to show it in the following format:
<ul id="smenu">
<li></li>
</ul>
So, how can I get the request to get data from the url and run a loop to print it out? I have tried this code but nothing happened. Thanks in advance :)
var xmlhttp = new XMLHttpRequest();
var url = "http://www.thedailystar.net/json/category";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<li href="' + arr[i].name + '">' +
arr[i].display + '</li><br>';
}
document.getElementById("smenu").innerHTML = out;
}
If your JavaScript is not running on thedailystar.net domain it will be a cross domain request. If this is the case, you will need to enable CORS on your resource server (http://www.thedailystar.net/json/category).
Most of the time, to enable CORS, the server needs to return the following header in its response:
Access-Control-Allow-Origin: *
More information on CORS: http://enable-cors.org/server.html
Your data at the URL provided contains an object with a property named category whit the value being an array. This array is what I suspect you are expecting to parse.
So, only change the call ty myFunction from:
myFunction(myArr);
to:
myFunction(myArr.category);
Related
I am completely new to javascript and web development.
I'm having a problem with the for loop; what happens to me is that the ids come back to me all together and not individually in order to retrieve the relative image and title through the id, so I can't recover images and title from the json array.
Specifically I get the error:
Uncaught TypeError: Cannot read properties of undefined (reading 'immagine') at XMLHttpRequest.xmlhttp.onreadystatechange
Warning: I have no problems in how to retrieve items in a json array because I know how to do it very well
This is my code:
//here I get all the articles, so my json array
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5u1234.execute-api.us-east-2.amazonaws.com/articles";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var allart = JSON.parse(this.responseText);
var container=document.getElementById("slideshow")
for(var i = 0; i < allart.Items.length; i++)
{
container.innerHTML += '<div class="slideshow-container"></div>';
document.getElementById("id").innerHTML += "<br/>" + allart.Items[i].id;
myFunction1(allart.Items[i].id);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
//here I pass the id via function call, and for each id I want to retrieve image and title which has that specific id only i get the set of ids without having one at a time to retrieve what i need
function myFunction1(id) {
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5u1234.execute-api.us-east-2.amazonaws.com/articles/"+id;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
document.getElementById("img1").src="articoli_img/"+myArr.Item.immagine;
document.getElementById("title1").innerHTML = myArr.Item.titolo;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I would be very thankful for any help.
It seems that "Item" prop doesn't exist in returned object (located in myFunction1()) (did you mean to write myArr.immagine?)
Since you are new: I recommend to use for-each loops in collections, by using:
for(let item of allart.Items) {
.....
}
My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();
any idea with this is not working?
var xmlhttp = new XMLHttpRequest();
var url = "http://content.warframe.com/dynamic/worldState.php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
}
everytime i get status = 0.
i use the same method to get my script working with the twitch one, but can't get this one working.
thank for your help guys.
edit : ok thanks any idea what can i do to get the data from this site then?(if someone have any idea it will be awesome. as you can guess i can't edit the page who provide the date, but i know some people are able to get the JSON data) .
I started with this post some time ago, unfortunately it didn't work. I decided to look in the console, an found out that it was not sending the requests' headers as they were unsafe. So I decided to comment them out for now.
However there is one more problem: "http is not defined". How do I solve that?
// will use this to turn an object into a url encoded string
var serializeObject = function(obj) {
var output = '';
for(var attr in obj) {
if(obj.hasOwnProperty(attr)) {
output += attr + '=' + obj + '&';
}
}
return output.slice(0, -1);
};
var url = 'http://spacej.ru/sample/getMcoordinates.php';
// you need to serialize your data into key value pairs like the following
var exampleCoords = {
x: 31,
y: 74,
z: 28
};
// postData will be x=10&y=20&z=30
var postData = serializeObject(exampleCoords);
var request = new XMLHttpRequest();
request.open('POST', url, true);
/*
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", postData.length);
request.setRequestHeader("Connection", "close");
*/
// this function gets called when the request changes
// mistake pops up here !
http.onreadystatechange = function() {
// request was successful
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postData);
Try renaming the http variable to request. The http variable does not appear to be declared anywhere in your code.
I am reading a comma separated text file from the server, i get the valuse but when i chage the comma seprated variables in the file, it doesn't load the correct result int the browser
while browser persist the first time variable list only, whlile it works correct in IE, in firefox i am facig this proble.
How to sort it out
var arrUserTags = new Array();
var txt;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/TinyEditor/TextFile.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = xmlhttp.responseText;
arrUserTags = txt.split(",");
alert(arrUserTags.length);
parse();
}
}
// Add some values to the list box
function parse() {
for (i = 0; i < arrUserTags.length; i++) {
mlb.add(arrUserTags[i], arrUserTags[i]);
alert('hi');
}
}
You server is presumably sending caching instructions that tell browsers the URI for the text file won't change for a while.
Either configure the server to send no cache headers, or change the URI (e.g. by adding a rand() query string to it).