JSON response returning null array - javascript

Please help i have been trying from 1 hours and not able to get whats wrong
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
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 = arr[i].ID + arr[i].Title + arr[i].Description;
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I am trying to fetch details from http://it-ebooks-api.info/v1/book/2279690981 but it show only empty array being returned. What changes are required ?
Modification
I added [ ] on JSON object and it worked .. Please can someone explain me.
Thank in advance :)

The response does not contain an array, so the for loop is not needed and this should get you the result you are looking for:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var out = "";
var i;
out = "<p>" + response.ID + response.Title + response.Description + "<p>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
If you use the full listing available from http://it-ebooks-api.info/v1/search/php, then you need the for loop to go through the array like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse.Books);
}
}
function myFunction(Books) {
var out = "";
for (var i = 0; i < Books.length; i++) {
out += "<p>ID: " + Books[i].ID + "</p>" + "<p>Title: " + Books[i].Title + "</p>" + "<p>Description: " + Books[i].Description + "</p>"
}
document.getElementById("id01").innerHTML = out;
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
And to make it slightly more elegant, you could have a function that adds the book and if you get only one book you can call it directly from the onreadystatechange, and if you have the full listing, then you can loop it through, but still use the same function. So something like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttpo.responseText);
if (response.Books) { // If the response object has Books array, we pass it to the parseBooks functoin to add them all one by one.
parseBooks(response.Books)
} else {
addBook(response); // If there is no Books array, we assume that there is only one book and add it to the list with addBook function.
}
}
}
function addBook (Book) {
var text = document.getElementById("id01").innerHTML;
var body = "<p>ID: " + Book.ID + "</p><p>Title: " + Book.Title + "</p><p>Description: " + Book.Description + "</p>";
document.getElementById("id01").innerHTML = text + body; // Append the innerHTML with the new Book.
}
function parseBooks(Books) {
for (var i = 0; i < Books.length; i++) {
addBook(Books[i]) // Add all books in the array one by one
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>

You JSON feed is just a simple object and not an Array of objects. Note the opening curly braces in the returned feed: {}
You should then change your myFunction function so it goes through an object and not an array just by removing the for loop:
function myFunction(obj) {
var out = "",
id01 = document.getElementById("id01");
out = obj.ID + obj.Title + obj.Description;
id01.innerHTML = id01.innerHTML + out;
}
Edit:
You can use the same function then inside a for loop when you have to parse an Array of Objects.
Taking as a feed the JSON returned from http://it-ebooks-api.info/v1/search/php, you can retrieve the Books value and then loop through it:
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
var url2 = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var rslt = JSON.parse(xmlhttp.responseText);
console.log(rslt);
var books = rslt.Books;
for (var i = 0; i < books.length; i++)
{
myFunction(books[i]);
}
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();

Related

How to Get Attribute Value of XMLHttpRequest in Results

I have the following Microsoft Dynamics related XMLHttpRequest javascript function, and is encountering issue when attemtping to retrieve the entity attributes of the returned records.
The record managed to be created even though the conditions should have blocked it. It is likely that my following statement caused the issue:
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
function DisableInvalidRecordCreation(context) {
var saveEvent = context.getEventArgs();
var idNumber= Xrm.Page.getAttribute("IDNumber").getValue();
var category= Xrm.Page.getAttribute("Category").getValue();
var id = Xrm.Page.data.entity.getId();
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=1");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if (results.value.length > 0 && id == "") {
alert(results.value.length); //Displayed as 1
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
for (var i = 0; i < results.entities.length; i++) {
var returned_category= results.entities[i]["Category"];
alert(returned_category); //Not displayed
if (category == 100000003 && returned_category!= 100000003)
{
alert("Invalid record");
saveEvent.preventDefault();
}
}
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
This is happening because in your get request you are selecting only IDNumber field and not the one you desire like Category
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
Also it should not be var result1 = results.results[0];
rather it should be var result1 =results.value[0]
sample code snippet for reference
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var abc = results.value[i]["abc"];
var xyz = results.value[i]["xyz"];
var pqr = results.value[i]["pqr"];
var pqr_formatted = results.value[i]["pqr#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}

How to get website to load without clicking on the header

As of now I have to click on google to load google. Is there a way to just automatically load google without clicking on the title. I have tried removing the title and it will say unidentified and I click on that it will take me too google.
<html>
<body>
<div id="id01"></div>
<script>
var myArray = [
{
"display": "google",
"url":"https://google.com
},
]
myFunction(myArray);
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '' + arr[i].display + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>

reference error can't find xmlhttp

Trying to get my code to connect to API and retrieve a list of local farmers markets but keep getting Reference error that xmlhttp is not defined on line 40. Haven't caught any spelling errors and have tried moving chunks of code to see if they work at different positions.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>Markets</title>
<script>
window.onload = function() {
function myFunction(arr) {
out = "<h1>Markets</h1>";
var i;
for (i = 0; i < array.results.length; i++) {
out = out + "<em>" + item.marketname + "</em><br>" + details.marketdetails.Address + "</p>"
arr.results.forEach(printDetails)
}
document.getElementById("market_details").innerHTML = out;
}
var mybutton = document.getElementById("submit_btn")
mybutton.onclick = function() {
var xmlhttp = new XMLHttpRequest();
var zip = document.getElementById("zip").value
var url = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + zip;
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();
}
itemsProcessed = 0
function printDetails(item, index, array) {
console.log(item.marketname)
var xmlhttp = new XMLHttpRequest();
var url2 = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myDArr = JSON.parse(xmlhttp.responseText);
details = myDArr
//console.log(myDArr.marketdetails)
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
itemsProcessed++
}
}
</script>
</head>
<body>
<h1> Find Your Local Market!<h1>
Enter Zip Code:<input id="zip"></p><br>
<button id = "submit_btn">Submit</button>
<div id="market_details"></div>
</body>
The first problem is that you define the xmlhttp inside the onclick handler and you use it outside the handler:
mybutton.onclick = function() {
var xmlhttp = new XMLHttpRequest(); //<-- This must be used from inside the current function
//Your code here
xmlhttp.open("GET", url, true); //<-- put this inside the function
xmlhttp.send(); //<-- put this inside the function
}
The second problem is that you open and send the XMLHttpRequest inside the onreadystatechange handler:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myDArr = JSON.parse(xmlhttp.responseText);
details = myDArr
//console.log(myDArr.marketdetails)
};
itemsProcessed++
}
xmlhttp.open("GET", url2, true);//<-- put this outside the onreadystatechange handler
xmlhttp.send();//<-- put this outside the onreadystatechange handler
I hope this will help you.

Value of list populated with javascript

How to populate the select list with the values that I got with javascript?
I am sending a GET request to a .php site which gives me the respond in JSON format. Now I want to put those lines I got into the select list.
<select id = "list" name=log size=50 style=width:1028px>
<script type="text/javascript">
window.onload = function () {
var bytes=0;
var url = "/test/log.php?q='0'";
function httpGet(url)
{
var xhttp = new XMLHttpRequest();
var realurl = url + bytes;
xhttp.open("GET", url, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log(xhttp.responseText);
var response=JSON.parse(xhttp.responseText);
var log = response.key;
bytes = log.length;
}
};
xhttp.onerror = function (e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 2000;
function update() {
httpGet(url);
setTimeout(update, updateInterval);
}
update();
}
</script>
</select>
The response I get from log.php is "{"key":"whole log file"}". Now I want to store that reponse into a list and populate it every 2 seconds.
Loop over the contents of the returned string after JSON.parse-ing it. Create option elements from it, and insert those into the select.
var html = "";
var obj = JSON.parse(xhttp.responseText);
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>";
}
document.getElementById("list").innerHTML = html;
See JSBin

Need to use a variable in a getElementsByTagName function

The code below runs fine with a hard-coded tag name. I need to be able to call "loadDoc" with a variable that will return the tag I specify. I am rather new to JQuery and I'm not sure how to accomplish this.
Many thanks.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
}
xhttp.open("GET", "pyg280c.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var htext = "";
var x = xmlDoc.getElementsByTagName("PYP280CR");
for (i = 0; i <x.length; i++) {
htext += "<p>" + x[i].getElementsByTagName("PCST")[0].childNodes[0].nodeValue + "</p>";
}
document.getElementById("helptext").innerHTML = htext;
}
Since you say it works fine when you hardcode the tag name then as #Hackerman said pass the tagname into the loadDoc function. Pass it on to the myFunction function and simply use the tag name variable in the getElementByTagName(tag) function (no quotes around variables). It should work.
function loadDoc(myTagName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp, myTagName);
}
}
xhttp.open("GET", "pyg280c.xml", true);
xhttp.send();
}
function myFunction(xml, tag) {
var i;
var xmlDoc = xml.responseXML;
var htext = "";
var x = xmlDoc.getElementsByTagName("PYP280CR");
for (i = 0; i <x.length; i++) {
htext += "<p>" + x[i].getElementsByTagName(tag)[0].childNodes[0].nodeValue + "</p>";
}
document.getElementById("helptext").innerHTML = htext;
}
FYI - You mentioned jQuery. There is no jQuery in your code. jQuery probably would have made this easier.
Jquery version including some default ajax error handling:
function loadDoc(tag){
$.ajax({
url: "pyg280c.xml",
type: "GET",
dataType: "xml",
success: function(xml){
var xmlDOC = $.parseXML(xml.responseXML);
var x = $(xmlDOC).find("PYP280CR");
var htexts = $.map(x, function(el, idx){
return $(el).find(tag).children()[0].val();
}
htext = htexts.join(" ");
$('#helptext').html(htext);
},
error: function (xhr, ajaxOptions, thrownError){
console.log('status = ' + xhr.status);
console.log('error = ' + thrownError);
}
}

Categories

Resources