XML data pasing - ajax

Hi I am trying to display data from XML file to unordered list. Any help would be great. I do have an XML file books data wherein trying to print or display the books author etc.
<!DOCTYPE html>
<html>
<style>
</style>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
report(this);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function report(xml){
var i;
var xmlDoc=xmlhttp.responseXML;
var table = "";
var x = xmlDoc.getElementByTagName("CD");
for(i=0; i<x.length; i++){
table+="<li>" + x[i].getElementByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</li>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
<body>
<ul id="demo"></ul>
<button type="submit" onclick="loadDoc()">RUUUUNNNNN</button>
</body>
</html>

Related

JQueryUI autocomplete search with Django not working

I am working on a project with Django, for a restaurant management system. I wanted to use an autocomplete feature to take orders at the table.
As far as I understand JQueryUI function autocomplete() is what I need.
However I cannot seem to get it to work.
Following is my my HTML code for the page. It works in such a way that once the number of people in the party is inserted the same number of form input fiels is inserted in the table by a Javascrip script.
addOrder.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script type="text/javascript" src={% static "js/jquery-3.3.1.min.js" %}></script>
<script src={% static "js/jquery-ui.min.js" %}></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src={% static "js/createOrderIn.js" %}> </script>
<script type="text/javascript" src={% static "js/autocompleteDrink.js" %}></script>
<script type="text/javascript" src={% static "js/autocompleteMenu.js" %}></script>
<style>
.move {
margin: 30px;
}
</style>
<title>Add Order</title>
</head>
<body>
<div class="move">
<form action="/orders/addOrder" method="post" id="the-form" class="ui-widget">
<label> Party of </label>
<input type="text" id="people">
<input type="submit" class="btn btn-primary" value="Submit order">
</form>
</div>
</body>
</html>
This is the script I use to spawn new form input fields
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" id=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" id=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
The following are the relative Python/Django files
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ordersIndex, name = "index"),
path('changeStatus/<int:pk>', views.changeStatus, name="changeStatus"),
path('addOrder', views.addOrder, name="addOrder"),
path('addOrderRender', views.addOrderRender, name="addOrderRender"),
path('getDrinks', views.getDrinks, name="getDrinks"),
path('getMenus', views.getMenus, name="getMenu"),
]
views.py (only function getMenus())
def getMenus(request):
print("I am called")
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['name'] = menu.name
menu_json['n_courses'] = menu.number_of_courses
menu_json['price'] = menu.price
results.append(menu_json)
data = json.dump(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
And lastly this is the function that is supposed to use JQueryUI to make the ajax call and retrieve the possible menu's
autocompleteMenu.js
$(function() {
$("#menu").autocomplete({
source: "/orders/getMenus/",
});
});
As you can probably see from the getMenus() function in views.py I also print a check line ("I am called"), which sure enough does not get printed on console. Also even by switching the autocomplete() source parameter to a local array there is no result.
I do feel like I am doing some very naive mistake but I really cannot seem to figure it out (I am also pretty new with JQuery).
I think the error should be in the provided files, but I'll be happy to post edits in just in case
Thank you in advance!
I realized that the problem was due to the fact that I had to bind autocomplete to the id of the newly created id's (which I changed to classes). Also the JSON data must have a lable field, (and I had to use json.dumps(), not json.dump() :p).
The followings did the trick:
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" class=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" class=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
$('#the-form').find('input[class=menu]:last').autocomplete({
source: "/orders/getMenus"
});
$('#the-form').find('input[class=drink]:last').autocomplete({
source: "/orders/getDrinks"
});
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
views.py
def getDrinks(request):
if request.is_ajax():
q = request.GET.get('term', '')
drinks = Drink.objects.filter(name__contains=q)
results=[]
for drink in drinks:
drink_json = {}
drink_json['label'] = drink.name
results.append(drink_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
def getMenus(request):
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['label'] = menu.name
menu_json['id'] = menu.number_of_courses
results.append(menu_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Browser does not render appended child node

I'm experimenting with web service to transmit new elements to document DOM.
So I'm preparing a XML on server side with necessary informations to do that job. My server side XML is as followed:
<Root>
<Command>Add
<Data><button id="PB" style="width:600px; height:100px;"/></Data>
</Command>
</Root>
This XML will be caught by following page.
You will see XML has a command id "Add", which should add the nodes below data to the page.
When code is running, the button will be created and shown properly in document DOM (see code function onMessage), but it will not be rendered.
The browser debugger tells me, the width and height of the button seems to be Null. When I edit the attributes in browser debugger, the button will be rendered after change. I get this behaviour on Chrome and IE.
I need a hint, what has to be changed to let it run.
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8002/chat";
var output;
var websocket;
"use strict";
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var parser, xmlDoc, NodeCommand, but;
parser = new DOMParser();
xmlDoc = parser.parseFromString(evt.data, "text/xml");
NodeCommand = xmlDoc.getElementsByTagName("Command");
switch (NodeCommand[0].textContent) {
case "Add":
output.appendChild(NodeCommand[0].childNodes[1].childNodes[0]);
break;
}
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Solved!
This can't be done in this (intuitive) way. Elements have to be created over document.

First AJAX project...(wont load text file inline)

This is my first time working with AJAX, and I cant seem to figure out WHY the .txt file will NOT load? but instead goes to a new page with just that text displayed) ie: not loading in the same page:
my index.html page:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<script src="js/main.js"></script>
</body>
</html>
here is my main.js script:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.readystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
};
};
})();
alert(message);
in my ajax.txt file.. I just have some random plain text: This is Ajax text to be loaded.
I am NOT running this locally, but through localhost using WAMP web server..
What am I missing? or overlooking here?
Tutorial link: tutsplus.com/lesson/the-simplest-ajax-script
to solve your problem:
Make this replacement to your code:
onClick -> onclick (js is case sensitive)
readystatechange -> onreadystatechange
then put this piece of code out of the onreadystatechange function:
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
This is the new main.js:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onclick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.onreadystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
return false;
};
//open the request
xhr.open("GET", "files/ajax.txt?aiai", true);
//send the request
xhr.send(null);
return false;
};
})();
alert(message);
I think its easier to do it like that:
first, HTML:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<div id="textFiles"><!-- files display here --></div>
</body>
</html>
JS:
<script>
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function loadText() {
var message = "Test";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("textFiles").innerHTML = xmlhttp.responseText;
alert(message);
}
else{
document.getElementById("textFiles").innerHTML = "Loading Files...";
}
};
xmlhttp.open("POST",'files/ajax.txt',true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>

Create addListener click event for more than one shape on the Google map

Look at this code:
This creates four circles on the map in a same position and it creates addListener click event for each one too but I just can click on the last one. I want to fix it in a way that I can click on all of them to make setEditable(true) for each one.
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var selectedShape;
function clearSelection()
{
if(selectedShape)
{
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape)
{
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
</script>
<script>
var amsterdam=new google.maps.LatLng(52.395715,4.888916);
function initialize()
{
var mapProp = {center:amsterdam, zoom:7, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myArray = [];
var myCity;
for(var i = 0; i < 4; i++)
{
myCity = new google.maps.Circle({
center:amsterdam,
radius:20000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
});
myArray.push(myCity);
google.maps.event.addListener(myCity, 'click', function() {setSelection(myCity)});
myArray[i].setMap(map);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
Use this instead of myCity :
google.maps.event.addListener(myCity, 'click', function() {
setSelection(this)
});
Using setSelection(myCity) will refer to the last myCity created.

Getting a getXMLHTTP is not defined error

Here is my javascript:
<script type="text/javascript">
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
//ERROR is right here
//UNCAUGHT REFERENCE ERROR: getXMLHTTP IS NOT DEFINED
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
It is being called from this:
<tr>
<td width="150">Country</td>
<td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option> </select></td>
</tr>
Just to be safe, this is my header, maybe I am doing this incorrectly?
<head>
<link rel="stylesheet" type="text/css" href="view/css/application.css" />
<script type="text/javascript" src="view/javascript/application.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
Another note, I am working off this example and he is using a mysql server, I am using ODBC to connect to an Access database. Would I not use xmlHTTP for this? I honestly don't know.
Your getXMLHTTP() should look like this :
<script type="text/javascript">
function getXMLHTTP() {
var x = false;
try {
x = new XMLHttpRequest();
}catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
function getState(countryId){
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req){
req.onreadystatechange = function(){
if (req.readyState == 4){
if (req.status == 200){
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>

Resources