Getting attribute from XML with my script - javascript

I try to read a specific value of a XML feed. Evertyhing is working but I want to read the "StartTime=" value too.
This is the XML:
<Program StartTime="17:00:00" EndTime="17:30:00">
<Name>name</Name>
</Program>
And this is the code:
$.ajax({
type: "GET",
url: "./data.xml",
dataType: "xml",
error: function (e) {
alert("An error occurred while processing XML file");
console.log("XML reading Failed: ", e);
},
success: function (response) {
$("ul").children().remove();
$(response).find("Program").each(function () {
var _name = 'Program: ' + $(this).find('Name').text();
console.log(_name);
var _time = 'Time: ' + $(this).find('StartDateTime').text();
// add content to the HTML
$("ul").append('<li>' + _name + '</li>');
$("ul").append('<li>' + _time + '</li>');
});
}
});
}
I found some interesting information, but I can't actually use it...

The StartTime is an attribute of <Program>, not an element/node inside it. find() is for elements that are descendants.
Use attr() instead
Try:
var _time = 'Time: ' + $(this).attr('StartDate')

Related

Using/looping response from Ajax call from another function

I am calling an Ajax function from another function and want to get the response and then parse the Json in order to assign it to new divs.
The call is made like this: thedata = GetChequesByBatchID(batchId); and this is the response:
Then, I am trying to loop through the response, but this is where the problem is. I am not sure how to get the response and loop through the thedata. This data should be assigned to the htmlFromJson so it will be inserted as group of divs in the TR. Any ideas?
My function:
<script type="text/javascript">
$(document).ready(function (params) {
var batchId;
var thedata;
var htmlFromJson = "";
$('.showDetails').click(function () {
// Show Details DIV
$(this).closest('tr').find('.details').toggle('fast');
batchId = $(this).data('batchid');
thedata = GetChequesByBatchID(batchId);
var json = jQuery.parseJSON(thedata);
$.each(json, function () {
htmlFromJson = htmlFromJson + ('<div class="ListTaskName">' + this.ChequeID + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAccountNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAmount + '</div>');
});
}).toggle(
function () {
// Trigger text/html to toggle to when hiding.
$(this).html('Hide Details').stop();
$(this).closest("tr").after("<tr class='456456'><td></td><td colspan = '999'>" + '<div class="zzss">' + htmlFromJson + '</div></td></tr>');
},
function () {
// Trigger text/html to toggle to when showing.
$(this).html('Show Details').stop();
//$(this).find('.zoom').remove();
$('tr.456456').remove();
}
);
});
</script>
My Ajax function:
<script type="text/javascript">
function GetChequesByBatchID(BatchID) {
var xss;
var qstring = '?' + jQuery.param({ 'BatchID': BatchID });
return $.ajax({
url: '<%=ResolveUrl("~/DesktopModules/PsaMain/API/ModuleTask/GetChequesByBatchID")%>' + qstring,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
jQuery.parseJSON(result); //the response
},
error: function (response) {
alert("1 " + response.responseText);
},
failure: function (response) {
alert("2 " + response.responseText);
}
});
return xss;
}
</script>
$.ajax is async operation (if you don't include async:false option which is not recommended) so your GetChequesByBatchID function immediately returns either $.ajax object or undefined. Correct usage of $.ajax is to call DOM changing methods from success or error parts of $.ajax.

How to have a same duplicated div structure but parsing a different xml data in each div

I am making some application that it loads data from an xml file. it works file if there is one corresponding div structure and one xml path. But I want to have multiple copies of my div structure, but each one will load different xml content.
I tired to do it by loop but it does copy each data in both content.
JSFIDDLE: https://goo.gl/8XwMYz
HTML:
<div class="data" data-xml="https://dl.dropboxusercontent.com/u/33538012/file1.xml">
</div>
<div class="data" data-xml="https://dl.dropboxusercontent.com/u/33538012/file2.xml">
</div>
jQuery:
$(".data").each(function() {
var path = $(this).attr("data-xml");
$.ajax({
url: path,
dataType: "xml",
success: parse,
error: function() {
alert("Error: Something went wrong with loading the playlist!");
}
});
});
function parse(document) {
$(document).find("person").each(function() {
$(".data").append(
"<div class='name'>Name: " +
$(document).find("name").text() +
"</div><div class='title'>Title: " +
$(document).find("title").text() + "</div>")
//$(document).find("name").text();
});
}
As you can see in the HTML I have exactly the same structure but each one are linked to a different xml file paths., an in my code I want to load the corresponding data based on the xml file they are linked to.
UPDATE:
Based on the answer #charlietfl has provided, the code seems better now, but still does not provide the intended result. I have been testing on the below code, and realised that it does not pass the xml instance to the parse function.
$(".data").each(function() {
// store element instance
var elem = $(this);
var path = $(this).attr("data-xml");
//console.log($el);
$.ajax({
url: path,
dataType: "xml",
success: function(xml){
parse(document, elem);
},
error: function() {
alert("Error: Something went wrong with loading the playlist!");
}
});
});
function parse(document, elem) {
console.log($(document).find("name").text());
$(document).find("person").each(function() {
//alert($el);
var $person = $(this);
elem.append(
"<div class='name'>Name: " +
$person.find("name").text() +
"</div><div class='title'>Title: " +
$person.find("title").text() + "</div>")
});
}
Any idea?
This should do it. You need to store the instance of element outside the ajax and pass that into the success handling
$(".data").each(function() {
// store element instance
var $el = $(this),
path = $(this).attr("data-xml");
$.ajax({
url: path,
dataType: "xml",
success: function(xml) {
parse(document, $el);
},
error: function() {
alert("Error: Something went wrong with loading the playlist!");
}
});
});
function parse(document, $el) {
$(document).find("person").each(function() {
var $person = $(this);
$el.append(
"<div class='name'>Name: " +
$person.find("name").text() +
"</div><div class='title'>Title: " +
$person.find("title").text() + "</div>")
});
}

String Not Appended to Dynamically Created Div

I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}

Undefined is not a function (AJAX, PHP, jQuery)

I am very new to jQuery and AJAX so I apologise if I am being stupid.
I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:
[{"id":1,
"user_id":14,
"title":"The Title",
"thumbnail":"image.jpg",
"summary":"summary of post",
"content":"content info here",
"category":"Graphic Design",
"sub_category":"Adobe Photoshop",
"views":0,
"published":0,
"created_at":"2015-04-16 00:09:57",
"updated_at":"2015-04-16 00:09:57"}, {and so on...}]
The jQuery is:
function retrieveTutorials()
{
$.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
var tutorial = ('')
$.each(data, function(){
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
});
$("#generated-content").empty().append(tutorial);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
The error I am currently receiving is "Uncaught TypeError: undefined is not a function" which refers to the following section
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
Any ideas as to where I am going wrong?
I have used very similar code before which worked fine
try this
var tutorial = $('<div></div>');
You should select any DOM Element and assign it to tutorial variable, something like this:
var tutorial = $('someCSSselector');
There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.
You can do this:
var tutorial = $('<div>');
...
$("#generated-content").empty().append(tutorial.html());
You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.
var tutorial = $('<div class="generatedbox">')
$.each(data, function(){
tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>'))
});

accessing variables outside ajax

I have the following code:
var src, flickrImages = [];
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
// undefined returned here for flickrImages
map.setZoom(13);
map.setCenter(new google.maps.LatLng(xmlLat,xmlLng));
infowindow.setContent('<strong>' + xmlTitle + '</strong><br>' + xmlExcerpt + '<br><br>' + flickrImages.join(''));
infowindow.open(map,this);
I am trying to access flickrImages variable outside the ajax so I am able to put it inside a infowindow for google maps. Unfortunately outside the ajax it returns undefined.
I tried moving the flickr things into the ajax but unfortunately it then loses some of the other information such as xmlTitle and xmlExcerpt.
Any help is much appreciated.
Thanks in advance,
Dave.
The reason why flickrImages is undefined where your comment is, is because the call to $.ajax is asynchronous, which means it does not block until your request completes.
That's why there is a success function that gets "called back" when the underlying HTTP request completes. So, you need to handle your flickrImages variable from your success function, or alternatively, from your success function, pass flickrImages to some other function which does your processing.
The ajax call is asynchronous, so it won't wait around for an answer - it will just go ahead and run the rest of the script. Passing async:false in the settings (see http://api.jquery.com/jQuery.ajax/) should solve your problem, though it will make it a lot slower as the script will have to wait for the ajax call to return.
It would be neater for the rest of the script to be called from the success callback as you tried to do - how is it that xmlTitle and xmlExcerpt are unavailable there?
Define a global variable outside of your ajax call and assign it a value
var myData
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
myData = data
myFunction()
}
});
As said by Karl Agius a "The ajax call is asynchronous". For this you just have to add
async: false,
to your ajax request. Here is you code looks after adding this:
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
async: false,
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
But its not a good practice to stop asynchronous in ajax call. But will work for you. Use Ajax callback on success instead (check here).
Here is another option. You create a function that return an ajax call like this.
function flickrImages (){
return $.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json"
});
}
Then on your code somewhere, you call this function an retrieve the success or in my case the .done() function like this
var result= flickrImages ();
flickrImages = [];
result.done(function(data){
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
});
console.log (flickrImages);

Categories