here is my javaScript code:
window.addEventListener('load', function() {
var submitimages = document.getElementById('submitimages');
submitimages.addEventListener('click', upload);
var images = document.getElementById('images');
});
var upload = function(event) {
event.preventDefault();
event.stopPropagation();
var data = new FormData();
for(var i = 0; i < images.files.length; ++i) {
data.append('images[]', images.files[i]);
}
var xhr = XMLHttpRequest();
xhr.open('POST', 'upload.php?test=' + 'test', true);
xhr.send(data);
}
My objective is to upload multiple images using form data and I want those sent images to move on a different directory depending on text that is on the url upload.php?test=' + 'test' where as on my example I want to move those image to test folder
and here is my php code so far
Please help I tried everything I know but I think I need idea whos someone is more knowledgeable to JavaScript. Regards
Related
I´m starting to customize/improve an old audio editor project. I can import audio tracks to my canvas VIA drag&drop from my computer. The thing is that I also would like to use audio tracks already stored in the server just clicking over a list of available tracks... instead of use the <input type="file"> tags. How can I read the server side files with a FileReader?Ajax perhaps? Thanks in advance.
This is the code for the file reader:
Player.prototype.loadFile = function(file, el) {
//console.log(file);
var reader = new FileReader,
fileTypes = ['audio/mpeg', 'audio/mp3', 'audio/wave', 'audio/wav'],
that = this;
if (fileTypes.indexOf(file.type) < 0) {
throw('Unsupported file format!');
}
reader.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) { // DONE == 2
$('.progress').children().width('100%');
var onsuccess = function(audioBuffer) {
$(el).trigger('Audiee:fileLoaded', [audioBuffer, file]);
},
onerror = function() {
// on error - show alert modal
var tpl = (_.template(AlertT))({
message: 'Error while loading the file ' + file.name + '.'
}),
$tpl = $(tpl);
$tpl.on('hide', function() { $tpl.remove() })
.modal(); // show the modal window
// hide the new track modal
$('#newTrackModal').modal('hide');
};
that.context.decodeAudioData(e.target.result, onsuccess, onerror);
}
};
// NOTE: Maybe move to different module...
reader.onprogress = function(e) {
if (e.lengthComputable) {
$progress = $('.progress', '#newTrackModal');
if ($progress.hasClass('hide'))
$progress.fadeIn('fast');
// show loading progress
var loaded = Math.floor(e.loaded / e.total * 100);
$progress.children().width(loaded + '%');
}
};
reader.readAsArrayBuffer(file);
};
return Player;
Thanks for the suggestion micronn, I managed to make a bypass without touch the original code. The code as follows is the following:
jQuery('.file_in_server').click(function()
{
var url=jQuery(this).attr('src');//Get the server path with the mp3/wav file
var filename = url.replace(/^.*[\\\/]/, '');
var path="http://localhost/test/audio/tracks/"+filename;
var file = new File([""], filename); //I need this hack because the original function recives a buffer as well as the file sent from the web form, so I need it to send at least the filename
var get_track = new XMLHttpRequest();
get_track.open('GET',path,true);
get_track.responseType="arraybuffer";
get_track.onload = function(e)
{
if (this.status == 200) //When OK
{
Audiee.Player.context.decodeAudioData(this.response,function(buffer){ //Process the audio toward a buffer
jQuery('#menu-view ul.nav').trigger('Audiee:fileLoaded', [buffer, file]); //Send the buffer & file hack to the loading function
},function(){
alert("Error opening file");
jQuery('#newTrackModal').modal('hide');
});
}
};
get_track.send();
});
After this, in the fileLoaded function, the track is added to the editor.
var name = 'Pista ' + Audiee.Collections.Tracks.getIndexCount();
track = new TrackM({buffer: audioBuffer, file: file, name: name}); //being audioBuffer my buffer, file the fake file and name the fake file name
Audiee.Collections.Tracks.add(track);
And... thats it!
I have:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
document.getElementById('content').innerHTML = xhr.responseText; // Update
}
};
xhr.open('GET', 'data/data-one.html', true); // Prepare the request
xhr.send(null);
Now I want to do the same thing for another link, so when the link is clicked, in the code above, data-one.html is inserted to the HTML container with an id of content in my html page.
Now lets image I have another link in my nav and want to do the same process for another html container with an id of content1 this time to insert data-two.html .
Do I have to create the httprequest in this file or another ajax file? Are the variables gonna be different?
I already tried with the same variable both in the same file and other files but I get an error saying the I can't set the innerHTML to Null. I can't find out why. Please help.
This code is just to get you started. It is very verbose and can be improved to reused. For the sake of clarity I decided to keep it simple though.
function reqListener1 () {
console.log("listener1 -- html echo", this.responseText);
}
function reqListener2 () {
console.log("listener2 -- json echo", this.responseText);
}
document.addEventListener("DOMContentLoaded", function () {
var url1 = "/echo/html/";
var url2 = "/echo/json/";
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener1);
oReq.open("GET", url1);
oReq.send();
// you could use the same variable. but you'll need to instantiate a different object
var oReq2 = new XMLHttpRequest();
oReq2.addEventListener("load", reqListener2);
oReq2.open("GET", url2);
oReq2.send();
});
Demo: http://jsfiddle.net/pottersky/7dz8r19d/1/
I would like to seek your help about xmlhttprequest. I would like to perform xmlhttp request sending out to get pictures repeatly from server only when the previous http response is received.
In server side, I have created http responses which tagged with xmlhttp status =900.So I want to send out the request once the response due to previous request is received, otherwise, the program should wait until its arrival.
For example:
When I press the button somewhere in the browser, it triggers first picture (jpeg) request to server, then waiting the server's response. After getting the Http response with status marked as 900, xmlhttp will decode the response and display the picture on (image).
In the following code, by capturing the packet with wireshark, I think I success to get the right packet flow. However, the picture can not be shown in the DIV.
Can anyone help me ? Thanks a lot and a lot!
enter code here
function init(url)
{
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',url,true);
xmlHTTP.send();
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e)
{
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64=btoa(raw);
var dataURL="data:image/jpeg;base64,"+b64;
document.getElementById("image").src = dataURL;
};
xmlHTTP.onreadystatechange=function(){
buff(xmlHTTP.status);
}
}
buff(status){
if (status=900){
sleep(1000);
init('/images/photos/badger.jpg');
}
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</head>
<body>
<div id="image"><h2>picture display here</h2></div>
<button type="button" onclick=buff(900)>Get Picture</button>
enter code here
There are several problems with your code.
Markup
The problem with your markup is, that you are using a div tag to display an image. The src attribute is not supported on div tags. You should use an img tag instead like this:
....
<img id="image" />
<button type="button" onclick="buff(900)">Get Picture</button>
Statuscode
Why are you using a status of 900? If the request was correct and the image was loaded, please use a status of 200.
Image loading
Why are you even using an XMLHttpRequest for loading images?
You could simply change the src attribute on the img tag and the browser will request the image.
If you want to reload the image you could just refresh the src attribute. If all images a served under the same URL, you can add a request param like the current time:
document.getElementById("image").src = "/images/photos/badger.jpg#" + new Date().getTime();
This way the browser will request the image again and won't use the one allready loaded and cached. See this answer for further info. (Actually the question is nearly the same as yours...)
Sleep function
Your sleep function will use resources because it's a loop that will constantly run for the specified time. While it runs, it will add numbers and do comparisons that are completly unnecessary.
please use something like the javascript build in setTimeout():
buff(status) {
if(status === 900) {
setTimeout(funciton(){
init('/images/photos/badger.jpg');
}, 1000);
}
}
Update: working example
I set up a working example in the code snippet. It loads images from the same url, but they are served randomly on each request by lorempixel.
I reorganized the image loading. Actually there was another problem. You startet the next image loading with onreadystatechange. This will fire for each change of the readystate and not only when the image is loaded. Therefore I start the next buff() from the onload() like so:
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',url,true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64 = btoa(raw);
var dataURL = "data:image/jpeg;base64," + b64;
document.getElementById("image").src = dataURL;
buff(this.status);
};
xmlHTTP.send();
For convenience I added a button for stopping the loading of new images.
For your example you just have to change the imageUrl and imageStatus variables.
var imageUrl = "http://lorempixel.com/400/200/", // set to "/images/photos/badger.jpg" for your example
imageStatus = 200, // set to 900 for your example
stopped = true;
function stopLoading() {
stopped = true;
}
function loadNextImage(url) {
if(!stopped) { // only load images if loading was not stopped
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET',url,true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64 = btoa(raw);
var dataURL = "data:image/jpeg;base64," + b64;
document.getElementById("image").src = dataURL;
buff(this.status); // set the next timer when the current image was loaded.
};
xmlHTTP.send();
}
}
function buff(status) {
if (status === imageStatus) {
setTimeout(function() {
loadNextImage(imageUrl + "?" + new Date().getTime());
}, 1000);
} else {
// Status does not match with expected status.
// Therefore stop loading of further images
stopLoading();
}
}
function init() {
stopped = false;
loadNextImage(imageUrl);
}
document.getElementById("start").onclick = function(){
init(imageUrl);
};
document.getElementById("stop").onclick = stopLoading;
<img id="image" />
<button type="button" id="start">Get pictures</button>
<button type="button" id="stop">No more pictures</button>
I'm trying to access the gmail atom feed but can't seem to get it working. I've tried:
function testing(){
alert("hi");
getMail = new XMLHttpRequest();
getMail.open('GET','https://mail.google.com/mail/u/0/feed/atom/', true);
getMail.onload = function() {
var allXML = getMail.responseText;
alert("hi2");
alert(allXML);
}
getMail.send(null);
}
But when I run it I can't see the "hi2", let along the response text.
I am logged on to gmail and can see the xml if I put https://mail.google.com/mail/u/0/feed/atom/' directly into the browser. I'm using Firefox v29.
I've read the previous similar questions on here but nothing has helped.
Edit
Now I get to the "hi2" but the responseText is blank... code is:
function testing(){
getMail = new XMLHttpRequest();
getMail.open('GET','https://mail.google.com/mail/u/0/feed/atom/', true);
getMail.withCredentials = true;
getMail.onreadystatechange = function() {
if (getMail.readyState == 4) {
var allXML = getMail.responseText;
alert("hi2");
alert(allXML);
}
}
getMail.send(null);
}
Any ideas?
Hi all I have this code:
function test()
{
req = new XMLHttpRequest();
req.upload.addEventListener("progress", updateProgress, false);
req.addEventListener("readystatechange", updateProgress, false);
req.addEventListener("error", uploadFailed, false);
req.addEventListener("abort", uploadCanceled, false);
var data = generateRandomData(currentPayloadId);
totalSize = data.length;
req.open("POST", "www.mydomain.com/upload.aspx");
start = (new Date()).getTime();
req.send(data);
}
function updateProgress(evt)
{
if (evt.lengthComputable) {
total = totalSize = evt.total;
loaded = evt.loaded;
}
else {
total = loaded = totalSize;
}
}
Also, my server responds to the initial OPTIONS request for upload.aspx with 200 and the Access-Control-Allow-Origin: *
and then the second request POST happens
Everything seems in place and it's working great on FireFox but on G Chrome the updateProgress handler is not getting called but only once and then the lengthComputable is false.
I needed the Access-Control-Allow-Origin: * because this is a cross-domain call, the script parent is a resource on a different server then the upload.aspx domain
Anyone can give me some clues, hints, help please? is this a known issue with G Chrome?
Thank you!
Ova
I think I have a solution for your problem
I don't know what is behind this function "generateRandomData()"
var data = generateRandomData(currentPayloadId)
It is working when I change into this:
var data = new FormData();
data.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
Small explanation: You need manually to append to form data an file input form, where fileToUpload is <input type="file" name="fileToUpload" id="fileToUpload" />
And in your updateProgress function in IF part you can add something like this to track progress console.log(evt.total +" - "+ evt.loaded)
This is working in Google Chrome browser. I have tested in new browser version 57
I made for myself an upload progress form 4 years ago, which means that this code is working in old browser version too.
A whole code snippet will be looking like this
function test()
{
req = new XMLHttpRequest();
req.upload.addEventListener("progress", updateProgress, false);
req.addEventListener("readystatechange", updateProgress, false);
req.addEventListener("error", uploadFailed, false);
req.addEventListener("abort", uploadCanceled, false);
//var data = generateRandomData(currentPayloadId);
var data = new FormData();
data.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
totalSize = data.length;
req.open("POST", "www.mydomain.com/upload.aspx");
start = (new Date()).getTime();
req.send(data);
}
function updateProgress(evt)
{
if (evt.lengthComputable) {
total = totalSize = evt.total;
loaded = evt.loaded;
console.log(evt.total +" - "+ evt.loaded)
}
else {
total = loaded = totalSize;
}
}
I had this problem when the page your are loading doesn't contain a
Content-Length: 12345
in the header, where 12345 is the length of the response in bytes. Without a length parameter, the progress function has nothing to work on.
First, make sure that "www.example.com" is added to the manifest.json, like so:
manifest.json
{
..
"permissions": [
"http://www.example.com/",
"https://www.example.com/",
],
..
}
Then I think your example should work.
For more information about using xhr in google chrome extensions the docs are here.
Also the CSP docs are worth taking a look at if what I provided above does not.
This could simply be a compatibility issue with the XMLHttpRequest.upload property. It returns an XMLHttpRequestUpload object, but if you try find that object spec in MDN it doesn't exist so how do we know which browsers fully support it.
XMLHttpRequest.upload Compatability
Have you tried listening for progress directly on the xhr:
req.addEventListener("progress", updateProgress, false);
I use jQuery for progress like that:
$.ajax({
url : furl,
type : method,
data : data,
//...
},
xhr : function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$(".progress-bar").css("width", + percent + "%");
$(" .status").text(position + " / " + total + " (" + percent + "%)");
}, true);
}
return xhr;
},