I am trying to use object-oriented code to handle an AJAX upload. When I run the code, it sees the file, creates the XMLHttpRequest object, but I cannot seem to get the progress event to fire. The full source of my code can be found here: http://pastebin.com/89QawbS6
Here is a snippet:
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", MyObj.trackProgress, false);
xhr.open("POST", url, true);
...
Then in that same object, different method:
trackProgress: function (event) {
console.log(event);
// stuff that should calculate percent
}
But that console.log(event) never fires.
Please note: I know jQuery is great, and there are a dozen awesome upload plugins that I could just use instead. I am not doing this for a class or homework, I just want to understand the process better myself. So offering a jQuery plugin as an answer is not what I'm looking for. I'm trying to make myself less dependent on jQuery.
This FF bug might be the reason for your issue. It's reported on MacOSX and another similar bug on Linux. I don't know if that matters but I tested on Windows. I still believe that your code is fine.
Related
I compiled my reactjs using webpack and got a bundle file bundles.js. My bundles.js contains a component that make API calls to get the data.
I put this file in my html and pass the url to phantom.js to pre-compile static html for SEO reasons.
I am witnessing something strange here, the ajax calls for APIS are not getting fired at all.
For example, I have a component called Home which is called when I request for url /home. My Home component makes an ajax request to backend (django-rest) to get some data. Now when I call home page in phantomjs this api call is not getting fired.
Am I missing something here?
I have been using React based app rendering in Phantomjs since 2014. Make sure you use the latest Phantomjs version v2.x. The problems with Phantomjs occur because it uses older webkit engine, so if you have some CSS3 features used make sure they are prefixed correctly example flexbox layout.
From the JS side the PhantomJS does not support many newer APIs (example fetch etc.), to fix this add the polyfills and your fine. The most complicated thing is to track down errors, use the console.log and evaluate code inside the Phantomjs. There is also debugging mode which is actually quite difficult to use, but this could help you track down complex errors. I used webkit engine based browser Aurora to track down some of the issues.
For debugging the network traffic, try logging the requested and received events:
var page = require('webpage').create();
page.onResourceRequested = function(request) {
console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function(response) {
console.log('Receive ' + JSON.stringify(response, undefined, 4));
};
function uploadFile(){
var file = $("file1").files[0];
var formdata = new FormData(); formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "upload.php";
ajax.send(formdata);
}
Error1: Unable to get value of the property '0': object is null or undefined
Error2: ForData not supported.
The FormData API is not supported by IE8 or IE9. It was only added in IE10. If you want to support these old browsers, then you cannot use modern HTML5 APIs.
There is a jQuery Forms plugin which does work in old IE versions and can allow you to upload files via ajax. I've used it myself and it is very effective. You can download it here: http://malsup.com/jquery/form/. You will probably need to rewrite your code a fair bit in order to use it as it's quite different conceptually to the HTML5 FormData API, but at least you'll get something that will work across all the browsers you want to support.
You could also try looking to see if there's a polyfill for FormData which would allow you to keep using your existing code. A quick google turned up this one, which I found listed here. I haven't tried it so can't vouch for it, but the polyfills listed by Modernizr on that list are generally pretty good.
I'm trying to write an add-on for firefox and i'm having a problem-
When the user right-clicking on the page the add-on is adding an element to the page's body using
document.body.appendChild(myElement);
myElement has a button and i want that "onClick" it will call a xmlHttpRequest and handle the response in some why. I've tried to inject the two scripts using
document.getElementsByTagName('head')[0].appendChild(xmlRequestFunction);
document.getElementsByTagName('head')[0].appendChild(handleResponseFunction);
but it didn't work because of (i assume) a security problem.
What can i do?
Thanks
Do not use onclick when working with content, use addEventListener instead (see https://developer.mozilla.org/en/XPCNativeWrapper#Limitations_of_XPCNativeWrapper if you need to know why). Like this:
myElement.addEventListener("click", function(event)
{
var request = new XMLHttpRequest();
...
}, false);
http://digitarald.de/project/fancyupload/3-0/showcase/attach-a-file/
That's the uploader plugin I'm using.
If you go there in firefox, you'll notice you have to click "attach a file" twice before it works. It seems to work fine in every other browser (that I've tested).
it's creating a flash object, and I'm not sure how to go about making it so you only click once in FF.
I'm not familiar with mooTools, but have you tried something like this? (attempted to write it in mooTools, but have no idea what I'm doing).
$('uploadLink').addEvent('click', function(){
if(Browser.firefox) $('uploadLink').fireEvent('click');
});
or I suppose if it has to wait for the flash to be created, something like this:
$('uploadLink').addEvent('click', function(){
if(Browser.firefox){
var flashTimer = setTimeout(function(){
clearTimeout(flashTimer);
/// or however you make sure the flash has successfully been added to the page
if($('flashContainer').getElements().length) $('uploadLink').fireEvent('click');
},100);
}
});
There's always the possibility that FF's security measures won't let you do something like this (mouse interactions with flash can be potentially harmful, as flash has FS access and stuff).
Depending on what your backend is, I'm highly in favor of skipping flash for file uploads when possible. One very well written plugin for such a task is available here:
http://valums.com/ajax-upload/
Good luck!
I'm looking for a way through AJAX (not via a JS framework!) to real time monitor a file for changes. If changes where made to that file, I need it to give an alert message. I'm a total AJAX noob, so please be gentle. ;-)
Edit: let me explain the purpose a bit more in detail. I'm using a chat script I've written in PHP for a webhop, and what I want is from an admin module monitor the chat requests. The chats are stored in text files, and if someone starts a chat session a new file is created. If that's the case, in the admin module I want to see that in real time.
Makes sense?
To monitor a file for changes with AJAX you could do something like this.
var previous = "";
setInterval(function() {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if (ajax.responseText != previous) {
alert("file changed!");
previous = ajax.responseText;
}
}
};
ajax.open("POST", "foo.txt", true); //Use POST to avoid caching
ajax.send();
}, 1000);
I just tested it, and it works pretty well, but I still maintain that AJAX is not the way to go here. Comparing file contents will be slow for big files. Also, you mentionned no framework, but you should use one for AJAX, just to handle the cross-browser inconsistencies.
AJAX is just a javascript, so from its definition you do not have any tool to get access to file unless other service calls an js/AJAX to notify about the change.
I've done that from scratch recently.
I don't know how much of a noob you are with PHP (it's the only server script language I know), but I'll try to be as brief as possible, feel free to ask any doubt.
I'm using long polling, which consists in this (
Create a PHP script that checks the content of the file periodically and only responds when it sees any change (it could include a description of the change in the response)
Create your XHR object
Include your notification code as a callback function (it can use the description)
Make the request
The PHP script will start checking the file, but won't reply until there is a change
When it responds, the callback will be called and your notification code will launch
If you don't care about the content of the file, only that it has been changed, you can check the last-modified time instead of the content in the PHP script.
EDIT: from some comment I see there's something to monitor file changes called FAM, that seems to be the way to go for the PHP script