Ajax function is not display xml data on some mobile browsers - javascript

I tried to view XML data in html. This project works fine on desktop browsers but does not work on some mobile browsers. I feel like the issue is obviously but I don't know what to do. Please help.
<div class="row" id="xmldata"></div>
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: xmlParser2
});
});
function xmlParser2(xml) {
xml = $(xml).children();
let total = $(xml).children().length;
$(xml).children().each(function(idx, index, item) {
let tag = $(this).prop("tagName");
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total - 1) : prevIdx;
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random reveal" id="random">
<div class="thumbnail randomdiv3">
<a href="#${tag + idx}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>
</div>`;
$("#xmldata").append(html);
});
}

Related

Outsourcing jQuery request on solr in external javascript

I am trying to outsource my inline javascript into an external one. The inline code looks like this and it works fine.
<script type="text/javascript">
$.getJSON('../servlets/solr/select?q=mods.genre:issue_a&state:published&rows=1&
fl=returnId,id,search_result_link_text,parentLinkText,mods.title&sort=modified
desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let ausgabe = "Ausgabe: ";
let titelmain = doc['search_result_link_text'];
let titelall = doc['mods.title'];
for (let i=0, item; item=titelall[i]; i++) {
if (item.indexOf(titelmain)>=0) {
titelall.splice(i,1);
}
}
let titel = titelall.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<span class="fa fa-arrow-right text-info" />' + ' ' +
'<span style="font-weight:bold">' + (doc['parentLinkText']) +
'</span>' + '<br/>' + '<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['returnId']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + titel + '</p>' + '<p/>')
);
});
});
</script>
The external javascript (new.js) looks like this.
It is stored inside the same folder as the html (index.html) invoking it.
$(document).ready(function(){
jQuery.getJSON('http://localhost:8282/mir/servlets/solr/select?q=mods.genre:journal&state:published&rows=2&fl=id,search_result_link_text,mods.title,mods.title.main,sb_amt,sb_ort&sort=modified desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let amt = doc['sb_amt'] ? doc['sb_amt'] : ' ';
let ort = doc['sb_ort'] ? doc['sb_ort'] : ' ';
let alletitel = doc['mods.title'];
let titel = alletitel.slice(1);
titel = titel.join(' ' + '|' + ' ');
let meta = [titel,amt,ort];
let text = meta.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['id']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + text + '</p>')
);
});
});
alert('New Documents');
});
I added alert to be sure that the external javascript is beeing resolved.
The alert text pops up correctly but there is no data displayed.
In my HTML Code I have this:
<script src="new.js"></script>
<div class="col-md-4">
<h4 class="text-dark font-weight-bold" style="">PERIODICALS</h4>
<div id="periodicals"></div>
<a style="vertical-align:top" href="../servlets/solr/select?q=mods.genre:journal&
state:published&sort=modified desc"></a>
</div>

How to add next previous buttons to popup?

I need to load XML data to next and previous buttons on the popup box. When button click, my code is fail to load the XML data. How can I implement the code.
Here is the script
function xmlParser(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let tag = $(this).prop("tagName");
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<a href="#${tag}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>`;
let popup = `<div id="${tag}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#xmldata").append(html);
$("#popup").append(popup);
});
}
Plunker
Firstly div id is being duplicated if you use directly tag name. So use index in for loop and do some simple calculation to get prev & next items, something like:
$(xml).children().each(function (idx) {
let tag = $(this).prop("tagName");
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic rotation
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
//..........check plunker code
http://next.plnkr.co/edit/Sj188FthvFu6H5uv?open=lib%2Fscript.js

display value (label name) of the clicked item

i have a page with clickable divs that has been populated dynamically with Json. The divs contains list of items, and when i click on a specific one, i get a new page that contains the name and details of the clicked item.
My issue is that i can't figure out how to display the label (name) of the item cliked, if you can give some help. Many thanks !
Here is my JSON array:
$data['dataHeader'] = array('id', 'Name', 'Value');
$data['dataJson'] = array(
array('id1', 'Jeans', 'blablablabla'),
array('id2', 'Leather Jacket', 'some random description'),
array('id3', 'Suede Boots', 'description of boots')
);
Here is what i tried to do :
(function( $ ) {
// Plugin to clickable element
$.fn.infoClickable = function() {
this.each(function() {
// get the object
var elm = $( this );
// Define click event
elm.on("click", function(){
//Get info relative to clicked element
var currentPage = elm.data("page");
loadPage_X_Content(elm);
});
});
}
// Load page 1
loadPage1Content();
// Application du plug-in
$('.clickableDiv').infoClickable();
}( jQuery ));
function loadPage_X_Content(elm){
var nextPage = currentPage + 1;
var nextPageName = '#LV' + nextPage +'Content';
arrayOfData = reponseData;
currentValue = arrayOfData;
var elm = $( this );
var elmID = elm.attr("id");
var PageContent = '';
PageContent += '<div>' + elmID + '</div>';
$.ajax({
url : "Pages/index.php",
type: 'GET',
dataType: 'json',
data: 'action=loadPage' + '&ID=' + elmID,
success: function(reponseData) {
For header :
LVContent += '<div class="HeaderLine">';
$.each(arrayOfData['dataHeader'], function(currentIdx, currentValue)
{
if (currentIdx > 0) PageContent += '<div class="' + arrayOfData[currentIdx] + '">'+ currentValue +'</div>';
});
For data :
$.each(arrayOfData['dataJson'], function(currentIdx, currentValue){
PageContent += '<div class="BlocLine clickableDiv" ';
PageContent += ' id="' + currentIdx + "_" + currentContext + '"';
PageContent += ' >';
// columns
$.each(currentValue, function(currentIdx, currentValueCol){
if (currentIdx > 0){
PageContent += '<div class=" '+ arrayOfData[currentIdx] +' "';
PageContent += ' >'+ currentValueCol +'</div>';
}
});
PageContent += '</div>';
});
$(nextPageName).append(PageContent);
$(nextPageName).find('.clickableDiv').infoClickable();
});
The code included does not specify what elm is.
So just to clarify, is your elm:
var elm = document.getElementById('theAttrDivId');
?
Also you're asking for the name but searching for the ID, so make sure it's:
var elmID = elm.attr("name");

ajax callback to insert image if exists

I've been following this answer in an attempt to write good asynchronous js - but I can't quite figure out what's going wrong for me.
I'm using autocomplete to request a specific set of files from the server, but for some datasets these files may not exist (i.e, there may be one, or up to four files). If they do exist, I want to append .html to include them.
The images don't load unless I add
async: false
to the .ajax call, which makes the callback redundant.
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
$.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
})(i);
}
Then image_html contains html for only those images that exist.
$('#outputcontent').html(outer_html + image_html + outer_html_end);
Can anyone explain to my misunderstanding here please? Why isn't image_html being populated?
EDIT: 'full' code below. I use jquery autocomplete to pull from the stellar_comp array, then for those with properties that exist (some are blank), html is generated. Within that is the ajax call.
$(function () {
var stellar_comp = [
{
value:'X0005-28',
data: {
set0: {
aperture:'X2105-28',
secat:'X025-18',
set:'1',
run:'r06',
continuumFilter:'J',
narrowBandFilter:'638/28',
numberOfSources:'1',
priorityCode:'1'
etc... etc ...
},
},
];
$('#autocomplete').autocomplete({
lookup: stellar_comp,
onSelect: function (suggestion) {
var path_Value = 'data/' + suggestion.value + '/';
var outer_html = '<h1>' + suggestion.value + ' </h1> <div class="container">';
var outer_html_end = '</div>';
for (var category in suggestion.data) {
if (suggestion.data.hasOwnProperty(category)) {
if (suggestion.data[category].aperture) {
summary_table_contents = '<tr> <td>' + suggestion.data[category].set + '</td> <td>' + suggestion.data[category].run + '</td> <td>' + suggestion.data[category].continuumFilter + '</td> <td>' + suggestion.data[category].narrowBandFilter + '</td> <td>' + suggestion.data[category].numberOfSources + '</td> <td>' + suggestion.data[category].priorityCode + '</td></tr> ';
summary_table += summary_table_contents;
var aperturePlot = suggestion.data[category].aperture + '_' + suggestion.data[category].run;
var seCATPlot = suggestion.data[category].secat + '_Rsub_ss_' + suggestion.data[category].run;
var aperture_match = suggestion.data[category].aperture_match;
cog = path_Plots + aperturePlot + '_cog';
sbprof = path_Plots + aperturePlot + '_sbprof';
thumb_cog = '';
thumb_cog_temp = '';
thumb_sb = '';
temp='';
for (var i = 1; i < 5; i++) {
(function (counter) {
function some_function(callback) {
$.ajax({
type: "GET",
url: cog + counter + "_1.jpg",
async: false,
success: function (result) {
callback(counter);
}
});
}
some_function(function (num) {
var thumb_cog_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + cog + num + '_1.jpg"> <img class="img-thumbnail" src="' + cog + num + '_4.jpg" /></a> <div class="caption"><h5>' + suggestion.value + ':S' + num + '</h5></div></div>';
var thumb_sb_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + sbprof + num + '_1.jpg"><img class="img-thumbnail" src="' + sbprof + num + '_4.jpg" /></a><div class="caption"><h5>' + suggestion.value + ':S' + num + ' </h5></div></div>';
console.log(num, counter);
thumb_cog += thumb_cog_temp;
thumb_sb += thumb_sb_temp;
});
})(i);
}
cog_sbprofile_row='<div class="row"><h3>C o G</h3> ' + thumb_cog + '</div><div class="row"><h3>Profiles</h3> ' + thumb_sb + '</div>';
console.log(cog_sbprofile_row);
body_html += aperture_row;
body_html += seCAT_row;
body_html += aperture_match_row;
body_html += pixel_map_row;
body_html += skyprofile_row;
body_html += cog_sbprofile_row;
body_html += '<hr>';
};
};
};
top_html += summary_table + '</tbody> </table> </div></div> <hr>';
$('#outputcontent').html(outer_html + hipass_container + top_html + body_html + outer_html_end);
}
});
});
The current problem is due to using the resulting HTML string, before it has been created via multiple asynchronous calls. You need to either defer that operation until all loads are completed, or change the situation so it is not dependent on final completion (progressive loading looks busier anyway).
Personally I would simply insert placeholders for the images as you loop and insert each as they load. This way the order is retained. You can even do effects (fade etc) on each as they load:
var wrapper = "";
for (var i = 1; i < 5; i++) {
// Make a placeholder element for each image we expect
wrapper += '<div class="thumbnail" id="thumb_' + i + '">'
(function (num) {
// call the function
$.ajax({
type: "GET",
url: num + "_1.jpg",
success: function (result) {
var image_temp = '<img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num;
// Insert new image into unique element and fade it in
$('#thumb_'+num).append(image_temp).fadeIn();
}
});
})(i);
}
// Append all placeholders immediately - these will be appended to as each image is loaded
$('#outputcontent').html(outer_html + wrappers + outer_html_end);
Update:
As Alnitak points out, the whole exercise is a little pointless as you are ignoring the result returned from the Ajax call anyway, so you might as well drop the Ajax call (which adds no value) and simply build the image elements on the fly server-side :)
You have to do the appending after all ajax requests finish their jobs. First define this:
var after = function(reqs) {
var d = $.Deferred(),
cnt = reqs.length;
if (!cnt) {
d.resolve();
}
var limit = cnt; // separate var just in case reqs are synchronous
// so it won't mess up the loop
for (var i = 0; i < limit; i++) {
reqs[i].always(function() {
cnt--;
if (!cnt) {
d.resolve();
}
});
}
return d.promise();
};
You can use $.when instead of this but if one of the requests results in 404 it won't wait for others. Now:
var image_html = "",
requests = [];
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
return $.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
var req = ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
requests.push(req); // push the request to the array
})(i);
}
after(requests).done(function() {
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});
Note that I've added return $.ajax(...).
BTW: what's the point of defining ajaxTest function? Just put everything in an anonymous callback.
Read more about deferred objects and promises here:
http://api.jquery.com/category/deferred-object/
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
or just google it.
EDIT: if the order is important then you just have to tweak the callback function a bit:
var image_html = []; // array instead of string
// some code...
var req = ajaxTest(function (num) {
// ...
image_html[counter] = image_temp;
});
// some code...
after(requests).done(function() {
image_html = image_html.join("");
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});

onerror attribute in <object> tag

I am currently trying to play a list of .wav file using the VLC plugin and the html object tag in the following manner :
$.each(rdata['results'],function(key,data)
{
newRow += '<div class="row-fluid"><div class="span3"><label>Name : ' + data['recordingId'] + '.wav</label></div>';
newRow += '<div class="span2"><label>duration : ' + data['duration']+ '</label></div><div class="span4" style="background: transparent url(img/ajax-loader.gif) no-repeat">';
newRow += '<object data=' + audioUrl +' type="application/x-google-vlc-plugin" width="300" height="30" onerror="error()"></object></div><div style="width:20%"><button type="button" class="btn showShareModal" data-toggle="modal">Share Feedback</button><button type="button" class="btn showRaiseModal" data-toggle="modal">Raise Issue</button></div></div><hr/>';
}
EDIT : The entire function definition :
function fnFormatDetails ( apiUrl, baseUrl )
{
var newRow = "";
var audioUrl;
$.ajax({
type: "GET",
url: apiUrl,
async: false,
contentType : "text/json",
beforeSend:function()
{
image.src = "img/ajax-loader.gif";
},
success: function(data)
{
console.log("success from " + apiUrl);
var rdata = $.parseJSON(data);
$.each(rdata['results'],function(key,data){
audioUrl = baseUrl + data['recordingId'];
newRow += '<div class="row-fluid"><div class="span3"><label>Name : ' + data['recordingId'] + '.wav</label></div>';
newRow += '<div class="span2"><label>duration : ' + data['duration']+ '</label></div><div class="span4" style="background: transparent url(img/ajax-loader.gif) no-repeat">';
newRow += '<object data=' + audioUrl +' type="application/x-google-vlc-plugin" width="300" height="30" onerror="error()"></object></div><div style="width:20%"><button type="button" class="btn showShareModal" data-toggle="modal">Share Feedback</button><button type="button" class="btn showRaiseModal" data-toggle="modal">Raise Issue</button></div></div><hr/>';
});
},
error: function(xmlhttprequest,textstatus,message){
if(textstatus === "timeout")
alert("Read timeout. Try again after some time");
else if(xmlhttprequest.status == 500)
alert("Sorry! connection reset by third party server");
},
complete:function(){
image.src = saveSrc;
}
});
newRow = newRow.substring(0,newRow.length - 5);
return newRow;
//------------------------------------------------------------
};
I also have the error function defined as follows :
function error()
{
alert("Resource load error");
}
However, even when the audioUrl throws up an internal server error, onerror does not get fired. Could someone please tell me why this is happening ?
Thanks.
In your success callback here:
success: function(data)
{
console.log("success from " + apiUrl);
var rdata = $.parseJSON(data);
$.each(rdata['results'],function(key,data){
audioUrl = baseUrl + data['recordingId'];
newRow += '<div class="row-fluid"><div class="span3"><label>Name : ' + data['recordingId'] + '.wav</label></div>';
newRow += '<div class="span2"><label>duration : ' + data['duration']+ '</label></div><div class="span4" style="background: transparent url(img/ajax-loader.gif) no-repeat">';
newRow += '<object data=' + audioUrl +' type="application/x-google-vlc-plugin" width="300" height="30" onerror="error()"></object></div><div style="width:20%"><button type="button" class="btn showShareModal" data-toggle="modal">Share Feedback</button><button type="button" class="btn showRaiseModal" data-toggle="modal">Raise Issue</button></div></div><hr/>';
});
},
It looks like you are constructing the HTML string in newRow, but you are not actually inserting it into the DOM anywhere. You need to do something like $(document.body).append($(newRow)) (just an example if you wanted to add it to the end of the HTML body).

Categories