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);
}
Related
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?
Using Ajax, I've created a sort of console that allows me to execute some PHP functions dynamically.
It looks like this
The problem is that after a bunch of commands, the console becomes hard to read. So I've created a javascript function, named "wipe();", which clears the <div> containing the console.
I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.
But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.
I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a <script>function</script> from another <script></script> block.
So why is it failing to do that ?
here is the php code :
echo '<script>wipe();</script>';
and here is the the first <script> block:
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
evalJSFromHtml(span.innerHTML);
}
xmlhttp.send();
}
function wipe() {
span.innerHTML = '';
}
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
}
Call the 'wipe' function as a callback function directly from the 'send' function. Check status = 200 for a success response.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
wipe(); // 'Wipe' callback function
}
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
But when I try to call this function by making the PHP-AJAX return a "wipe();", it doesn't work. It does nothing.
try create script tag and add to document rather than change inner html.
var spaScript = document.getElementById("spaScript");
var wraper = document.createElement("div");
wraper.innerHTML = xmlhttp.responseText;
var script = document.createElement("script");
script.innerHTML = wraper.getElementsByTagName("script")[0].innerHTML;
spaScript.appendChild(script);
Test if wipe() is in the input and if it is trigger it instead of the ajax call
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
if (data.indexOf('wipe()') == -1) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
}
xmlhttp.send();
}
} else {
wipe();
};
}
function wipe() {
span.innerHTML = '';
}
inserting a script tag directly inside an element should not work (and by the way generating an error in the console).
Using the native eval() function on the response text without speciying the tag attribute should solve the problem.
on server side
echo 'wipe()';
on client side
eval(xmlhttp.responseText)
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
I want to do somthing like this:
var urls = [url1, url2, url3];
for(var i = 0; i < urls.length; i++) {
var doc = getDocumentFor(urls[i]);
doc.applyFunctionX();
}
Is it possible or should I open a page in a Browser (PhantonJS) ?
Try this
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var com = document.getElementById(elementId);
com.innerHTML = xhr.responseText;
}
xhr.send();
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
My html 5 canvas is being saved to a server via php. It also pops up in a new window that is not html. The new window only contains the png image. I would like this new popup window to be able to share to social media. I know about auth2.0 and setting that up. What I don't know is how to get my png created from the saved canvas to popup on a new html page so I can add my social media tools. I am pretty sure it would be an edit to this line, window.open(testCanvas.toDataURL("images/png"));.
function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(testCanvas.toDataURL("images/png"));
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}
New example without server side (using localStorage)
On the first page:
<input type="file" id="upfile" />
<script>
$ = function(id) { return document.getElementById(id); };
$('upfile').onchange = function(e) {
var files = e.target.files;
for (var i = 0; i < files.length; i++)
{
var f = files[i];
if (! f.type.match('image.*'))
continue;
var reader = new FileReader();
reader.onload = (function(filecontent) {
return function(ev) {
var b64data = ev.target.result;
localStorage.setItem('img', b64data);
window.open('popup.html', 'popup', 'width=600,height=400');
};
})(f);
reader.readAsDataURL(f);
}
};
</script>
In the popup page:
<img src="" id="thepicture" />
<script>
window.onload = function() {
document.getElementById('thepicture').src = localStorage.getItem('img');
};
</script>
Check the working demo here