How to display xml information using AJAX - javascript

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

Related

Displaying Order History without using tables

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

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.

Simple ajax script to display a book's name

I started learning Ajax and I did this simple HTML page that displays a user input, when he types the name of a book (stored in an array in the php file), using ajax, the user can see below the input the results while he types, this is the part I couldn't manage to do, Here's the code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="bookstore.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body onload="process()">
<h1>
Hadhemi's BookStore !
</h1>
Enter the book you want to order
<input type="text" id="userInput">
<div id="underInput"> </div>
</body>
</html>
And this is the JS file
// 3 functions : create an object, communicate and response
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //check for IE
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest(); // ! IE
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Can't Create that object");
else
return xmlHttp;
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
book = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","book.php?book=" + book,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse()
{
//sends back an xml file
if (xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML= message;
setTimeout('process()',1000);
}
else
{
alert("OOps! Something went wrong!");
}
}
}
And this is the PHP file :
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
echo'<response>';
$book = $_GET['book'];
$bookArray = array('Book1','Book2','Book3');
if(in_array($book, $bookArray))
echo 'We do have'.$book.'!';
elseif ($book='')
echo 'Enter a book name idiot!';
else
echo 'We dont have'.$book.'!';
echo'</response>';
?>
I can't manage to display what the JS file is supposed to do, anyone knows how to fix it?
EDIT: I placed all the files in the www folder under Wamp.
There are a few things wrong in what you posted.
Firstly, you have a typo in:
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
^ the "n"
Which should read as encoding.
Having errors set to be displayed on your server would have thrown you the following:
XML Parsing Error: XML declaration not well-formed Location: http://www.example.com/book.php?book.php?book= Line Number 1, Column 21:
Plus, do keep in mind that, and as I stated in comments that Book1 and book1 are not treated the same, therefore the array keys are considered as case-sensitive.
Consult the following answer on Stack:
https://stackoverflow.com/a/5404753/
You're also doing an assignment for while using a single equal sign:
elseif ($book='')
^
rather than a comparison, which should contain an additional equal sign:
elseif ($book=='')
^^
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/function.error-reporting.php
Plus, make sure that PHP is indeed installed, running and properly configured.

Ajax won't Display on web page

I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.

Reading a response in javascript from JSP

I am new in learning AJAX and stuck in the first program. Tried to debug but unable to do so.
Below is my code snippet
----------input-ajax.html-------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML PAGE</title>
<script type="text/javascript">
var request=null;
function createRequest(){
try{
request= new XMLHttpRequest();
)catch(e){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request=null;
}
}
}
if(request==null){
alert("Error Creating Request Object");
}
}
function getName(){
alert("getname called");
createRequest();
var url = "showName-ajax.jsp";
request.open("POST",url,true);
alert("before");
request.onreadystatechange = updatePage;
alert("after");
request.send(null);
}
function updatePage(){
//var newName= request.getResponseHeader("r1");
var newName= request.responseText;
var name1 = document.getElementById("name");
replaceText(name1,newName);
}
function replaceText(el, text) {
if (el != null) {
clearText(el);
var newNode = document.createTextNode(text);
el.appendChild(newNode);
}
}
function clearText(el) {
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
el.removeChild(childNode);
}
}
}
}
</script>
</head>
<body>
<h1>WELCOME <span id="name"> GUEST</span></h1>
<form method="POST">
<input type="text" name="t1">
<input type="button" value="Show Name" onclick="getName();"/>
</form>
</body>
</html>
----------showName-ajax.jsp------------
<%
String s1=request.getParameter("t1");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(s1); // Write response body.
%>
But When I run the program (click on the button) nothing happens. Even the alert message that getName function is called does not appear. PLEASE HELP!!!!
Typo:
)catch(e){
should be
}catch(e){
This would show up as an error in the console of your browser. Be sure to always check that first if things don't work like they should.
You have a ) instead of a } here:
try{
request= new XMLHttpRequest();
)catch(e){
So your function never gets defined.
change )catch(e){ to }catch(e){
but
why are you creating request object everytime on button click?
you just need to call "createRequest()" only once on page load event.

Categories