Giter Site home page Giter Site logo

cmlenz / jquery-iframe-transport Goto Github PK

View Code? Open in Web Editor NEW
354.0 354.0 156.0 360 KB

jQuery Ajax transport plugin that supports file uploads through a hidden iframe

Home Page: http://cmlenz.github.com/jquery-iframe-transport/

License: MIT License

JavaScript 87.23% CSS 0.39% HTML 12.38%

jquery-iframe-transport's People

Contributors

braddunbar avatar cmlenz avatar jangosteve avatar jbyers avatar laurens avatar omahlama avatar s2b avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-iframe-transport's Issues

Aborting an upload

A simple change should enable you to entirely cancel uploads. Instead of appending the proxy form to the document.body, attach it to the iframe's document.body. To abort after submission, simply remove the iframe.

No additional data sent

Hi!

I used this plugin with jquery 1.6.1, but when I upgraded to 1.7.1 the additional form data was not sent. With blind troubleshooting I found out that the additional data was not found in options.data, but it was in the origOptions.data. I fixed it by just adding:

options.data = origOptions.data;

to line 137.

File not chosen after starting upload

Does anyone have the same problem? This happens in chrome.
The input tag correctly shows the file path and the type logo, but once the iframe-transport script starts running it the tag shows "file not chosen". Everything
works fine, with the exception that if gives the impression to the user that something is wrong...

Please add version tags

Hi,

please add version tags so jquery.iframe-transport can be installed via bower install jquery.iframe-transport#1.8.1

-- ooxi

How to get an error if the server fails to respond?

The docs say if any errors occur, those should be reported in the response body, but if the server fails and can't actually create a response, then the JS can't get notified and .done or .fail are not called at all.

Submitting request with Opera prompts file download.

Version: 11.64
Build: 1403
Platform: Mac OS X
System: 10.7.3

When I try to upload the file the browser tries to download the json response as a file.

I respond with:

content type: application/json
url: "/v1/users/:id.json"

Add support for cross domain uploads

I am trying to upload files to another domain(amazon s3). Amazon s3 can be made to set a 303 redirect to another url where I am returning a textarea as per the documentation. This is working in browsers except IE8 where I am getting an access denied. The line indicated by the debugger is

var doc = this.contentWindow ? this.contentWindow.document :

I am using a slightly older version of your plugin but the lines indicated have not been changed.
This is how a typical form looks like :

<form enctype="multipart/form-data" method="post" action="http://flosadasXXX.s3.amazonaws.com/" id="upload" class="" target="">
<input type="hidden" name="key" value="p9B2Jq0kEeCn1QAW6paCyA/d0tbgrIgEeC_xAAW6paCyA">
<input type="hidden" name="signature" value="vPS750BKR8lt4aIPYpWR759L1Os=">
<input type="hidden" name="AWSAccessKeyId" value="AKIAJE7UXTTTQ">
<input type="hidden" name="policy" value="eyJleHBpcmF0aW9uIjogIjIwMTEtMDctMTlUMTc6NDI6MTNaIiwKImNvbmRpdGlvbnMiOiBbeyJ4LWFtei1tZXRhLXVpZWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsIDAsIDEwNDg1NzYwXSx7ImJ1Y2tldCI6ICJmbG9ja2VkaW5uZXN0LmxpdHRsZXdpa2kuaW4ifSx7ImtleSI6ICJwOUIySnEwa0VlQ24xUUFXNnBhQ3lBL2QwdGJncklnRWVDX3hBQVc2cGFDeUEifSx7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9sb2NhbGhvc3Q6ODAwMC9maWxlL3VwZGF0ZSJ9XX0=">
<input type="hidden" name="success_action_redirect" value="http://localhost:8000/file/update">
<input type="hidden" name="x-amz-meta-fileId" value="d0tbgrIgEeC_xAAW6paCyA">
<input type="hidden" name="content-type" value="text/plain">
<input type="hidden" name="x-amz-meta-filename" value="rcpts_edit.txt">
<input type="hidden" name="x-amz-meta-uid" value="p9B2Jq0kEeCn1QAW6paCyA">
<span class="file-overlay">
<input type="file" size="1" name="file" id="file-attach-input">
</span>
<button title="Attach a file" type="button" class="button" id="file-share">
<img alt="Attach a file" src="/rsrcs/img/attach.png">
</button>
<!--<input type="submit" value="Submit"/>-->
<input type="hidden" name="X-Requested-With" value="IFrame"></form>

Let me know if you need more information.

Thanks,
Abhi

[object Object] and Firefox 35.0

Hi,
I'm using this plugin in my backbone.js application to send JSON data and files in the same request. Thats how i do it:

this.model.save(that.model.attributes, {
     iframe: true,
     dataType: 'json',
     contentType: false,
     files: this.$('form :file'),
     data: that.model.attributes
}).done(function(){...});

And it works fine everywhere, except Firefox 35.0 -- it sends me an [object Object] in request and nothing else.
Do you have an ideas, what i'm doing wrong?

IE asks to download JSON file -- Demo

When doing an upload in IE (tested in 10, 9) the browser responds with asking if you want to download the returning JSON file. Is this an issue with the demo or the plugin in general?

[patch] If the textarea exists but does not have data-status and data-statusText attributes, they end up being NULL.

Here's a patch to fix that:

diff --git a/jquery.iframe-transport.js.1 b/jquery.iframe-transport.js
index b5ba270..a71425a 100644
--- a/jquery.iframe-transport.js.1
+++ b/jquery.iframe-transport.js
@@ -182,17 +182,22 @@
                 (this.contentDocument ? this.contentDocument : this.document),
                 root = doc.documentElement ? doc.documentElement : doc.body,
                 textarea = root.getElementsByTagName("textarea")[0],
-                type = textarea ? textarea.getAttribute("data-type") : null,
-                status = textarea ? textarea.getAttribute("data-status") : 200,
-                statusText = textarea ? textarea.getAttribute("data-statusText") : "OK",
-                content = {
+                type, status, statusText;
+                if(textarea) {
+                    type = textarea.getAttribute("data-type");
+                    status = textarea.getAttribute("data-status");
+                    statusText = textarea.getAttribute("data-statusText");
+                }
+                var content = {
                   html: root.innerHTML,
                   text: type ?
                     textarea.value :
                     root ? (root.textContent || root.innerText) : null
                 };
-              cleanUp();
-              completeCallback(status, statusText, content, type ?
+                if(!status) status = 200;
+                if(!statusText) statusText = "OK";
+                cleanUp();
+                completeCallback(status, statusText, content, type ?
                 ("Content-Type: " + type) :
                 null);
             });

File input events

When I try to bind change event to file input:

$file = $('<input type="file" name="file" multiple>')
     .appendTo('form').change(function(){
           that.onFileChange();
     });

This works for first upload, but next fail. As I understood, the elements are replaced. Please add replacing events to.

Documentation for Browser Support

It'd be great to have the information on browser support to the README.md. Is this possible to get? Just want to make sure this will fix what I hope it will ๐Ÿ˜„

Content Security Policy warning

In Firefox and Chrome (haven't tried IE), I'm getting a content security policy warning upon calling $.ajax. If I change the content security policy to unsafe-inline on script-src, the issue goes away.

I used the debugger to track the issue. It appears to happen when the iframe is appended to the body.

I change line 193,194 from

iframe = $("<iframe src='javascript:false;' name='" + name +
            "' id='" + name + "' style='display:none'></iframe>");

to

iframe = $("<iframe name='" + name +
            "' id='" + name + "' style='display:none'></iframe>");

and the warning goes away. I am not sure, however, what else this might affect.

When submitting file on Chrome, response is 200 OK but status is "(canceled)".

Although the file is sent successfully with this code:

Send this file: <input id="myfile" type="file" name="filename" />

<script type='text/javascript'>

$(document).ready(function() {

    $('#myfile').change(function() {
        $.ajax("/ajaxpost/upload.php", {
            files: $('#myfile'),
            iframe: true,
            success: function(data) {
                console.log('success');
                console.log(data);
            },
            complete: function(data) {
                console.log('complete');
                console.log(data);
            },
            error: function(data) {
                console.log('error');
                console.log(data);
            }
        });

    });

});

</script>

The Google Chrome (16.0 in my test) browser will report the result as 200 OK but status "(canceled)". Some hints on the web talked about cross-domain issues and/or header type issues but neither seemed to apply in my simple test.

I was finally able to get rid of the "(canceled)" message by modifying the original source code, removing the line in cleanUp()...

 function cleanUp() {
      markers.replaceWith(function(idx) {
        return files.get(idx);
      });
      form.remove();
      //iframe.attr("src", "javascript:false;").remove();
    }

I don't know why commenting out that last line fixes the problem. Maybe someone with much more Javascript and browser knowledge can shed some light.

Incompatibility with PECL uploadprogress

Hi,

this transport works great for uploading files but in it's current state is incompatible with PECL uploadprogress library when using "data" attribute to submit the UPLOAD_IDENTIFIER parameter.

The UPLOAD_IDENTIFIER needs to be inserted before the file input otherwise the uploadprogress won't work. I managed to solve this by changing "appendTo" to "prependTo" on line 153. Maybe this change should make it to stable version or maybe only for UPLOAD_IDENTIFIER data?

Best
Jan

[enhancement] Add missing bower.json.

Hey, maintainer(s) of cmlenz/jquery-iframe-transport!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library cmlenz/jquery-iframe-transport is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "cmlenz/jquery-iframe-transport",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Runtime error in IE when REST request threw an exception

In IE9, if the server request threw an exception, the reference to "this.contentWindow.document" at line 182 throws an "Access Denied" runtime exception. (Thank you, Microsoft.) Wrapping the current load function implementation in a try/catch:

try
{
var doc = [...]
[...]
}
catch (e) {
cleanUp();
completeCallback(500, "Internal Server Error");
}

appears to fix the problem.

Any thoughts or comments on this would-be workaround?

Dave

Iframe url additional character

In jquery.iframe-transport.js, options.url get the "?" character at the final of the string.

If the action url is /user/avatar the iframe form action url will be /user/avatar?

This can be a problem for some configurations. I have temporally fixed this with:

options.url = options.url.replace(/(\?)$/, '');

before the form is builded. line ~190.

[patch] If the textarea exists but does not have data-status and data-statusText attributes, they end up being NULL.

Here's a patch to fix that:

diff --git a/jquery.iframe-transport.js.1 b/jquery.iframe-transport.js
index b5ba270..a71425a 100644
--- a/jquery.iframe-transport.js.1
+++ b/jquery.iframe-transport.js
@@ -182,17 +182,22 @@
(this.contentDocument ? this.contentDocument : this.document),
root = doc.documentElement ? doc.documentElement : doc.body,
textarea = root.getElementsByTagName("textarea")[0],

  •            type = textarea ? textarea.getAttribute("data-type") : null,
    
  •            status = textarea ? textarea.getAttribute("data-status") : 200,
    
  •            statusText = textarea ? textarea.getAttribute("data-statusText") : "OK",
    
  •            content = {
    
  •            type, status, statusText;
    
  •            if(textarea) {
    
  •                type = textarea.getAttribute("data-type");
    
  •                status = textarea.getAttribute("data-status");
    
  •                statusText = textarea.getAttribute("data-statusText");
    
  •            }
    
  •            var content = {
               html: root.innerHTML,
               text: type ?
                 textarea.value :
                 root ? (root.textContent || root.innerText) : null
             };
    
  •          cleanUp();
    
  •          completeCallback(status, statusText, content, type ?
    
  •            if(!status) status = 200;
    
  •            if(!statusText) statusText = "OK";
    
  •            cleanUp();
    
  •            completeCallback(status, statusText, content, type ?
             ("Content-Type: " + type) :
             null);
         });
    

LICENSE?

Would be good to have a license on this library :)

Can't get this to work.

I copied the code verbatim into a new html file (actually merged the html and js into one file) running under tomcat. I'm planning on uploading the files to tomcat.

When I try to upload a file:

Request URL:http://localhost:8080/profile/image
Request Method:GET
Status Code:405 Method Not Allowed

It's not even hitting the code unless I put dataType: 'iframe' and won't do a post unless I add type: 'POST'.

The endpoint works fine. I'ved tested that. Tried with Chrome and FF. Neither seem to work.

What Cam I doing wrong?

[patch] XHTML compatibility

Using the plugin with XHTML5 resulted in firefox not parsing the page correctly. Fix below.

--- static/js/jquery.iframe-transport.js    (revision 4818)
+++ static/js/jquery.iframe-transport.js    (working copy)
@@ -142,14 +142,14 @@
           name = value.name;
           value = value.value;
         }
-        $("<input type='hidden'>").attr({name:  name, value: value}).
+        $("<input type='hidden'></input>").attr({name:  name, value: value}).
           appendTo(form);
       });

       // Add a hidden `X-Requested-With` field with the value `IFrame` to the
       // field, to help server-side code to determine that the upload happened
       // through this transport.
-      $("<input type='hidden' value='IFrame' name='X-Requested-With'>").
+      $("<input type='hidden' value='IFrame' name='X-Requested-With'></input>").
         appendTo(form);

       // Move the file fields into the hidden form, but first remember their

Fix for object, array and string data support

I wanted to use your plugin at some other plugin I was making, so I took the liberty of fixing the script to allow support for arrays, objects and strings:

Just replace where it says:

// If there is any additional data specified via the `data` option,
// we add it as hidden fields to the form. This (currently) requires
// the `processData` option to be set to false so that the data doesn't
// get serialized to a string.
if (typeof(options.data) === "string" && options.data.length > 0) {
    $.error("data must not be serialized");
}
$.each(options.data || {}, function(name, value) {
    if ($.isPlainObject(value)) {
        name = value.name;
        value = value.value;
    }
    $("<input type='hidden' />").attr({name:  name, value: value})
                                .appendTo(form);
});

With the following:

// Convert data to string, if not already a string
if ( options.data && options.processData && typeof options.data !== "string" ) {
    options.data = jQuery.param( options.data, options.traditional );
}

// Convert string to file inputs to be submitted to the iframe

// Split string by "&"
var splitString= decodeURIComponent( options.data ).split("&");
for ( var i = 0; i < splitString.length; i++ ) {
    // Split substing by "="
    var keyValuePair= splitString[i].split("=");
    // Create input field with name and value of split string
    $("<input type='hidden' />").attr({name: keyValuePair[0], value: keyValuePair[1]})
                                     .appendTo( form );
}

Please add this to the actual plugin!
Also use the fix mentioned on another issue, so that data are submitted in jQuery 1.7+!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.