XML response text is undefined - javascript

I am making a call to an external server and am getting a valid response back with data. If I dump that data into console.log() I can see the data that I'm looking for. However the returned data is XML and if I try and use the getElementsByTagName method on the response text I get the error Uncaught TypeError: searchResults.getElementsByTagName is not a function. I checked and searchResults is undefined, which I'm assuming is my problem, I'm just not sure how to fix it.
function getBggData() {
var searchTerm = document.getElementById("searchTerm").value;
// console.log("Search Term = " + searchTerm);
var httpURL = "https://www.boardgamegeek.com/xmlapi2/search?type=boardgame,boardgameexpansion&query=" + searchTerm
// console.log("URL used is = " + httpURL);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
displayData(this);
}
};
xhttp.open("GET", httpURL, true);
xhttp.send();
};
function displayData(xml) {
var i;
var searchResults = xml.responseText;
console.log(searchResults.type);
console.log(searchResults);
var table = "<tr><th>Game</th><th>Year Released</th></tr>";
var x = searchResults.getElementsByTagName("item");
document.getElementById("resultsHeader").innerHTML = "Search Results = " + x + " items.";
document.getElementById("searchResults").innerHTML = table;
};

you can do like this,
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml,"text/xml");
console.log(xmlDoc.getElementsByTagName("title")[0]);
here we are parsing the xml and getting it to the variable xmlDoc

var searchResults = xml.responseXML;

Related

If/else statement in case JSON endpoint doesn’t exists

I am trying to create a scenario where if endpoint doesn’t exists, function still returns a value.
When the endpoint exists, I get a value, no problem.
var main = function(){
json_url = "http://ergast.com/api/f1/current/next.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
let race = " ";
if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
race = " ";
}
else {
race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}
I get the following result
2022-07-09
But in case the endpoint doesn’t exists, I get a error.
var main = function(){
json_url = "http://ergast.com/api/f1/current/last.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
let race = " ";
if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
race = " ";
}
else {
race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}
How can I rectify this. Do I have to assign something other than undefined in this case.
Use as below:
var main = function(){
json_url = "http://ergast.com/api/f1/current/last.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
return weather.MRData.RaceTable.Races[0].date;
}
or:
race = weather.MRData.RaceTable.Races[0].FirstPractice.date;
or:
race = weather.MRData.RaceTable.Races[0].Qualifying.date;

mediawiki api can not display the results from array

Hello you wonderful people, I am trying to build JavaScript file to extract information from Wikipedia based on search value in the input field and then display the results with the title like link so the user can click the link and read about it. So far I am getting the requested information in(JSON)format from Mediawiki(Wikipedia) but I can't get it to display on the page. I think I have an error code after the JavaScript array.
I'm new at JavaScript any help, or hint will be appreciated.
Sorry my script is messy but I am experimenting a lot with it.
Thanks.
var httpRequest = false ;
var wikiReport;
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
} catch (requestError) {
return false;
}
return httpRequest;
}
function getWiki(evt) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
var search = document.getElementsByTagName("input")[0].value;//("search").value;
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort();
httpRequest.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=" + search , true);//("get", "StockCheck.php?t=" + entry, true);
//httpRequest.send();
httpRequest.send();
httpRequest.onreadystatechange = displayData;
}
function displayData() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
wikiReport = JSON.parse(httpRequest.responseText);//for sunchronus request
//wikiReport = httpRequest.responseText;//for asynchronus request and response
//var wikiReport = httpRequest.responseXML;//processing XML data
var info = wikiReport.query;
var articleWiki = document.getElementsByTagName("article")[0];//creating the div array for displaying the results
var articleW = document.getElementById("results")[0];
for(var i = 0; i < info.length; i++)
{
var testDiv = document.createElement("results");
testDiv.append("<p><a href='https://en.wikipedia.org/?curid=" + query.pages[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
var newDiv = document.createElement("div");
var head = document.createDocumentFragment();
var newP1 = document.createElement("p");
var newP2 = document.createElement("p");
var newA = document.createElement("a");
head.appendChild(newP1);
newA.innerHTML = info[i].pages;
newA.setAttribute("href", info[i].pages);
newP1.appendChild(newA);
newP1.className = "head";
newP2.innerHTML = info[i].title;
newP2.className = "url";
newDiv.appendChild(head);
newDiv.appendChild(newP2);
articleWiki.appendChild(newDiv);
}
}
}
//
function createEventListener(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener) {
form.addEventListener("submit", getWiki, false);
} else if (form.attachEvent) {
form.attachEvent("onsubmit", getWiki);
}
}
//createEventListener when the page load
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
Mediawiki api link
https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=
You are wrong some points.
1)
var articleW = document.getElementById("results")[0];
This is wrong. This will return a element is a reference to an Element object, or null if an element with the specified ID is not in the document. Doc is here (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
The correct answer should be :
var articleW = document.getElementById("results");
2)
var info = wikiReport.query;
for(var i = 0; i < info.length; i++) {}
The info is object . it is not array , you can't for-loop to get child value.
wikiReport.query is not correct wiki data. The correct data should be wikiReport.query.pages. And use for-in-loop to get child element
The correct answer:
var pages = wikiReport.query.pages
for(var key in pages) {
var el = pages[key];
}
3) This is incorrect too
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. You are using the method to adds a string . This will cause error. Change it to node element or use append method instead
I have created a sample test.You can check it at this link below https://codepen.io/anon/pen/XRjOQQ?editors=1011

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

jQuery.post() dynamically generated data to server returns empty response

I'm generating a series of variables in a loop (using JS), and I'm assigning them an .id and a .name based on the current index. At each loop I'm sending a request to the server using jQuery.post()method, but the returning response is just an empty variable.
Here's the code:
JavaScript
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
$(document).ready(function(){
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
});
}
PHP
<?php
$index = $_POST['ind'];
$myVar = $_POST['myVarID'.$index];
echo $myVar;
?>
Response: Server response: ''
If I instead set a static index in JS code, getting rid of the loop, so for example:
var index = 0;
I get the expected result: Server response: myVarName0
Why is this happening? And how can I solve it?
Assuming the php file is in order. I use this:
function doThing(url) {
getRequest(
url,
doMe,
null
);
}
function doMe(responseText) {
var container = document.getElementById('hahaha');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
var thing = "script.php?" + url;
req.open("GET", thing, true);
req.send(null);
return req;
}
then use it like this:
doThing("myVarID="+myVar.id+"&i="+index);
also, you will have to change your PHP to something like this:
<?php
$index = $_GET['ind'];
$myVar = $_GET['myVarID'.$index];
echo $myVar;
?>
Obviously this code needs to be edited to suit your own needs
the function doMe is what to do when the webpage responds, in that example I changed the element with the id hahaha to the response text.
This won't win you any prizes but it'll get the job done.
Solution
It is working fine removing:
$(document).ready()
Working code
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
}

Unexpected end of input error with chrome.tabs.query

I've been struggling with this and have had no luck. I've included the error and most of the context around the block in question.
var successURL = 'https://www.facebook.com/connect/login_success.html';
var userFirstName = ''
var userEmail = ''
function onFacebookLogin(){
if (localStorage.getItem('accessToken')) {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.indexOf(successURL) !== -1) {
var params = tabs[i].url.split('#')[1];
var accessToken = params.split('&')[0];
accessToken = accessToken.split('=')[1];
localStorage.setItem('accessToken', accessToken);
chrome.tabs.remove(tabs[i].id);
console.log(accessToken);
pullSecurityToken();
findFacebookName();
}
}
});
}
}
chrome.tabs.onUpdated.addListener(onFacebookLogin);
function pullSecurityToken(){
var pointUrl = "localhost:3000/api/v1/retrieve_token_for/" + localStorage.accessToken + "/" + localStorage.securityToken;
var xhr = new XMLHttpRequest();
xhr.open("GET", pointUrl, true);
alert(JSON.parse(xhr.responseText));
}
var response = ''
function findFacebookName(){
if (localStorage.accessToken) {
var graphUrl = "https://graph.facebook.com/me?access_token=" + localStorage.accessToken;
console.log(graphUrl);
var xhr = new XMLHttpRequest();
xhr.open("GET", graphUrl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == '401'){
alert("Security Token Invalid, please check and try again.");
}
response = JSON.parse(xhr.responseText);
userFirstName = response.first_name
userEmail = response.email
console.log(response);
}
}
}
xhr.send();
}
Here's the error:
Error in response to tabs.query: SyntaxError: Unexpected end of input
at onFacebookLogin (chrome-extension://dapeikoncjikfbmjnpfhemaifpmmgibg/background.js:7:17)
Even if you use a synchronous request, you still need to send it. So add an xhr.send(); after the xhr.open inside pullSecurityToken.
As Felix Kling points out in the comments, the lack of send will directly cause your error, because the responseText property is still an empty string and such a string is not valid JSON whereas "" would be valid JSON.

Categories

Resources