Displaying Order History without using tables - javascript

i am new to UI devlopment.I use to do coding but i have been asked to get the value from xml and display order history without using tables.I am getting xml from jax-rs and want to display on html.
My Xml is:
<orderHistory>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039011
</detail_url>
<lineItemCount>ssolineItemCount</lineItemCount>
<order_id>7039012</order_id>
<sort_date>1448316</sort_date>
<status>Shipped</status>
<store_label>SSO Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>11.76</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039009
</detail_url>
<lineItemCount>tsolineItemCount</lineItemCount>
<order_id>7039009</order_id>
<sort_date>1448316</sort_date>
<status>Cancelled</status>
<store_label>Teacher Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>15.25</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orderHistory>
My Html is like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function init() {
// put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly
//xmlhttp = new XMLHttpRequest();
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/NewShot/schl-api/myresource/com/";
xmlhttp.open('GET', url, false);
xmlhttp.send();
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
//alert('Inside');
var xmlData = xmlhttp.responseXML;
if (!xmlData) {
xmlData = (new DOMParser())
.parseFromString(
xmlhttp.responseText,
'text/xml');
}
// alert('Content'+xmlData);
var store , O_url ,status,total,description,tracknum,litncount,trackhrf,subdate,sdate,durl,elements;
var conference = xmlData
.getElementsByTagName("orders");
for (var i = 0; i< conference.length; i++) {
// alert('In For');
store = conference[i].getElementsByTagName("store_label")[0].firstChild.data;
O_url = conference[i].getElementsByTagName("order_id")[0].firstChild.data;
status = conference[i].getElementsByTagName("status")[0].firstChild.data;
total = conference[i].getElementsByTagName("total")[0].firstChild.data;
description = conference[i].getElementsByTagName("description")[0].firstChild.data;
tracknum = conference[i].getElementsByTagName("tracking_num")[0].firstChild.data;
litncount = conference[i].getElementsByTagName("lineItemCount")[0].firstChild.data;
trackhrf = conference[i].getElementsByTagName("tracking_href")[0].firstChild.data;
subdate = conference[i].getElementsByTagName("submitted_date")[0].firstChild.data;
sdate = conference[i].getElementsByTagName("sort_date")[0].firstChild.data;
durl = conference[i].getElementsByTagName("detail_url")[0].firstChild.data;
//alert(date+" "+name+" "+url);
elements +="StoreType::"+store+ "<br>" +"OrderUr::"+ O_url + "<br>" +
"Status::"+status+"<br>"+"Total Bill::"+total+"<br>"+""+"Item Description::"+description+"<br>"+"Trackinh Number::"+tracknum+"<br>"+
"LineItemCount::"+litncount+"<br>"+"Tracking Link::"+trackhrf+"<br>"+"Submission Date::"+subdate+"<br>"+"Sort Date::"+sdate+"<br>"+"DetailUrl::"+durl+"<br><br>";
}
document.getElementById("demo").innerHTML= elements;
/* date = conference[0]
.getElementsByTagName("date")[0].firstChild.data;
name = conference[0]
.getElementsByTagName("name")[0].firstChild.data;
url = conference[0]
.getElementsByTagName("url")[0].firstChild.data;
*/
// alert('Name'+name+'Date'+date+'url'+url);
} else {
name = "";
date = "";
url = ""
alert("Invalid Employee ID");
}
} else {
alert("Error ->" + xmlhttp.responseText);
}
}
</script>
</head>
<body onload="init()">
<h1>Call Scholastic Service </h1>
<table>
<tr>
<input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
</table>
<p id="demo"></p>
</body>
</html>
I want to display value without using table in following format:
Store Label: <Value> LineItem Count:<Value>
OrderId: <Value> LineItem Count:<Value>
Status Times: <Value> Tracking Link:<Value>
Total: <Value> Submission Date:<Value>
Description: <Value> Date Sorting:<Value>
Tracking Number:<Value>
Detail Url:<Value>
I tried using but it was not proper.
Thanks

Related

Read the xml in javascript

I have this type of xml
<root>
<Message code="AC_CONNECTOR__FAIL_IN_CONNECT"
id="AR_AC_CONNECTOR__FAIL_IN_CONNECT"
bundleName="Error" locale="pt" severity="4" userFlag="">
(AR1-000001) Error in the data
</Message>
<Message code="AC_CONNECTOR__FAIL_IN_DISCONNECT"
id="AR_AC_CONNECTOR__FAIL_IN_DISCONNECT" bundleName="Error"
locale="pt" severity="4" userFlag="">
(AR1-000001) error
</Message>
</root>
and i want it to be read in the javascript
after reading this i need to replace value of the message with another based on the code property of the message
i have done this code ...
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reading XML</title>
<script type="text/javascript">
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'error1.xml', false);
xml.send();
var xmldata = xml.responseXML;
document.write("Nutan");
xmldata = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var emp = xmldata.getElementsByTagName("ptr");
// document.write(emp);
var output=emp[0].getElementsByTagName("Message")[0].firstChild.data;
document.write(output);
}
</script>
</head>
<body>
<h1>
XMl file
</h1>
<button onclick="readXML()">Read xml file</button>
</body>
</html>
but this code is not reading the xml file ..which is in above format
please help me to read xml file with above format
If you want to access the code value you have to use the getAttribute("code") function reference, if you want to list the code value for each child the following code is working.
<html>
<head>
<script>
function readXML() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "error1.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Message");
for (var i = 0; i < x.length; i++) {
var node_code = x[i].getAttribute("code");
document.write(node_code + " ");
var node_value = x[i].childNodes[0].nodeValue;
document.write(node_value + " <br>");
}
}
</script>
</head>
<body>
<button onclick="readXML()">Read xml file</button>
</body>
</html>
It's better if you separate your JS code from your HTML by using two separate files. If this isn't what you are looking for please explain your problem better.

XMLHttpRequest with php will not work

I've been trying to get this solved for 2 weeks now and still have no success.
JavaScript:
var quotenum = 0;
var xmlhttp = null;
var rt = "";
function ChangeQuote() {
quotenum++;
xmlhttp = null;
//alert("quotenum= "+quotenum);
if (quotenum === 0) {
document.getElementById("quote").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
rt = xmlhttp.responseText;
//alert("quote= "+rt);
alert("request number= " + xmlhttp.length);
document.getElementById("quote").innerHTML = rt;
}
};
xmlhttp.open("Get", "getquote.php?q=" + quotenum, false);
//xmlhttp.open("GET", "getquote.php?XDEBUG_SESSION_START=netbeans-xdebug&q=" + quotenum, false);
xmlhttp.send();
//var thediv = document.getElementById("quote");
return false;
}
PHP:
error_reporting(E_ERROR | E_PARSE);
$q="";
$q = intval($_GET['q']);
$link=mysqli_connect("localhost","root","sequence","babylon");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT quotetext FROM quote where quotenum='".$q."'";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo $row["quotetext"];
}
Can anyone see anything wrong with this?
Using WAMP I can see the correct result when I run the PHP file in a browser.
I also try to use Jquery instead.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var quotenum = 0;
// var xmlhttp = null;
// var rt = "";
function ChangeQuote() {
quotenum++;
$.ajax({
url: "getquote.php?q="+quotenum,
method: "get",
data: {
q: quotenum
}
}).done(function (data) {
alert(data);
document.getElementById("quote").innerHTML = data.quotetext;
});
return false;
}
</script>
The only noticable error I see is you inlining your js with the script tag that has a src attribute.
HTML 4.01 Specification:
The script may be defined within the
contents of the SCRIPT element or in
an external file. If the src attribute
is not set, user agents must interpret
the contents of the element as the
script. If the src has a URI value,
user agents must ignore the element's
contents and retrieve the script via
the URI.

how can i export the geolocation output to log file?

I have this code it displays the geolocation (Longitude: xx Latitude: xx Accuracy: xxx) ..how can I output the results into a log file log.txt when any body visit the url
<!-- <xml version="1.0" encoding="utf-8"> -->
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Geolocation API Demo</title>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport"/>
<script>
function successHandler(location) {
var message = document.getElementById("message"), html = [];
html.push("<img width='512' height='512' src='http://maps.google.com/maps/api/staticmap?center=", location.coords.latitude, ",", location.coords.longitude, "&markers=size:small|color:blue|", location.coords.latitude, ",", location.coords.longitude, "&zoom=16&size=512x512&sensor=false' />");
html.push("<p>Longitude: ", location.coords.longitude, "</p>");
html.push("<p>Latitude: ", location.coords.latitude, "</p>");
html.push("<p>Accuracy: ", location.coords.accuracy, " meters</p>");
message.innerHTML = html.join("");
}
function errorHandler(error) {
alert('Attempt to get location failed: ' + error.message);
}
navigator.geolocation.getCurrentPosition(successHandler, errorHandler);
</script>
</head>
<body>
<div id="message">Location unknown</div>
</body>
</html>
This is the javascript code which will send the data asynchronously to the server.
function successHandler(location) {
var message = document.getElementById("message"), html = [];
html.push("<img width='512' height='512' src='http://maps.google.com/maps/api/staticmap?center=", location.coords.latitude, ",", location.coords.longitude, "&markers=size:small|color:blue|", location.coords.latitude, ",", location.coords.longitude, "&zoom=16&size=512x512&sensor=false' />");
html.push("<p>Longitude: ", location.coords.longitude, "</p>");
html.push("<p>Latitude: ", location.coords.latitude, "</p>");
html.push("<p>Accuracy: ", location.coords.accuracy, " meters</p>");
message.innerHTML = html.join("");
//Send this to server
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","script.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send("latitude="+location.coords.latitude+"&longitude="+location.coords.longitude+"&accuracy="+location.coords.accuracy); // pass data, assuming lat, long, acc are respective js variables
}
function errorHandler(error) {
alert('Attempt to get location failed: ' + error.message);
}
navigator.geolocation.getCurrentPosition(successHandler, errorHandler);
Retrieve the data on server side and save with below PHP code (script.php)
<?php
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$accuracy = $_POST['accuracy'];
$string = $latitude." - ".$longitude." | ".$accuracy; // this will turn into 00000 - 00000 | 0.25
$myfile = file_put_contents('log.txt', $string.PHP_EOL, FILE_APPEND);
?>
For this you will need a server side that can store data locally on its system. I would suggest that you use PHP or whatever other server side language you know.
You will write a program that will receive an object, or perhaps just 2 variables and will store it into a file.txt.
This should not be very hard, if you are confused you should look up JavaScript AJAX calls.
For java here is the code.
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","file.jsp?latitude="+location.coords.latitude+"&longitude="+location.coords.longitude+"&accuracy="+location.coords.accuracy,true);
xmlhttp.send();
In Jsp (file.jsp) write. Better to write java code in servlets not in JSP.
java.io.File file = new java.io.File("d://filename.log");
java.io.FileWriter writer = new java.io.FileWriter(file);
writer.write(request.getParameter("latitude")+" "+request.getParameter("longitude")+" "+request.getParameter("accuracy"));
writer.flush();
writer.close();

How to display xml information using AJAX

I am confused on how to read information from an .xml file using AJAX. All I want my program to do is display a button that the user can press, then it will display a list of movies in the .xml file. Right now my webpage shows the button but when a user presses it nothing happens. I'm going to post my 3 files and hopefully someone can help me out.
index.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX - responseXML</title>
<script src="ajax.js"></script>
<script>
function getMovies() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
movieTitles = xmlDoc.getElementsByTagName('title');
for (i = 0; i < movieTitles.length; i++) {
output += movieTitles[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('movieBox');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "movies.xml", true);
xmlHttp.send();
}
</script>
</head>
<body>
<h3>My Movies</h3>
<div id="movieBox"></div>
<button type="button" onclick="getMovies()">Get Movie Titles</button>
</body>
</html>
ajax.js
function xmlHttpObjCreate() {
var xmlHttp;
try
{xmlHttp=new XMLHttpRequest();
}
catch (e)
{try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
return xmlHttp;
}
movies.xml
<?xml version= "1.0"?>
<collection>
<movies>
<title> Gone with the Wind
<year> 1939 </year>
</title>
<title> 2001: A Space Odyssey
<year> 1968 </year>
</title>
<title> Jurassic Park
<year> 1993 </year>
</title>
<title> The Shawshank Redmption
<year> 1994 </year>
</title>
<title> Balto
<year> 1995 </year>
</title>
</movies>
</collection>
This is the error that I get
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

Need help to improve this largest common substring implementation

I have scanned the web for largest substring implementations to use in my xmlhttp request, however I found that only 1 has worked, in other cases the responsetext hasn't been treated as a string no matter what I have written:
txt = txt + ""; // or
txt = new string(txt);)
This function works, but it is terrible slow. I am just wondering if you code gurus out there could help me improve this algorithm.
The site that I'm calling a xmlhttprequest is looking like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /</title>
</head>
<body>
<h1>Index of /</h1>
<ul><li> Parent Directory</li>
<li> random/</li>
<li> random_1/</li>
<li> random/</li>
<li> random_1/</li>
<li> random/</li>
<li> random_1/</li>
</ul>
</body></html>
In other words you can strip of all the html tags for better speed, I will just search for the plain text in the html text document.
You can watch the script in action here at tdsoft.se
<html>
<head>
<script type="text/javascript">
var txt;
var buildName = "";
var xmlhttp;
function lcs(a, b) {
var aSub = a.substr(0, a.length-1);
var bSub = b.substr(0, b.length-1);
if (a.length == 0 || b.length == 0) {
return "";
} else if (a.charAt(a.length-1) == b.charAt(b.length-1)) {
return lcs(aSub, bSub) + a.charAt(a.length-1);
} else {
var x = lcs(a, bSub);
var y = lcs(aSub, b);
return (x.length > y.length) ? x : y;
}
}
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("http://tdsoft.se/testni.html",handleXML);
}
var checkState = function(xmlhttp, callback) {
try{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback();
}
else {
// Check back again 1 sec later
setTimeout(checkState, 1000);
}
}
catch(err){
setTimeout(checkState, 1000);
}
};
function handleXML()
{
checkState(xmlhttp, function() {
txt=xmlhttp.responseText;
buildName = "random";
txt = txt.replace(/<[^>]*>/g, "");
var myvar = "";
myvar = lcs(txt, "random");
document.write(myvar);
});
}
</script>
</head>
<body onLoad="myFunction()">
</body>
</html>
Seems like you would want to take a different approach at this.
I'm not exactly sure the point of what you are trying to do but it seems like something like this would be what you want:
You request a Document
Parse the links in the document and store them in an object keyed by their ids with values being their text
Change your lookup function to go after the link list
Here's a code example (using jQuery for simplicity):
//untested!
var links = {};
function successFunction(data) {
var aTags = data.find('a');
aTags.each(function() {
var $this = $(this);
links[$this.attr('href')] = $this.text();
});
}
function lookup(id) {
return links[id] || '';
}
$.ajax({
url: 'requestPage.htm',
success: successFunction
});
EDIT:
If you want to do this non-jquery you can just replace the following things:
$.ajax to your XMLHttpRequest method
data.find('a') to getElementsByTagName
.each(function(){...}) to var i = aTags.length; while(i--) { links[aTags[i].href] = aTags[i].innerHTML; }

Categories