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);
}
Related
I'm trying to make a script to upload multiple files using ajax, and print them on the screen with a loading circle display.
The script is working for one file, but I have a problem to make it works for multiple files. I guess it a "scope" problem. But my JS knowledge is not that good.
Also, I'm only using standard JS, no jQuery.
Here's the script :
var index_div = 0;
var dropper = document.querySelector('#upload');
dropper.addEventListener('dragover', function(e) {
e.preventDefault(); // Annule l'interdiction de "drop"
}, false);
dropper.addEventListener('dragenter', function() {
dropper.style.borderStyle = 'solid';
});
dropper.addEventListener('dragleave', function() {
dropper.style.borderStyle = 'dashed';
});
dropper.addEventListener('drop', function(e) {
e.preventDefault();
dropper.style.borderStyle = 'dashed';
var files = e.dataTransfer.files,
filesLen = files.length;
for (var i = 0 ; i < filesLen ; i++) {
var NomImage = files[i].name;
if(files[i] != '')
{
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
var newDiv = document.createElement("div");
newDiv.setAttribute("class","image_div");
document.getElementById("upload").appendChild(newDiv);
document.getElementsByClassName("image_div")[index_div].innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
var form = new FormData();
form.append('file', files[i]);
xhr.open('POST', "./traitement_upload.php", true);
xhr.onload = function (e) {
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementsByClassName("image_div")[index_div].innerHTML =
xhr.responseText;
index_div += 1;
}
}
xhr.send(form);
}
}
});
Sorry for the sloppy code. If I check the xhr readyState and status during the loop, the first(s) are 1 and 0, then the last one is good.
You can see I'm creating a new div for each uploaded file so I can print a thumbnail in it.
For what I understand, the code is processing while the ajax request is not done yet. The result is I only see the last file I submitted.
If I put a false to the async flag on xhr.open, it works but it doesn't show the loading gif of course.
Thank you for your help.
You should extract the code for AJAX functionality in a separate function - otherwise the closure for xhr.onload will use the current (at the time of calling) value of index_div - most probably the last one from the FOR cycle. Also, querySelector returns a collection - even if it finds just a single element, or even if it finds nothing. Also, you should use both event.dataTransfer and event.target in order to handle both drag/drop and normal clicking.
var dropper = document.getElementById('upload');
dropper.addEventListener('dragover', function(e)
{
e.preventDefault();
dropper.style.background = '#eee';
}, false);
dropper.addEventListener('dragenter', function()
{
e.preventDefault();
dropper.style.background = '#eee';
}, false);
dropper.addEventListener('dragleave', function()
{
e.preventDefault();
dropper.style.background = '#fff';
}, false);
dropper.addEventListener('drop', uploadFile, false);
document.getElementById('file_upload').addEventListener('change', uploadFile, false);
function uploadFile(e)
{
e.preventDefault();
dropper.style.background = '#fff';
dropper.style.borderStyle = 'dashed';
var files = (e.dataTransfer || e.target).files,
filesLen = files.length;
for (var i = 0 ; i < filesLen ; i++)
{
if(files[i] != '')
{
var newDiv = document.createElement("div");
newDiv.setAttribute("class","image_div");
newDiv.innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
document.getElementById("upload").appendChild(newDiv);
doAJAX(newDiv,files[i]);
}
}
}
function doAJAX(div,file)
{
var form = new FormData();
form.append('file', file);
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', "./traitement_upload.php", true);
xhr.onload = function (e)
{
if(xhr.readyState==4 && xhr.status==200)
{
div.innerHTML = xhr.responseText;
}
}
xhr.send(form);
}
I know this question has been asked before, but I tried to apply the answers with no results.
I'm trying to do multiple requests on the same domain with a for loop but it's working for the entire record of my array.
Here is the code I use:
function showDesc(str) {
var prod = document.getElementsByName("prod_item[]");
var xhr = [], i;
for (i = 0; i < prod.length; i++) {
var txtHint = 'txtHint10' + i;
(function(i) {
var xhr = new XMLHttpRequest();
var url = "getDesc.php?q=" + str;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById(txtHint).innerHTML = xhr.responseText;
}
};
xhr.open("GET", url, false);
xhr.send();
})(i);
}
}
PHP
<select name="prod_item[]" id="prod_item.1" onchange="showDesc(this.options[this.selectedIndex].value)"></select>
<div id="txtHint100"></div>
and then I will use dynamic table for the prod_item field and div_id.
Is there any mistake in my code?
I have this code which gets a specific web page content and loads it in an iframe. It works fine, unfortunately this content is in the body and doesn't come with CSS formatting, so I get an unformatted page. How can I get the stylesheet to come with the page content?
Thanks in advance!
var getHTML = function (url, callback) {
if (!window.XMLHttpRequest) return;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (callback && typeof (callback) === 'function') {
callback(this.responseXML);
}
}
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
};
function loadFram() {
var src = document.getElementById("opt1").value;
getHTML(src, function (response) {
var x = document.getElementById("frame1");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
y.body.innerHTML = response.documentElement.querySelector('[id="Container"]').innerHTML;
});
};
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
$.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);
}
}