Loop through XML attributes and elements with jQuery - javascript

I've searched most of the forums and can't find what I am looking for. I want to do the following:
XML file:
<vaardigheden>
<vaardigheid soort="techniek">HTML/CSS</vaardigheid>
<vaardigheid soort="techniek">PHP/MySQL</vaardigheid>
<vaardigheid soort="techniek">Javascript</vaardigheid>
<vaardigheid soort="Instrument">Drums</vaardigheid>
<vaardigheid soort="Instrument">Gitaar</vaardigheid>
</vaardigheden>
I would like to loop through the attributes and elements and get this result:
Techniek
HTML/CSS
PHP/MySQL
Javascript
Instrument
Drums
Guitar
Does anyone have an idea how to achieve this? Just need the basic understanding of looping through attributes and elements in this way with jQuery.

DEMO
Using parseXML and each - NOTE the script will work on either a string as here or an ajaxed file.
var xml = '<vaardigheden> <vaardigheid soort="techniek">HTML/CSS</vaardigheid> <vaardigheid soort="techniek">PHP/MySQL</vaardigheid><vaardigheid soort="techniek">Javascript</vaardigheid><vaardigheid soort="Instrument">Drums</vaardigheid><vaardigheid soort="Instrument">Gitaar</vaardigheid></vaardigheden>',
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$vaardigheden = $xml.find( "vaardigheid" );
var currentSoort = "", content = $("#content");
$.each($vaardigheden,function(i,item) {
var soort = $(this).attr('soort');
if (soort != currentSoort) {
content.append("<dt>"+soort+"</dt>");
currentSoort = soort;
}
content.append("<dd>"+$(this).text()+"</dd>");
});

Hope this helps :)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>XML JQUERY Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
function parseXml(xml)
{
var titles = [];
var newL ;
$(xml).find("vaardigheid").each(function()
{
if (jQuery.inArray($(this).attr("soort"), titles)==-1){//append new title
newL = '<label>'+$(this).attr("soort")+'</label><br/>';
var newList = '<ul id="' + $(this).attr("soort") + '" \><li>'+$(this).text()+'</li></ul>';
$("#output").append($(newL));
$("#output").append($(newList));
titles.push($(this).attr("soort"));
}
else{
var newItem = '<li>'+$(this).text()+'</li>';
$("#"+$(this).attr("soort")).append($(newItem));
}
});
}
$.ajax({
type: "GET",
url: "myFile.xml",
dataType: "xml",
success: parseXml
});
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Related

JS, how can i refresh the page or div when json data changed?

Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);

Pass json var to php

Friends be patient with me. I'm not even a newbie. I'm developping a website that accesses MySQL database and I'm using this code:
File getdata.php
<?PHP
require_once("php/simfatic-RegistrationForm-dc288cf/source/include/membersite_config2.php");
$mycon = mysqli_connect("localhost", "dbuser", "ammr4024", "gadgetbid") or die("Erro! " . mysqli_error($mycon));
$myque = "SELECT * FROM leilaov WHERE numero12345 = 1";
$resul = $mycon->query($myque);
if(!$resul) {
die("Erro no query!" . $fgmembersite->UserId());
}
$myrow = mysqli_fetch_array($resul);
$variarr = array('0' => $myrow['fotodet'], '1' => $myrow['anoini'], '2' => $myrow['mesini'], '3' => $myrow['diaini'], '4' => $myrow['horaini'], '5' => $myrow['minutoini']);
echo json_encode($variarr);
?>
File getdatamain.php
<!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>Untitled Document</title>
<script>
function reqListener () {
console.log(this.responseText);
}
function teste() {
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var variarr = JSON.parse(this.responseText);
alert(variarr[0]+" em "+variarr[1]+"-"+variarr[2]+"-"+variarr[3]+" às "+variarr[4]+":"+variarr[5]);
};
oReq.open("GET", "getdata.php", true);
oReq.send();
}
</script>
</head>
<body>
Botanito
<input type="submit" name="botao" id="botao" value="Largar bosta" onclick="teste()" />
</body>
</html>
This works perfect! Clicking the button retrieves the information I want from MySQL table.
My question is:- Is it possible to pass a variable to getdata.php?
As you can see in this file I have
$myque = "SELECT * FROM leilaov WHERE numero12345 = 1";
Well, I want to pass a variable and use it in this "SELECT" (instead of "1")
Here's some of my trials that didn't work.
var indice = 1;
oReq.open("POST", "getdata.php", true);
oReq.send(indice);
var indice = {
object: { child:1 }
}
oReq.open("POST", "getdata.php", true);
oReq.send(indice);
When I print the $POST the result is always the same
Array
(
)
Can anybody help me?

Fusion Tables MAXIMUM QUERY set data to 0 IF return no row

Hello I want to set my data value to 0 if my query result no row or data undefined. I tried change the dataType, error, done, succees and set header to
header('Content-Type: application/json');
Blockquote
but not worked.
Can anybody help me? thanks for any help..
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fusion Tables Layer Example: Basic JSONP Request</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function jp() {
var query = "SELECT MAXIMUM ('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR WHERE idStatistikPohon=0 ";
var encodedQuery = encodeURIComponent(query);
// Construct the URL
var url = ['https://www.googleapis.com/fusiontables/v1/query'];
url.push('?sql=' + encodedQuery);
url.push('&key=AIzaSyA6Lug89RBK8spwEEq1WYrrzbDwlsgUrK0');
url.push('&callback=?');
// Send the JSONP request using jQuery
$.ajax({
url: url.join(''),
dataType: 'jsonp',
success: function (data) {
response = jQuery.parseJSON(data);
var rows = data['rows'];
var ftData = document.getElementById('ft-data');
var tpv = rows[0][0];
if(tpv != null){
ftData.innerHTML = "Total "+tpv+" data";
}
}
});
}
</script>
<script type="text/javascript">
function initialize() {
jp();
}
</script>
</head>
<body onload="initialize()">
<div id="ft-data"></div>
</body>
</html>
success: function (data) {
//set data to an empty object when it's undefined
var data=data||{};
//set default for rows when it's undefined
var rows = data['rows']||[[[0]]];
var ftData = document.getElementById('ft-data');
var tpv = rows[0][0]
if(tpv != null){
ftData.innerHTML = "Total "+tpv+" data";
}
}

get element Tag value from the xml

this is my JavaScript code:-
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API with Google Maps API</title>
<meta charset="UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body onload="getlg()">
<script>
function getlg(){
var region = $('#region').val();
var xml;
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/xml?address="+$("#region").html()+"&sensor=true",
async: false,
dataType:'text/xml',
success: function(data){
xml=data;
$('#Div_Get').html('');
}
});
xmlDoc = $.parseXML( xml );
$xml = $( xmlDoc );
var abc= xmlDoc.getElementsByTagName("lat")[1].firstChild.nodeValue;
}
</script>
<div id="region">Rajkot</div>
<div id = "Div_Get"></div>
</body>
</html>
here i am try to set value in url and get the xml file.
now i try to get from this xml lat and long value.
i am try getElementsByTagName but not success nothing is output and give me error xmlDoc is null on this line var abc= xmlDoc.getElementsByTagName("lat")[1].firstChild.nodeValue;
please help me out of this.
thanks.
Change you datatype from
dataType:'text/xml',
To
dataType:'xml',
And Please have a look at documentation for Specifying the Data Type for AJAX Requests.

Javascript File References Problem (with jQuery)

Before, I had this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
Line: 54
Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong?
Am I right in saying that this is ASP.Net? If it is, inline scripts like:
<%=Url.Action("GetDescription") %>
cannot go in the external JavaScript file.
Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -";
Since you are now serving the js as a static file, rather than via your ASP, lines like
<%=Url.Action("GetChildCategories") %>
will no longer work as the server doesn't interpret them and replace them with the correct values. You'll need to hard-code them in the script, or leave those lines as inline scripts in the main page and set them as global variables which you can then reference from the external file.

Categories