Ajax request: undefined - javascript

Hello there i wanted to request an api with ajax.
The api has plain json (what i thought)
now i set up an ajax request in javascript but i get an undefined error for the variables.I think i know the problem but I dont know an answer yet.
<script type="text/javascript">
document.getElementById("button").addEventListener('click', loadUsers);
// Load Github USers
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats){
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+stats[i].p_level+'</li>'+
'<li>p_currentmmr: '+stats[i].p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}
This was the javascript part
the json file from the api looks like this
{"results":
[{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"},
{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"}],
"totalresults":2}
My Guess is that the json file isnt a normal array because it contains the "results": and "totalresults" property.
Does Anyone know how to fix it without getting into the json file?

You're going to want to loop through stats.results instead of just stats, see the following example:
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats.results){
var row = stats.results[i];
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+row.p_level+'</li>'+
'<li>p_currentmmr: '+row.p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}

Related

How do I get scripts to work after a xhttps request

So I have a search page that I'm working on that has a given JSON object as a return. When I click the search button, it's supposed to load up the results page (without a refresh), with the JSON parsed and placed neatly in div's using JS (I can't use jQuery) (this code is in ajax_info.html). Everything independently works. However, when I try to use AJAX with JavaScript, it doesn't load. Again, everything works when loaded independently. But right now, no scripts are working inside the script tag of ajax_info.html. Is there a better method that I could use to update the page with the results page without reloading? This is my code:
function loadDoc() {
var setInnerHTML = function(elm, html) {
elm.innerHTML = html;
Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
const newScript = document.createElement("script");
Array.from(oldScript.attributes)
.forEach( attr => newScript.setAttributes(attr.name, attr.value) );
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
oldScript.parentNode.replaceChild(newScript, oldScript);
});
}
console.log('hello');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 && xhttp.readyState == XMLHttpRequest.DONE) {
setInnerHTML(document.getElementById("demo"),this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "ajax_info.html", true);
xhttp.send();
}
and this is the relevant code for ajax_info.html:
<script>
alert("hello");
console.log('adfasdf');
const searchResults = {
//Json stuff
}
// console.log(searchResults);
//const obj = JSON.parse(searchResults);
//document.getElementById("demo2").innerHTML = searchResults.response.docs[0].es_description;
let text="";
for(let i=0; i<searchResults.response.docs.length; i++) {
text+="<div class='p-3 border rounded-3'>";
text+="<a href=''>"+ "<strong class='text-primary largeText'>" + searchResults.response.docs[i].es_title + "</strong></a>";
text+="<div class='largeText'>" + searchResults.response.docs[i].es_description + "</div>";
text+="<div>" + searchResults.response.docs[i].author + "</div>";
text+="<div>" + searchResults.response.docs[i].site + "</div>";
text+="<div>" + searchResults.response.docs[i].es_date + "<a class='text-success'> " + searchResults.response.docs[i].site + "</a></div>";
//text+="<a href='url'>"+ searchResults.response.docs[i].es_title + "</a>";
text+="</div>";
//text+=searchResults.response.docs[i].author + "<br>";
//text+=searchResults.response.docs[i].site + "<br>";
//text+=searchResults.response.docs[i].es_date + "<br>";
//text+="<p></p>";
document.getElementById("demo2").innerHTML = text;
console.log(i);
}
//alert(searchResults.response.docs.length);
</script>
demo2 is the id of the div inside of ajax_info and demo is the id of the body of index.html

How do i print from a json string array using javascript within html code

Example output image
I have a JSON file which I populate from excel via a bit of vba code. It comes out in the format of:
[{"Name":"testing1","Data":"15"},{"Name":"testing2","Data":"1"},{"Name":"testing3","Data":"3"}]
I wish to take this data to an HTML webpage. I want to print it as a simple list.
I've printed from a json object using something like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var people = response.people;
var output = '';
for (var i = 0; i < people.length; i++) {
//console.log(people[i].name);
output += '<li>' + "Name: " + people[i].name + " Age:" + people[i].age + '</li>';
}
document.getElementById('people').innerHTML = output;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
I want to know how to change it to print from the string array without the object.

Struggling to understand AJAX w/ Javascript

I am very new to programming.
I am trying to output a list of (my two empty) GitHub repositories into a <p> with id="repos". When I run the code, I receive the error message:
Uncaught ReferenceError: id is not defined at XMLHttpRequest.gitHubRequest.onreadystatechange
And I'll receive this error for every the other two keys I want to pull the value from (full_name & html_url).
Can someone give me some insight as to how I can make this code work? it needs to be Javascript- its for a class. Thanks you!
let gitHubRequest = new XMLHttpRequest();
gitHubRequest.open('GET', 'https://api.github.com/users/billythesailor/repos', true);
gitHubRequest.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var repos = JSON.parse(this.responseText);
var output = '';
for(var i in repos){
output +=
'<ul>' +
'<li>ID: ' +id[i]+'</li>' +
'<li>Full Name: ' +full_name[i]+'</li>' +
'<li>URL: ' +html_url[i]+'</li>'+
'</ul>'
}
document.getElementById('repos').innerHTML = output;
}
}
gitHubRequest.send();
The issue is that the id, full_name, and html_url are fields on the repo objects, but you're accessing them as defined arrays. So id[i] needs to change to repos[i].id and so on. I've updated your example below!
let gitHubRequest = new XMLHttpRequest();
gitHubRequest.open('GET', 'https://api.github.com/users/billythesailor/repos', true);
gitHubRequest.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var repos = JSON.parse(this.responseText);
var output = '';
for(var i in repos){
output +=
'<ul>' +
'<li>ID: ' + repos[i].id +'</li>' +
'<li>Full Name: ' + repos[i].full_name +'</li>' +
'<li>URL: ' + repos[i].html_url +'</li>'+
'</ul>'
}
document.getElementById('repos').innerHTML = output;
}
}
gitHubRequest.send();
<div id="repos"></div>
Also, if you're new to Javascript and interested in making ajax requests, I'd look into the Fetch API, which is bit cleaner to use.
fetch('https://api.github.com/users/billythesailor/repos')
.then(res => res.json())
.then(repos => {
// do stuff with the repo data!
});

trying to use data detail in buttons but getting a unexpected error

I am using the following code which displays my items from a database on the screen. I have tried adding a button to each of them using data detail as this is how i am passing data through local storage. However when i run this code i get an error message with an unexpected { in the html += line, can you not do this?
function display(results) {
article = document.getElementById("homeArticle");
var html = '';
for (var i = 0; i < results.length; i++){
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
var quant = item.P_QUANTITY;
// next I add to the string that we want to place on the page
html += '<section id="homePageSection"><div id="test"> <p>Name: ' + name + '</p><p>Description: ' + description + '</p><p>Price: £' + price + '</p><p>Quantity: ' + quant + '</p><button data-detail='{"name":"banana", "cost": "19"}'>Bananas</button></div></section>';
};
article.innerHTML = html;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var results = JSON.parse(this.responseText);
display(results.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
You need to escape the the ' around your stringed object using backslash.
Like this
'<button data-detail=\'{"name":"banana", "cost": "19"}\'>Bananas</button>'
You would need to escape the single quotes inside your string:
'</p><button data-detail=\'{"name":"banana", "cost": "19"}\'>Bananas</button></div></section>'

Get Particular node value in array from xml

I have one variable name as result in javascript Function.
The result variable's value is xml,
I need to form an Array with the opportunityid(which is highlighted in Image) values only.
how to get from the particular node value and form a array.?
I was used following Function,
function guid(){
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
"<soap:Body>" +
"<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
"<q1:EntityName>opportunity </q1:EntityName>" +
"<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
"<q1:Attributes>" +
"<q1:Attribute>opportunity id</q1:Attribute>" +
"</q1:Attributes>" +
"</q1:ColumnSet>" +
"<q1:Distinct>false</q1:Distinct>" +
"</query></RetrieveMultiple>" +
"</soap:Body></soap:Envelope>";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var result = xmlHttpRequest.responseXML.xml;
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.loadXML(result);
}
As I can see the structure of your xml, it is as follows:
<soap:Body>
<RetrieveMultipleResponse>
<RetrieveMultipleResult>
<BusinessEntities>
<BusinessEntity>
<q1:oppourtunityid>
</q1:oppourtunityid>
</BusinessEntity>
</BusinessEntities>
</RetrieveMultipleResult>
</RetrieveMultipleResponse>
</soap:Body>
for this you can make use of DOM Element as follows:
var businessEntites = result.getElementsByTagName('BusinessEntity');
var oppidArr = [];
for(var i=0; i<businessEntities.length; i++)
{
var oppid = businessEntites.item(i).getElementsByTagName('q1:oppourtunityid').item(0).childNodes[0].nodeValue;
oppidArr[i] = oppid;
}
I guess, you should try below code, I have copied some of it from Mozilla's site as it's having best practice code with conditions :)
function guid(){
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
"<soap:Body>" +
"<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
"<q1:EntityName>opportunity </q1:EntityName>" +
"<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
"<q1:Attributes>" +
"<q1:Attribute>opportunity id</q1:Attribute>" +
"</q1:Attributes>" +
"</q1:ColumnSet>" +
"<q1:Distinct>false</q1:Distinct>" +
"</query></RetrieveMultiple>" +
"</soap:Body></soap:Envelope>";
var xmlHttpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!xmlHttpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpRequest.onreadystatechange = getContents;
xmlHttpRequest.open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
function getContents() {
if (xmlHttpRequest.readyState === 4) {
if (xmlHttpRequest.status === 200) {
var xmldoc = xmlHttpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('q1:Attributes').item(0);
alert(root_node.firstChild.data);
} else {
alert('There was a problem with the request.');
}
}
}
}

Categories