How can convert a XML document into a Js String? - javascript

I need this XML document (register.xml):
<?xml version="1.0" encoding="utf-8"?>
<All>
<Shoe>
<Name>All Stars</Name>
<BrandName>Converse</BrandName>
<ReleaseDate>10/2/08</ReleaseDate>
</Shoe>
<Shoe>
<Name>All Star1s</Name>
<BrandName>Converse1</BrandName>
<ReleaseDate>11/2/08</ReleaseDate>
</Shoe>
Store in this Javascript variable:
var ShoesXML
Because I actually create a html table from this Js variable that contains XML data this way:
`
var ShoesXML = "<All><Shoe><Name>All Stars</Name><BrandName>Converse</BrandName><ReleaseDate>10/2/08</ReleaseDate><Picture>pic.jpg</Picture></Shoe><Shoe><Name>All Star1s</Name><BrandName>Converse1</BrandName><ReleaseDate>11/2/08</ReleaseDate></Shoe></All>";
$(document).ready(function() {
xmlDoc=$.parseXML( ShoesXML );
$(xmlDoc).find("Shoe").each(function(i, n) {
var html = "<tr>\n" +
"<td><span>" + $(n).find("Name").text() + "</span></td>\n" +
"<td>" + $(n).find("BrandName").text() + "</td>\n" +
"<td>" + $(n).find("ReleaseDate").text() + "</td>\n" +
"</tr>";
$("table.shoetable tbody").append(html);
});
});
THE PROBLEM IS that with this way
var ShoesXML = "<All><Shoe><Name>All Stars</Name><BrandName>Converse</BrandName><ReleaseDate>10/2/08</ReleaseDate><Picture>pic.jpg</Picture></Shoe><Shoe><Name>All Star1s</Name><BrandName>Converse1</BrandName><ReleaseDate>11/2/08</ReleaseDate></Shoe></All>";
I'm setting the value manually, but I need to get it from the actual (register.xml) document and then store it in:
var ShoesXML
For later use.

Related

Steam webAPI Jquery script. return

I have a problem with this script I got from github.
I added value.appid myself because that seemed logical but I believe it data.response.games is a response for all my games and its values.
How do I get them to either print or see what is defined?
I would need something like value.description or maybe value.ownedAchievements.
I want to see what data i have to work with for the CSV.
I am a complete noob with this so be nice, also too expert comments I will have no clue what to do with cause I have never touched javascript in my life before.
I am currently learning HTML CSS and PHP.
I have a Docker running with my SQL as well... is there also a way to re-engineer this script to directly put these value.* values inside a column? without the need to download a CSV and import it manually all the time.
<script src='http://code.jquery.com/jquery-2.1.1.min.js' type='text/javascript'></script>
<script type='text/javascript'>
$(document).ready(function () {
function exportSteamToCSV(filename) {
var url = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + $('#webkey').val() + "&steamid=" + $('#steamid').val() + "&format=json&include_appinfo=1";
$.get(url, function(data) {
colDelim = ',';
rowDelim = '"\r\n"';
csv = '"Name","Playtime","Store' + rowDelim;
$.each(data.response.games, function(index, value) {
url = "http://store.steampowered.com/app/" + value.appid;
csv += value.name + colDelim + value.playtime_forever + colDelim + value.appid + colDelim + url + rowDelim;
//csv += value.name + colDelim + value.playtime_forever + colDelim + url + rowDelim; Was correct eerste versie
});
csv += '"';
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
var link = document.createElement("a");
link.download = filename;
link.href = csvData;
link.target = "_blank";
link.click();
});
};
$(".export").on('click', function (event) {
// CSV
exportSteamToCSV.apply(this, ['steamgames.csv']);
});
});
</script>
Solved this later in Laravel with the query from the APU. the URL just gets all the data.. from there you casn pretty much do anything.
$url = "https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=XXXXXXXXXX&steamid=XXXXXXXXXXformat=json&include_appinfo=1";
$jsondata = file_get_contents($url);
$parsed = json_decode($jsondata,true);
$games = $parsed['response']['games'];
echo SteamGame::count();
foreach($games as $game){
echo $game['name']."<br>";
$imgid = $game['appid'];
SteamGame::updateOrCreate(['name' => $game['name']],[
'name' => $game['name'],
'appID' => $game['appid'],
'storeURL' => "https://store.steampowered.com/app/".$game['appid'],
'imageURL' => "https://cdn.akamai.steamstatic.com/steam/apps/${imgid}/header.jpg",
'minutesplayed' => $game['playtime_forever']
]);

Why does loading a new html page reset javascript variables? How do I save those variables?

So I have this piece of code in an html file called demo.html
<img class="card-img-top" src="src/San_Francisco_Opera_House.jpg"
onclick="buyFunction('src/San_Francisco_Opera_House.jpg',
'SF opera house', 'price: $360,000')" alt="Card image cap">
This runs this javascript function which loads a new HTML page. I want to display the image in the new page,
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
setPicturePriceAndAddress();
});
};
function setPicturePriceAndAddress() {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
But all the values gets reset. Or is there another way to send information to the new html file without having to save variables?
You could potentially store the variables in session storage on demo.html and then call them inside of buy.html
demo.html:
function buyFunction(housePhotoString, addressString, priceString) {
sessionStorage.setItem('housePhoto', housePhotoString);
sessionStorage.setItem('address', addressString);
sessionStorage.setItem('price', priceString);
$(location).attr('href', 'buy.html');
}
buy.html:
$(document).ready(function() {
var housePhotoString = sessionStorage.getItem('housePhoto');
var addressString = sessionStorage.getItem('address');
var priceString = sessionStorage.getItem('price');
setPicturePriceAndAddress(housePhotoString, addressString, priceString);
});
function setPicturePriceAndAddress(housePhotoString, addressString, priceString) {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + housePhotoString + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + addressString + "</h4>" +
"<p class=\"card-text\">" + priceString + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
JavaScript is a client side language. Basically it is run on the web browser when it loads the page. Therefore, when a particular page is unloaded (moving away from the page, going to another page, closing the tab etc), the javascript values used in the page is flushed unless you take measures to save them.
For this, you can look into localStorage which saves the data in the browser and can be reused. Another method you can use is to set cookies which can also allow you to store and retrieve data from the user's browser between page loads.
You can store the variable in the localstorage and access the variables from anywhere under the same domain name , i.e you can use it another html file specified under same domain name
for example for your sample I created a little http server and then made a POC out of that
say your main script is contained in some index.html as your code block like this
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<script type="text/javascript">
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
//pass the houseAttributes object to setPicturePriceandAddress for better use of functions in js
setPicturePriceAndAddress(houseAttributes);
});
};
function setPicturePriceAndAddress(houseAttributes) {
let strHTML = "";
strHTML =
"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
console.log('data',strHTML);
//storing only for one time
var dataToSave = localStorage.setItem('strHtml',strHTML)
//storing for multiple time
var arr = [];
if(localStorage.getItem('arrOfStr')){
arr = JSON.parse(localStorage.getItem('arrOfStr'))
}
arr.push(strHTML);
localStorage.setItem('arrOfStr',JSON.stringify(arr))
$("#housePhotoBuy").html(strHTML);
};
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
</script>
</html>
Then you are accessing if in your file buy.html file
<html>
<head></head>
<body>
<h1>Buy</h1>
<script type="text/javascript">
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
getSavedValue()
</script>
</body>
</html>
and under the same domain name like for example if your index.html is in http://localhost:5000
and your buy.html is in http://localhost:5000/buy.html then you will be able to retrive all values stored in the buy.html in form of array if you want to store all the responses for a particular client or you can just access one single variable.I have made both the example you can use whatever you like according to your choice. If it's less than 5mb or something like that you can use localstorage and it is better to use than in cookie or session storage because they serve different purposes and they should be kept apart for saving extra data like this buy information for a particular client

Dynamically replacing HTML with getJSON by click of button

I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:
$(document).ready(function() {
$("#nav_list a").click(function(evt) {
buildName = "../json_files/" + $(this).attr("title") + ".json";
alert(buildName);
document.getElementById("main").innerHTML = "";
$.getJSON(buildName, function(data) {
$.each(data, function() {
$.each(this, function(key, value) {
$("#main").append(
"<h1>" + value.title + "</h2>" +
"<img src='" + value.image + "'>" +
"<h2>" + value.month + "<br>" + value.speaker + "</h2>" +
"<p>" + value.text + "</p>";
);
}); // inner each
}); // outer each
)}; // end of getJSON
}); // end click
}); // end ready
Notes:
The alert(buildName) is for my own testing.
The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.
Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).
I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:
$.getJSON(buildName, function(data) {
$.each(data, function(key, value) {
$("#main").append(
("#main h1").innerHTML.replace("<h1>" + value.title + "</h2>");
("#main img").innerHTML.replace("<img src='" + value.image + "'>");
("#main h2").innerHTML.replace("<h2>" + value.month + "<br>" + value.speaker + "</h2>");
("#main p").innerHTML.replace("<p>" + value.text + "</p>");
)
}); // endeach
)}; // end of getJSON
What do you guys think? I am absolutely stumped.
Remove the semi-colon at the end inside your .append(). Otherwise, I'm not sure. I wanted to comment this instead of answering but I lack the reputation. With your second attempt, those replace calls shouldn't be made inside the .append(). Good luck!
I think that the problem might be your json path that you construct.
Try using a standard path "../file.json" or "file.json" to check if you have the result you want or if the $.getJSON() is still ignored.
About the other errors: What is your devel. environment?
I also noticed that you have a bracket mismatched in your append function at the title part. So,
"<h1>" + value.title + "</h2>" +
would have to be changed to..
"<h1>" + value.title + "</h1>" +
I have re-created a sample of your site and it all seems to run fine using your code and .json files.
I just needed to modify the code as shown below. In this case, if you have a heading it will also clear the heading in your website.
<!--json retrieve script starts here -->
<script>
$(document).ready(function(){
$(":button").click(function() {
buildName = "../json_files/" + $(this).attr("title") + ".json";
alert(buildName);
//$("#main").empty();
document.getElementById("main").innerHTML = "";
$.getJSON(buildName, function(data){
//$.each(data, function() {
// $.each(data, function(key, value){
$("#main").append(
"<h1>" + data.title + "</h2>" +
"<img src='" + data.image + "'>" +
"<h2>" + data.month + "<br>" + data.speaker + "</h2>" +
"<p>" + data.text +"</p>"
);
// });
//});
});
});
});
</script>
<!--json script end here -->
NOTE: I have swapped the link with button to wire the event for this example.
You can also use multiple file entries in a single .json file in the format shown below:
{
"story1":"/jsonfile1.json",
"story2":"/jsonfile2.json",
"story3":"/jsonfile3.json"
}
which you would then parse with an $.each(data,function(key,value) where value would be the filename to be requested via $.getJSON so you can have multiple entries handled by a single file.
There were a few syntax errors - a parenthesis and curley bracket out of order, misplaced semi-colon, things of the like. The logic was correct.
Thanks all for the replies!

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

jQuery read XML URL

My below code working well but i need to import XML data from xml URL not from HTML file like this
if i need to retrieve image from XML how i can do that.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(document).ready(function(){
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).find('show').each(function(){
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
//alert($('#show_table').html());
})
all what i need is change this var xml = "9/8 ... " to let the JQuery code read from the ONLINE URL
If you need to load XML data from the URL, you need to execute AJAX request, it may be something like this:
$(function() {
$.ajax({
type: "get",
url: "http://yoursite.com/yourfile.xml",
dataType: "xml",
success: function(data) {
/* handle data here */
$("#show_table").html(data);
},
error: function(xhr, status) {
/* handle error here */
$("#show_table").html(status);
}
});
});
Keep in mind, if you use AJAX you can place .xml file on the same domain name. In other case you need to set up cross-origin resource sharing (CORS).
EDITED:
I modified your code, now it appends td element to your table. But xml is still inside html.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(function() {
$(xml).find('show').each(function() {
console.log(this);
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append($(html));
});
});
But you need to modify your html file, check my solution here: http://jsfiddle.net/a4m73/
EDITED: full solution with loading xml from URL
I combined two parts described above, check here: http://jsfiddle.net/a4m73/1/
Use jquery-xpath, then you can easily do what you want like:
$(xml).xpath("//shows/show");
if you want know more about xpath just take a look on XML Path Language (XPath) document.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>";
$(document).ready(function () {
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).xpath("//shows/show").each(function () {
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
})

Categories