How to import an xml file with javascript - javascript

So i've been googling this for a while now and no solution seems to work for me.
Given that the url to the xml file (taken from valve api) is: playerSummariesXml
I tried ajax calls such as:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp);
}
xhttp.open("GET", playerSummariesXml, true);
xhttp.send();
}
Which returns the link to my website with a /0 appended to the end,
and
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
which says activexObject not declared
And other things...
Is there one resolute way to pull an xml file with javascript from a given url and read/display it?
I'm getting really confused considering this is super easy to do with php and don't see why I can't find a similar thing with javascript.

Can you try the below code,
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp);
}
}
xhttp.open("GET", playerSummaries.xml, true);
xhttp.send();
1: you need to check if browser supports XMLHttpRequest or ActiveXObject Object.
2: .open() and .send() should not be written inside onreadystatechange function.
3: check if your referencing your xml file correctly, playerSummaries.xml or playerSummariesXml.
You can see my below code on GIT hub , which uses plain JS ajax to support for html,css,json ,xml,image responses.
https://github.com/vijaysani/JavascriptAjaxWithDifferentResponses
let me know if your still facing any issues.

Related

How to get a certain line from xml from other webpage (url) in js?

const xhrRequest = new XMLHttpRequest();
xhrRequest.onload = function()
{
dump(xhrRequest.responseXML.documentElement.nodeName);
console.log(xhrRequest.responseXML.documentElement.nodeName);
}
xhrRequest.open("GET", "/website_url.xml")
xhrRequest.responseType = "document";
xhrRequest.send();
I'm trying to request a xml page from a page, but i'm unable to get certain line from xml in javascript. Thank you!
You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp
Here is an example function:
function SendRequest(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
// Success
}
};
xmlhttp.open("GET", "example.com", true);
xmlhttp.send();
}
Now, about getting a value from the xml document, you can use .getElementsByTagName(). Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange of the http request
if(this.readyState == 4 && this.status == 200){
let xmlDocument = this.responseXML;
console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
}
So if the xml document had an element like:
<TestTag>Hello</TestTag>
the function would print Hello

How to call REST service using JavaScript?

Using the code I found from one of the StackOverflow postings, I'm trying to call a REST service GET method. However, when the code runs it is not putting the GET format correctly in the URL.
Here's the code:
<!DOCTYPE html>
<script>
function UserAction(json)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
};
xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(json);
}
</script>
<form>
<button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
<label for="json">JSON:</label>
<input type="text" id="json" name="json"><br><br>
</form>
</html>
The expected format of this GET REST service would be:
http://localhost:8080/isJsonValid/json
(where json in the line above is the actual JSON sent as a parameter.)
Yet, what is shown in the URL line includes the project, directory and the URL has the ?name=value syntax.
Since the GET doesn't match the simple http://localhost:8080/isJsonValid/json format, I get a 404 error.
I realize there's something obvious I'm missing.
Thanks to all for suggestions.
If you need to send data you need to either send it as a query param or as the body. If you want to send it as a body need to use POST type. Below is the example of POST type.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach(movie => {
console.log(movie.title)
})
} else {
console.log('error')
}
}
// Send request
request.send()
For post Request. As I don't have any API with me I have used get API URL.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText)
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
Thanks all for the great input and help!
The best solution for me was to just use, as suggested, a POST. The GET was always putting the "?" in the URL even if I concatenated it, That "?" isn't how the REST service interprets the GET parameters so it wouldn't work that way. In the REST framework I'm using, GET parameters are just concatenated with one or more "/" as separators in the URL.
Appreciate all the terrific help here on SO. :)

How do i put headers in an api call?

I am making an api call to
http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter
I have changed the appropriate information in the URL to reflect the correct host address/port / user id.
When that is complete, the page requests that I log on with a Username and Password.
I can manually enter this information, and receive the XML that I need. This is not Ideal. I would rather have a form that passess in this information.
To my understanding, this information is passed within the "headers". I have tried to look up how to do this, and even attempted using postman without much luck. I am not sure how to do this.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter", true);
xhttp.send();
}
per w3 schools I can use setRequestHeader() which adds a label/value pair to the header to be sent.
I have tried
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter", true);
xhttp.send();setRequestHeader(Username:myUserName,Password:myPassword);
}
with no resolution. once i get this working i will set up the form and pass in the values.
You are using setRequestHeader in the wrong way and calling send before setting headers in any case.
Try with
xhttp.setRequestHeader('Username', myUserName);
xhttp.setRequestHeader('Password', myPassword);
xhttp.send(); // only call send after setting up the headers
xhttp.setRequestHeaders(name, value) and it should be invoked before xhttp.send(). mdn

Import text file into a WordPress widget using JavaScript

I would like to have a WordPress text widget with a javascript that would populate the widget with text from some .txt file (this is to allow dynamic content on a cached page by allowing me to update that text file with new HTML content).
I found this thread and tried the following code, which did not work:
<script type="text/javascript">
function read(textFile){
var xhr=new XMLHttpRequest;
xhr.open('GET',textFile);
xhr.onload=show;
xhr.send()
}
function show(){
var pre=document.createElement('pre');
pre.textContent=this.response;
document.body.appendChild(pre)
}
read('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
</script>
Any suggestions on how to fix it?
Do you know Javascript or are you just hoping for a copy and paste solution? Perhaps try reworking this code here:
function getStuff(url) {
var xhttp, jsonData, parsedData;
// check that we have access to XMLHttpRequest
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// get the data returned from the request...
jsonData = this.responseText;
// ...and parse it
parsedData = JSON.parse(jsonData);
// return the data here
// if the data you're returning is an object
// you need to know the endpoints
// for example, if there was a username,
// you might return parsedData.username
var something = parsedData.endpoint;
// debug / test
console.log(something);
var elementToShowStuffIn = document.getElementById('theIDOfTheElement');
elementToShowStuffIn.innerHTML = something;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
getStuff('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
Yes, this works. Just replace this line here: var something = parsedData.foo.bar;

XMLHttpRequest alters text in UTF-8

While processing a huge XML client-side, got stuck with the following issue: some unicode characters are replaced with unreadable sequences, so server cannot parse that XML. Testing like this:
var text = new XMLSerializer().serializeToString(xmlNode);
console.log(text);
var req = new XMLHttpRequest();
req.open('POST', config.saveUrl, true);
req.overrideMimeType("application/xml; charset=UTF-8");
req.send(text);
Logging still shows the correct string:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
While in the request (Chrome dev tools) and at server side it appears modified like this:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
Original encoding of the XML file is UTF-8, too. Absolutely the same behavior when using jQuery.
Check that overrideMimeType use uppercase "UTF-8" or lowercase "utf-8"
Make sure that string before javascript calculation was in utf-8 (check page charset)
Use escape/encodeURIComponent/decodeURIComponent before send it to server and unescape it on server
Try application/x-www-form-urlencoded ans send xml like plain text
P.S. Modified string is in ISO-8859-15
It seems to do so.
I have here data json parameter that includes a string "Lääke" (finnish word), that i sent to server via ajax.
This did NOT work, server app did not receive 'ää' but '??':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.send();
This did work, server received 'ää':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
//orderStatusElement[0].innerHTML = "<b>Palvelimella jokin meni vikaan. Yritä myöhemmin uudelleen </b>";
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

Categories