I'm trying to retrieve data from an api, could someone help me on how to grab the node value of some child tags in an element in ajax? My XML api looks like this:
<distance ...>
<status>...</status>
<car>
<name>Golf</name>
<year>2016</year>
</car>
......
<car>
<name>BMW</name>
<year>2017</year>
</car>
</distance>
How can I retrieve all names and years tag values? Below is the script, I wrote comments in the area where I need help. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function searchXML()
{
var xmlhttp = new XMLHttpRequest();
var url = "https://www.example.se/api/products/xml";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log(xmlhttp.responseXML);
//Here I need help on how to retrieve data.
//when I used document.get....., I was getting .getElementsByClassName instead of getElementsById
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
<title></title>
</head>
<body>
<h2>The returned data under this text</h2>
<div id="mydata">
</div>
<button type="button" onclick="searchXML()">Get data</button>
</body>
</html>
You can use the XML DOm Manipulation API'S var xmlDoc = xml.responseXML;
the nodeValue returns the node value
here is an example XML..
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
that is being parsed for node value as
(Sorry for the CORS error...the code snippet will work on firefox)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "https://www.w3schools.com/xml/books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName('title')[0];
var y = x.childNodes[0];
document.getElementById("demo").innerHTML =
y.nodeValue; // gets the node value
}
<p id="demo"></p>
Related
I am trying to learn how to use an API in Laravel and show json results in my view. This is a sample code I have made but nothing is showing. The API is with values because when I try it in Postman, it returns json results.
<html>
<head>
<meta charset="utf-8">
<title>Item Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="container">
<ul id="items" class="list-group">
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function (){
getItems();
function getItems(){
$.ajax({
url:'https://www.boredapi.com/api/activity'
}).done(function (items){
let output = '';
$.each(items, function (key, activity){
output += '<li class="list-group-item">' +
'<strong>${activity.text}</strong>${text.body}' +
'</li>'
});
});
}
});
</script>
</body>
</html>
I suspect it might have a problem with the key tags i am trying to call. I am trying to make the call from blade not needed from the controller.
json returned from the API:
{
"activity": "Write a list of things you are grateful for",
"type": "relaxation",
"participants": 1,
"price": 0,
"link": "",
"key": "2062010",
"accessibility": 0
}
Here is the completed code.
<html>
<head>
<meta charset="utf-8">
<title>Item Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="container">
<ul id="items" class="list-group">
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function (){
getItems();
var output = '';
function getItems(){
$.ajax({
url:'https://www.boredapi.com/api/activity'
}).done(function (items){
let output = '';
$.each(items, function (key, activity){
output += '<li class="list-group-item">' +
'<strong>'+key+'</strong>' + activity +
'</li>'
});
$("#items").append(output);
});
}
});
</script>
</body>
</html>
try adding this:
$.ajax({
url:'https://www.boredapi.com/api/activity',
type: "GET",
},
Also console.log() your result might be helpful.
I'm using JSONText to load a JSON call in my Jquery but for some reason the request is failing,
Here is the code,
urls.py
urlpatterns = patterns('',
#JSON Response
(r'^json/$', json_request)
)
views.py
from django.utils import simplejson
def json_view(request):
print 'json_view being called'
to_json = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
def json_request(request):
variables = RequestContext(request)
return render_to_response('ajaxtest.html',variables)
ajaxtext.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>Insert title here</title>
<style>
#mainViewContainer{
background-color:red;
height:100px;
width:200px
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var main_container = $("<div>").attr("id", "mainViewContainer");
main_container.append($('<div id="table_layout" />')
.append($('<table id="table_set"/>').
append('<thead><tr> <th>ID</th><th>Name</th> <th>DOB</th> <th>Date Enrolled</th> </tr></thead>')));
$.getJSON("/json_view",function(census_data){
$(census_data).each(function(k,v){
$('#table_set').append();
trObj = $('<tr>');
trObj.append($('<td>').html(v.key1));
trObj.append($('<td>').html(v.key2));
trObj.append($('<td>').html(v.key3));
trObj.append($('<td>').html(v.key4));
$('#table_set').append(trObj);
});
main_container.appendTo(document.body)
});
</script>
</head>
<body>
</body>
</html>
You don't have a route for json_view in your urls.py. Try to add one:
urlpatterns = patterns('',
#JSON Response
(r'^json/$', json_request)
(r'^json_view/$', json_view)
)
(note the slash at the end of ^json_view/)
In xml document, I want to get the Bottom xml node, how can I get the last xml nodes
<Books>
<book>
<author> sasi </author>
<pdate>2013-01-02</pdate>
</book>
<book>
<author> surya</author>
<pdate> 2013-02-02</pdate>
</book>
<book>
<author>dolly</author>
<pdate> 2013-04-01</pdate>
</book>
</Books>
from the above I want get the last <book> node in the xml document.
Try this:
var xml = #"<Books>
<book>
<author> sasi </author>
<pdate>2013-01-02</pdate>
</book>
<book>
<author> surya</author>
<pdate> 2013-02-02</pdate>
</book>
<book>
<author>dolly</author>
<pdate> 2013-04-01</pdate>
</book>
</Books>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.FirstChild.LastChild;
Console.WriteLine(node.OuterXml);
Outputs:
<book><author>dolly</author><pdate> 2013-04-01</pdate></book>
Alternatively, you may select the last book child under the Books element:
doc.SelectSingleNode("Books/book[last()]")
or the last book element no matter where they are in the document:
doc.SelectSingleNode("//book[last()]");
**index.jsp (client side)**
**************************************************************************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Techniques AJAX - XMLHttpRequest</title>
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript">
<!--
function request(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(xhr.responseText);
var text = xhr.responseText;
var myObject = eval('(' + text + ')');
callback(myObject.Addresses);
}
};
xhr.open("GET", "jsonResponse.jsp", true);
xhr.send(null);
}
function readData(oData) {
alert(oData);
}
function getXMLHttpRequest() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
return null;
}
return xhr;
}
//-->
</script>
</head>
<body>
<p>
<button onclick="request(readData);">Afficher le fichier XML</button>
<div id="output"></div>
</p>
</body>
</html>
***jsonResponse.jsp (server side)***
**********************************************************************************
<%--
Document : jsonResponse
Created on : Mar 4, 2012, 8:39:23 PM
Author : ghorbel
--%>
<%#page import="org.json.JSONException"%>
<%#page import="org.json.JSONArray"%>
<%#page contentType="text/html; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<1 ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
addresses.put(i,address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.getWriter().flush();
response.setContentType("application/json");
response.getWriter().write(json.toString());
%>
</body>
</html>
The result of 'alert(xhr.responseText);' (the json return response from the server).
*************************************************************************************************
{"Addresses":[{"CustomerName":"Decepticons0"}]}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
****************************************************************************************
The problem here that the 'var myObject = eval('(' + text + ')');' cannot evaluate the json return response from the server.(the result is just above).
My question. Why the result contains these extra linges.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
</body>
</html>
when it' supposed to return just
{"Addresses":[{"CustomerName":"Decepticons0"}]}.
If someone can tell me what's wrong with the program.
I use Netbeans , Glassfish.
Thanks in advance.
As well as your code your JSP contains literal HTML. You only want the <%#page import...%> and your central code inside <% ... %> that does the work.
I am try get xml feed every 10 sec or add the new xml feed to the existing displayed results . Can someone show me how i can do that using ajax and json call backs.
Also, if I want to take a step further and want to paginate it by breaking down into 5 results per pages how would I do that?
If someone could show me some working examples would be really great
My code is below.. please feel free to expand
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery Xml Ajax</title>
<script language="javascript" src="jquery.js"></script>
<script language="javascript">
$(document).ready(function() {
$.ajax({
type:"GET",
url:"sample-xml-feed.xml",
dataType:"xml",
success:parseXml
});
});
function parseXml (xml) {
$(xml).find("Tutorial").each(function() {
$("#output").append($(this).attr("author") +"<br/>")
});
}
</script>
<body>
<div id="output"></div>
</body>
</html>
XML BIT below
<?xml version="1.0" encoding="utf-8"?>
<RecentTutorials>
<Tutorial author="The Reddest">
<Title>Silverlight and the Netflix API</Title>
<Categories>
<Category>Tutorials</Category>
<Category>Silverlight 2.0</Category>
<Category>Silverlight</Category>
<Category>C#</Category>
<Category>XAML</Category>
</Categories>
<Date>1/13/2009</Date>
</Tutorial>
<Tutorial author="The Hairiest">
<Title>Cake PHP 4 - Saving and Validating Data</Title>
<Categories>
<Category>Tutorials</Category>
<Category>CakePHP</Category>
<Category>PHP</Category>
</Categories>
<Date>1/12/2009</Date>
</Tutorial>
<Tutorial author="The Tallest">
<Title>Silverlight 2 - Using initParams</Title>
<Categories>
<Category>Tutorials</Category>
<Category>Silverlight 2.0</Category>
<Category>Silverlight</Category>
<Category>C#</Category>
<Category>HTML</Category>
</Categories>
<Date>1/6/2009</Date>
</Tutorial>
<Tutorial author="The Fattest">
<Title>Controlling iTunes with AutoHotkey</Title>
<Categories>
<Category>Tutorials</Category>
<Category>AutoHotkey</Category>
</Categories>
<Date>12/12/2008</Date>
</Tutorial>
</RecentTutorials>
What about running your AJAX request inside a setInterval()?
setInterval(function() {
$.ajax({
type:"GET",
url:"sample-xml-feed.xml",
dataType:"xml",
success:parseXml
});
}, 10000); // 10 seconds
For the pagination your parseXml() function should take care of the logic. Keep a counter variable somewhere and as soon as it reaches a 5th result, append to a new container and reset the counter.