Equivalent function in Javascript from jQuery - javascript

$.ajax({
url: 'http://' + window.location.host + '/',
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
I couldn't find a way to do the same in javascript, I can make ajax call like this
request = new XMLHttpRequest();
request.open('GET', 'http://' + window.location.host + '/', true);
request.onload = function(files) {
if (request.status >= 200 && request.status < 400){
// Success!
resp = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
but how do I get the list of the files in the directory?
CSJS and/or SSJS both answers are okay.
My main goal is not to use jQuery to accomplish what I want.

If you want to loop through the a:contains(.jpg) like in your jQuery example, your best bet is probably to use a DocumentFragment and then call .querySelectorAll on it :
var div = document.createElement('div');
div.innerHTML = request.responseText;
// if you want to search using text
var links = div.querySelectorAll('a')
for (i = 0; i < links.length; i++) {
var link = links[i];
if (!~link.innerHTML.indexOf('.jpg'))
continue;
// found one !
}
// if you want to search using an attribute
var links = div.querySelectorAll("a[href*='.jpg']");

You can dump the response text into a newly created <div> and use the standard methods to access the anchors; the following should even work for IE7:
// $(resp)
var doc = document.createElement('div');
doc.innerHTML = resp;
// .find('a')
var anchors = doc.getElementsByTagName('a'), // get all anchors
container = document.getElementById('some_id');
// .filter(":contains(.jpg)")
for (var i = 0; i < anchors.length; ++i) {
var contents = anchors[i].textContent || anchors[i].innerText || '';
if (contents.indexOf('.jpg') != -1) {
// var images = $(this).attr("href");
// $('<p></p>').html(images).appendTo
var para = document.createElement('p'),
text = document.createTextNode(anchors[i].href);
para.appendChild(text);
container.appendChild(para);
}
}

Related

Calling data from JSON file using AJAX

I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array

load multiple pages from different domain in different divs using javascript

I am trying to load one or more page from different domain inside div of my page on page load. Each page will be loaded in separate div.
I can do this using jquery but I do not want to do this using javascript so that I do not have to add the jquery script as I am not using jquery in my project anywhere.
Below is the jquery code
$(".Widget").each(function () {
var url = $(this).attr("data-url");
$(this).load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error: " + xhr.status + " " + xhr.statusText);
}
});
});
I have the equivalent javascript code
var widgets = document.getElementsByClassName('Widget');
for (var i = 0, len = widgets.length; i < len; i++) {
debugger;
var widget = widgets[i];
var xhr = new XMLHttpRequest();
xhr.onload = function () {
widget.innerHTML = this.response;
};
xhr.open('GET', widget.getAttribute("data-url"), true);
xhr.send();
}
But it is displaying only one page in the last div having class Widget.
Following code worked for me
I have created a separate function load
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
and called that function inside a for loop
var widgets = document.getElementsByClassName('Widget');
for(var i = 0, len = widgets.length; i < len; i++) {
var widget = widgets[i];
load(widget.getAttribute("data-url"),widget);
}

how to check if url of rss feed exists else show local image

I got a rss feed of a cartoon. how can I check if the URL of the image exists. if not, I have 4 local images and I want to display them in sequential order.
this is what I got:
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://rss.xiffy.nl/foksuk.php");
feed.setNumEntries(1);
feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT)
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var ul = document.createElement("ul");
var li = document.createElement('li');
var entryImageUrl = entry.xmlNode.getElementsByTagName("description")[0].getAttribute("url");
li.innerHTML = '<div id="tekst">' + entry.content + '</div>';
ul.appendChild(li);
container.appendChild(ul);
}
}
});
}
setTimeout((initialize),300);
Try this. Check for 404 Error.
var request = new XMLHttpRequest();
request.open('GET', URL, true);
request.send();
if (request.status === "404") {
alert("Image does not exist");
}

Parsing information about the latest GitHub commit

I've been trying to retrieve information about the latest commit of a specific repo using Javascript, but without many results.
I've been using a XMLHttpRequest to get the data from the repo's commits page (for example: https://api.github.com/repos/trapped/rotmg_svr/commits), but seems like it returns null.
Also, I tried to use regular expressions to get the first match of specific line values (for example, to get the value of the commit description, I used this one: "message": "(.*)", ), making it loop through all lines until it finds something (in the code I've posted I temporarily changed it to line numbers, trying to speed up the process since it wasn't working).
Also, when trying to load the page, it blocks. As my previous experience with C#'s webclient suggests me, it's probably related to the XMLHttpRequest thing (indeed when I tried to debug it was returning an undefined object).
Thanks in advance for all the help.
var messagelineindex = 14;
var linklineindex = 17;
var response = "";
function loadcommits() {
httpGet("https://api.github.com/repos/trapped/rotmg_svr/commits");
var lines = response.split("\n");
var message = parsemessage(lines[messagelineindex]);
var link = parselink(lines[linklineindex]);
addcommit(//+message+"");
//for (var i = 0; i < numlines; i++) {
// var line = lines[i];
// var commitmessage = parsemessage(line);
// if (commitmessage != "") {
// addcommit(commitmessage);
// break;
// }
//}
}
function parselink(text) {
var regex = /"link": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function parsemessage(text) {
var regex = /"message": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function addcommit(text) {
document.getElementById("commits").innerHTML = document.getElementById("commits").innerHTML + text.toString() + "\n\r";
}
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
}

Difficulty in loading multiple images in a list view served by multiple xml files

I am developing a html application for Android and I am trying to load images in a list view. Data specific to list items is being served by multiple xml files. I am using ajax to load xml files and populate the list items. Problem I am facing here is that there are 164 list items. Hence, 164 images and 10 xml files to load. my loader function exhausts after two iterations. It does read the xml files but it's unable to dynamically create list items and populate them with images after two iterations. I believe it's due to stack limitations. I can't think of alternate solution. If somebody could suggest an alternate solution that will be highly appreciated. Below is my loader function. It's a recursive function:
function loadChannels() {
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){ console.log('Error Loading Channel XML'); },
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
loadChannels();
}
}
});
}
try to remove the recursion with an outer loop - something like that:
function loadChannels(){
var stopFlag = false;
// request the pages one after another till done
while(!stopFlag)
{
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){
console.log('Error Loading Channel XML');
errorFlaf = true;
},
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
// lets disable the recursion
// loadChannels();
}
else {
stopFlag = true;
}
}
});
}
}

Categories