Php/ajax files uploading: hidden iframe loads more than once - php

My problem occurs, when I upload images with ajax. Ajax response comes to a hidden iframe, and for debug I echo it (uploaded image name) here and then alert it. So when I upload the first image - there's one alert, as it should be. When I upload the 2nd - I see 2 alerts. The 3rd - 3 alerts. And so on. It means, that my iframe reloads as many times, as the order number of the file being just uploaded.
Interesting, that the names in alerts after each file upload are always the same. For example, 2 times "mySecondImage.jpg", 3 times "myThirdImage.jpg"...
What can be done to solve the problem? Thanks.
// FUNCTION - AJAX FILE UPLOADER
// this function creates new elements, but only in case, when user uploads files
$.fn.fileUploader = function ( $inputName ) {
var $body = $(this);
var $form = $body.parents('form');
var $fileInput = $body.find(':file');
// after file is uploaded, we need the file input to be empty again
var $fileInputEmpty = '<input type="file" name="' + $inputName + '" />';
var $iframe = $('#ajaxResult');
// user submits the form
$form.submit( function() {
// check the result
$iframe.load( function () {
var $response = $iframe.contents().find('body').html();
alert($response); // debug
// add new content image
$output = createUpdateImage( $response, $('[name="imageLinkURL"]').val() );
// add new element
addNewElement( $output );
// success
if ( $response.length ) {
$fileInput.replaceWith( $fileInputEmpty );
$fileInput = $body.find(':file');
}
});
}); // form submit
};
$('.fileUploder').each(function () {
var $inputName = $(this).find(':file').attr('name');
$(this).fileUploader( $inputName );
});
Well, the glitch is fixed!
I slightly rewrote the jQuery function:
...
// user submits the form
$form.submit( function() {
var $response = '';
$iframe.load( function () {
$response = $iframe.contents().find('body').html();
});
// periodically check the result in iframe
var $timer = setInterval( function() {
if ( $response != '' ) {
clearInterval( $timer );
// do all required actions
}
}, 100 );
}); // form submit
...

$form.submit( function() {
$iframe.load( function () {
I think the problem is here. On form submit you add an event "on load". So it called 1 time, then 2 times, etc. Maybe removing the first of these two strings can help (use only load event handler).

Related

Calling WordPress Gallery Uploader/Selector From Metabox

When I click the Add Media button on a Post/Page, I have the option to Add Media. After selecting media, I click Insert Into Post, and the images are inserted. However, there is another option, which is on the left sidebar. I can click Create Gallery. The image selecting process is the same, but when I click Create New Gallery, it goes to a new frame which allows me to edit the order of the images.
This second window is what I am after. I am calling the frame from a metabox, and I have gotten it successfully to allow me to grab single or multiple images and save the ID's as a string, as well as insert thumbnails live into a preview box. I cannot find anything about calling the Gallery frame.
My current code is as follows:
jQuery('#fg_select').on('click', function(event){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frame = wp.media({
title: "Select Images For Gallery",
button: {text: "Select",},
library : { type : 'image'},
multiple: true // Set to true to allow multiple files to be selected
});
file_frame.on('open', function() {
var selection = file_frame.state().get('selection');
ids = jQuery('#fg_metadata').val().split(',');
ids.forEach(function(id) {
attachment = wp.media.attachment(id);
attachment.fetch();
selection.add( attachment ? [ attachment ] : [] );
});
});
file_frame.on('ready', function() {
// Here we can add a custom class to our media modal.
// .media-modal doesn't exists before the frame is
// completly initialised.
$( '.media-modal' ).addClass( 'no-sidebar' );
});
// When an image is selected, run a callback.
file_frame.on('select', function() {
var imageIDArray = [];
var imageHTML = '';
var metadataString = '';
images = file_frame.state().get('selection');
images.each(function(image) {
imageIDArray.push(image.attributes.id);
imageHTML += '<li><button></button><img id="'+image.attributes.id+'" src="'+image.attributes.url+'"></li>';
});
metadataString = imageIDArray.join(",");
if(metadataString){
jQuery("#fg_metadata").val(metadataString);
jQuery("#featuredgallerydiv ul").html(imageHTML);
jQuery('#fg_select').text('Edit Selection');
jQuery('#fg_removeall').addClass('visible');
}
});
// Finally, open the modal
file_frame.open();
});
Any ideas?
EDIT:
I've gotten it to the point where it calls the gallery directly, without any sidebars, etc. However, it now ignores the on('select') call. I guess galleries send a different call when selecting the image?
jQuery(document).ready(function($){
// Uploading files
var file_frame;
jQuery('#fg_select').on('click', function(event){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frame = wp.media({
frame: "post",
state: "featured-gallery",
library : { type : 'image'},
button: {text: "Edit Image Order"},
multiple: true
});
file_frame.states.add([
new wp.media.controller.Library({
id: 'featured-gallery',
title: 'Select Images for Gallery',
priority: 20,
toolbar: 'main-gallery',
filterable: 'uploaded',
library: wp.media.query( file_frame.options.library ),
multiple: file_frame.options.multiple ? 'reset' : false,
editable: true,
allowLocalEdits: true,
displaySettings: true,
displayUserSettings: true
}),
]);
file_frame.on('open', function() {
var selection = file_frame.state().get('selection');
ids = jQuery('#fg_metadata').val().split(',');
if (!empty(ids)) {
ids.forEach(function(id) {
attachment = wp.media.attachment(id);
attachment.fetch();
selection.add( attachment ? [ attachment ] : [] );
});
}
});
file_frame.on('ready', function() {
// Here we can add a custom class to our media modal.
// .media-modal doesn't exists before the frame is
// completly initialised.
$( '.media-modal' ).addClass( 'no-sidebar' );
});
file_frame.on('change', function() {
// Here we can add a custom class to our media modal.
// .media-modal doesn't exists before the frame is
// completly initialised.
setTimeout(function(){
$('.media-menu a:first-child').text('← Edit Selection').addClass('button').addClass('button-large').addClass('button-primary');
},0);
});
// When an image is selected, run a callback.
file_frame.on('set', function() {
alert('test');
});
// Finally, open the modal
file_frame.open();
});
EDIT 2:
Okay, so I've gotten everything to fire correctly. But I can't decipher the outputted gallery code.
// When an image is selected, run a callback.
file_frame.on('update', function() {
var imageIDArray = [];
var imageHTML = '';
var metadataString = '';
images = file_frame.state().get('selection');
images.each(function(image) {
imageIDArray.push(image.attributes.id);
imageHTML += '<li><button></button><img id="'+image.attributes.id+'" src="'+image.attributes.url+'"></li>';
});
metadataString = imageIDArray.join(",");
if (metadataString) {
jQuery("#fg_metadata").val(metadataString);
jQuery("#featuredgallerydiv ul").html(imageHTML);
jQuery('#fg_select').text('Edit Selection');
jQuery('#fg_removeall').addClass('visible');
}
});
Nothing is coming out for $imageArray, or $imageHTML. $image is something, it's an [object object].
EDIT 3: As mentioned below in comment, the main problem with the code from Edit 2 is that when using Gallery, you have to call 'library' instead of 'selection'.
// Uploading files
var file_frame;
jQuery('#fg_select').on('click', function(event){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frame = wp.media({
frame: "post",
state: "gallery",
library : { type : 'image'},
button: {text: "Edit Image Order"},
multiple: true
});
file_frame.on('open', function() {
var selection = file_frame.state().get('selection');
var ids = jQuery('#fg_metadata').val();
if (ids) {
idsArray = ids.split(',');
idsArray.forEach(function(id) {
attachment = wp.media.attachment(id);
attachment.fetch();
selection.add( attachment ? [ attachment ] : [] );
});
}
});
// When an image is selected, run a callback.
file_frame.on('update', function() {
var imageIDArray = [];
var imageHTML = '';
var metadataString = '';
images = file_frame.state().get('library');
images.each(function(attachment) {
imageIDArray.push(attachment.attributes.id);
imageHTML += '<li><button></button><img id="'+attachment.attributes.id+'" src="'+attachment.attributes.url+'"></li>';
});
metadataString = imageIDArray.join(",");
if (metadataString) {
jQuery("#fg_metadata").val(metadataString);
jQuery("#featuredgallerydiv ul").html(imageHTML);
jQuery('#fg_select').text('Edit Selection');
jQuery('#fg_removeall').addClass('visible');
}
});
// Finally, open the modal
file_frame.open();
});
The main thing here I'm having difficulty with now is that I can't get it to open to gallery-edit with a selection. I can get it to open there, but there are no images selected. I'm looking into that. I'm also looking into re-opening instead of creating a new view and sending a pre-selection. If I go to the selection window, then the order window, but click the X to close, I can re-open to the order window. So there should be a way.
EDIT 4
As per code from answer below, I've changed the pre-selection code to:
file_frame.on('open', function() {
var library = file_frame.state().get('library');
var ids = jQuery('#fg_perm_metadata').val();
if (ids) {
idsArray = ids.split(',');
idsArray.forEach(function(id) {
attachment = wp.media.attachment(id);
attachment.fetch();
library.add( attachment ? [ attachment ] : [] );
});
}
});
This allows me to re-open directly to the gallery-edit state and have images pre-selected. However, when I open directly to this state, I cannot click Cancel Gallery (return to image selection state). Clicking that button/link just closes the frame. I tried pre-filling both the library and the selection, but that doesn't work either. The following is from media-views.js, and seems to be what controls that button. Instead of changing the state to a specific state, it changes it to the previous state. Since we are opening directly to gallery-edit, there is no past state. I'm wondering if it's possible to open to gallery, and then on open, change to gallery-edit. Do it instantly so that the user doesn't see, but so that it gets the past state into the system.
galleryMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
EDIT 5:
Finally figured it all out. I couldn't get the above to work at all, I'm not sure why. So, there may be a better way to do this, involving that code. If so, I'd love to know.
file_frame.on('open', function() {
var selection = file_frame.state().get('selection');
var library = file_frame.state('gallery-edit').get('library');
var ids = jQuery('#fg_perm_metadata').val();
if (ids) {
idsArray = ids.split(',');
idsArray.forEach(function(id) {
attachment = wp.media.attachment(id);
attachment.fetch();
selection.add( attachment ? [ attachment ] : [] );
});
file_frame.setState('gallery-edit');
idsArray.forEach(function(id) {
attachment = wp.media.attachment(id);
attachment.fetch();
library.add( attachment ? [ attachment ] : [] );
});
}
});
FINAL EDIT
My code is now working entirely, and I appreciate the help! If you'd like to see it in action, check out http://wordpress.org/plugins/featured-galleries/
I'm relatively new to WP. In fact, I'm building my first WP theme and I'm stuck on the same question as you. Thank to your code, I can get to the Gallery page. And luckily, I've got the images saved. Here's my code:
// when click Insert Gallery, run callback
wp_media_frame.on('update', function(){
var library = wp_media_frame.state().get('library');
var images = [];
var image_ids = [];
thumb_wraper.html('');
library.map( function( image ) {
image = image.toJSON();
images.push(image.url);
image_ids.push(image.id);
thumb_wraper.append('<img src="' + image.url + '" alt="" />');
});
});
What I have found is you should get 'library' instead of get 'selection'.
Edit:
I've figured out how to go back to gallery-edit. Here is my full code:
$( '#btn_upload' ).on( 'click', function( event ) {
event.preventDefault();
var images = $( '#image_ids' ).val();
var gallery_state = images ? 'gallery-edit' : 'gallery-library';
// create new media frame
// You have to create new frame every time to control the Library state as well as selected images
var wp_media_frame = wp.media.frames.wp_media_frame = wp.media( {
title: 'My Gallery', // it has no effect but I really want to change the title
frame: "post",
toolbar: 'main-gallery',
state: gallery_state,
library: {
type: 'image'
},
multiple: true
} );
// when open media frame, add the selected image to Gallery
wp_media_frame.on( 'open', function() {
var images = $( '#image_ids' ).val();
if ( !images )
return;
var image_ids = images.split( ',' );
var library = wp_media_frame.state().get( 'library' );
image_ids.forEach( function( id ) {
attachment = wp.media.attachment( id );
attachment.fetch();
library.add( attachment ? [ attachment ] : [] );
} );
} );
// when click Insert Gallery, run callback
wp_media_frame.on( 'update', function() {
var thumb_wrapper = $( '#thumb-wrapper' );
thumb_wraper.html( '' );
var image_urls = [];
var image_ids = [];
var library = wp_media_frame.state().get( 'library' );
library.map( function( image ) {
image = image.toJSON();
image_urls.push( image.url );
image_ids.push( image.id );
thumb_wrapper.append( '<img src="' + image.url + '" alt="" />' );
} );
} );
} );
I figured that if you re-open the existed frame, it'll always keep the initial state, in your case it's 'gallery'. You'll have to create new frame every time and check if there's images to open 'gallery-edit'
Also, I prefer 'gallery-library' than 'gallery' because I want user to focus on my gallery.

JQuery Ajax Calls -- Intermittent image display issues (Chrome & FF) (some PHP and MySQL)

I use JQuery to pull form data and send an XMLHttpRequest(); I open the request using the POST method. The image and supplementary data are passed to a PHP script that handles, resizes, and saves it to the server. The file name and location of the image are updated in the relevant fields in a MySQL database. On the uploadComplete(evt) I attempt to display the newly uploaded image by calling .load() to populate a div.
80% of the time, the image displays correctly when the content is loaded into the div. 20% of the time, the image is displayed as if the link provided were a broken link. However, if I refresh the page, the image is displayed correctly.
Why does the image sometimes show as a broken link?
How do I stop it from doing this?
* EDIT
function loadFile()
{
var fileURL = $( "#url" ).val();
if(fileURL == "")
{
// Retrieve the FileList object from the referenced element ID
var myFileList = document.getElementById('upload_file').files;
// Grab the first File Object from the FileList
var myFile = myFileList[0];
// Set some variables containing the three attributes of the file
var myFileName = myFile.name;
var myFileSize = myFile.size;
var myFileType = myFile.type;
// Let's upload the complete file object
imageUpdate(myFile);
}
else
{
var newinfo = new Array();
newinfo[0] = "URL";
newinfo[1] = fileURL;
imageUpdate(newinfo);
}
}
function imageUpdate(newinfo)
{
var formData = new FormData(); // data object
// extra
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
formData.append("stylistID", stylistID);
// IF URL
if ( newinfo[0] == "URL" ){
formData.append("type", "URL");
formData.append("url", newinfo[1]);
}
// IF LOCAL FILE
else
{
formData.append("type", "FILE");
// Append our file to the formData object
// Notice the first argument "file" and keep it in mind
formData.append('my_uploaded_file', newinfo);
}
// Create our XMLHttpRequest Object
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
// Open our connection using the POST method
xhr.open("POST", "u/stylist_avatar.php", true);
// Request headers
//xhr.setRequestHeader("Content-Type", formData.files[0].type);
// Send the file
xhr.send(formData);
}
// While xhr is in progress
function updateProgress(oEvent)
{
if (evt.lengthComputable)
{
//var progressBar = document.getElementById("progressBar");
//var percentComplete = oEvent.loaded / oEvent.total;
//progressBar.value = percentComplete;
}
else
{
// unable to compute progress information since the total size is unkown
}
}
// onComplete
function uploadComplete(evt) {
//alert("The transfer is complete.");
resetForm($('#uploadImageForm'));
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
$('#uploadImageModal').modal('toggle');
// Reload right div
$( "#editStylistRight" ).load( "u/stylist_lookup.php", {stylistID: stylistID}, function (){});
// Reload stylist list
var index = 0;
var numRecords = 10;
$( "#stylistTable" ).load( "u/stylist_lookuptable.php", {start: index, end: numRecords}, function (){});
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
It seems that you are trying to show the new image before the PHP script in fact create and save the new image.
Instead of calling the javascript function that loads the new image on the "uploadComplete", use the "success" param (if you are using jQuery $.ajax function) that call the function that loads the new image.
The "success" function is called only when the server finish processing the request (when the PHP script finish editing and saving the image) and not when the new image params were succesfully sent to the server.
This happens because of image cache,force browser to fetch image evrytime.
use this in uploadcomplete event
var timestamp = new Date();
timestamp = timestamp.getTime();
imageurl+'?t='+timestamp;

Retrieving data from form made in javascript

I have uploaded a fiddle of my JS code (http://jsfiddle.net/3mcm2/), at the very bottom of which is the way in which I am calling the JS in my PHP document. In order to run the script, just remove the PHP code comments from the bottom. I just wanted to add that for you to see how I am outputting it in PHP. Also, above those last comments are three lines of comments in the .js file, which are there for you to see what it is that the PHP is echoing just to help you better understand how everything looks.
/* The following is what is in my .js file: (see the bottom of this script for part of
what is in my PHP file) */
var f = document.createElement("form");
f.setAttribute('method', "get");
f.setAttribute('action', "index.php");
var Category = (function () {
var categoryCount = 0;
function elem(tag) { // shortcut
return document.createElement(tag);
}
function text(str) { // shortcut
return document.createTextNode(str);
}
function Category(node) {
var self = this;
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.append(node);
}
}
Category.prototype.addTextbox = function () {
var e = document.createElement("input");
e.setAttribute('name', 'cat-'+this.categoryId+'-textbox[]');
f.appendChild(e); // this is where each textbox is supposed to be added to the form...
this.textboxes.push(e);
this.wrapper.insertBefore(e, this.addButton);
};
Category.prototype.append = function (node) {
return node.appendChild(this.wrapper);
};
return Category;
}());
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(s);
//var cat1 = new Category(document.body);
//var cat2 = new Category(document.body);
//document.getElementsByTagName('body')[0].appendChild(f);
The above comment is only for you to see what this script is doing and those three lines are not actually in my .js file. the following comments are part of what is in my PHP file, pretty much just outputting the above comments:
$counter = 0;
echo '<script type="text/javascript" src="js/categories.js"></script>';
foreach ($catArr as $category) {
$counter++;
echo 'do<script>var cat'.$counter.' = new Category(document.body);</script>';
}
echo "<script>document.getElementsByTagName('body')[0].appendChild(f);</script>";
My problem is that with the form I created in the JS, the GET is not delivering any data. My php page is simply going from index.php to index.php? with the question mark, and not with any of the textbox variables following the question mark. For some reason, the form is not finding those textboxes that are created or their names. Please help me out.
This code:
var cat1 = new Category(document.body);
function Category(node) {
var self = this;
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.appendChild(node);
}
}
appends all your input text boxes to the body and not the form, so when you press Submit no data is being passed
fiddle with working code: http://jsfiddle.net/5H8Pv/1/

calling on a complex function with onClick (ajax)

So I have this chunk of code here (below). It waits for a video to finish playing and then it looks up a cookie, sends that info to a php script through ajax, gets back a url from json, and reloads an iframe with a new url.
So I think you'll agree, it's sorta a lot going on.
Its purpose is to advance ONE forward in a playlist of videos. I am trying to create a button area where a user can click a >> sort of button and go forward. Which is exactly what this function does.
Rather than starting from scratch with a new function, is there a way to activate all of the above function functionality (ajax and all) when the user clicks that button?
<script>
function ready(player_id)
{
$f('play').addEvent('ready', function()
{
$f('play').addEvent('finish', onFinish);
});
function onFinish(play)
{
var now_video_var = $.cookie('now_video');
console.log ('player ' + now_video_var + ' has left the building');
var intermediate_integer = parseInt(now_video_var);
var request2 = $.ajax({
url : "geturl.php",
data : {intermediate_integer : intermediate_integer},
type : 'post'
}).done(function(data) {
var gotfrom = jQuery.parseJSON(data);
var NEWURL = gotfrom[1] ;
console.log(gotfrom);
console.log(data);
console.log(gotfrom[1]);
var theiframeforrealyo = document.getElementById('play');
$(theiframeforrealyo).attr("src", "http://player.vimeo.com/video/" + gotfrom[1] +"?api=1&player_id=play&title=0&byline=0&portrait=0&autoplay=1");
var new_video_var = intermediate_integer +1;
$.cookie('now_video', new_video_var);
console.log ( 'cookie function ok: the cookie is....');
console.log ($.cookie('now_video'));
});
}
}
window.addEventListener('load', function() {
//Attach the ready event to the iframe
$f(document.getElementById('play')).addEvent('ready', ready);
});
</script>

Why form.submit() is fails IE9 , when form in iframe and user coming through gmail

I created function to send email with a back link to my site, I'm using codeigniter framework
after user click that particular link (back link) on email, user redirects to my page which has an iframe.
i used that iframe to submit a form with file input, with out page refreshing.
When user coming through that link using gmail in IE9 browser the form.submit() function fails, in other browsers it works properly and other email(except gmail) too.
pleas help me to find solution
thank you.
update
actually I'm using the ajaxupload jquery library, it fails on the line form.submit(); at above scenario
/* Creates form, that will be submitted to iframe
* #param {Element} iframe Where to submit
* #return {Element} form
*/
_createForm: function(iframe){
var settings = this._settings;
// We can't use the following code in IE6
// var form = document.createElement('form');
// form.setAttribute('method', 'post');
// form.setAttribute('enctype', 'multipart/form-data');
// Because in this case file won't be attached to request
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.setAttribute('action', settings.action);
form.setAttribute('target', iframe.name);
form.style.display = 'none';
document.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data) {
if (settings.data.hasOwnProperty(prop)){
var el = document.createElement("input");
el.setAttribute('type', 'hidden');
el.setAttribute('name', prop);
el.setAttribute('value', settings.data[prop]);
form.appendChild(el);
}
}
return form;
},
/**
* Gets response from iframe and fires onComplete event when ready
* #param iframe
* #param file Filename to use in onComplete callback
*/
_getResponse : function(iframe, file){
// getting response
var toDeleteFlag = false, self = this, settings = this._settings;
addEvent(iframe, 'load', function(){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
// We reload to blank page, so that reloading main page
// does not re-submit the post.
if (toDeleteFlag) {
// Fix busy state in FF3
setTimeout(function(){
removeNode(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
// fixing Opera 9.26,10.00
if (doc.readyState && doc.readyState != 'complete') {
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument) {
// response is a xml document Internet Explorer property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
doc.normalize();
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = eval("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
},
/**
* Upload file contained in this._input
*/
submit: function(){
var self = this, settings = this._settings;
if ( ! this._input || this._input.value === ''){
return;
}
var file = fileFromPath(this._input.value);
// user returned false to cancel upload
if (false === settings.onSubmit.call(this, file, getExt(file))){
this._clearInput();
return;
}
// sending request
var iframe = this._createIframe();
var form = this._createForm(iframe);
// assuming following structure
// div -> input type='file'
removeNode(this._input.parentNode);
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
form.appendChild(this._input);
form.submit();
// request set, clean up
removeNode(form); form = null;
removeNode(this._input); this._input = null;
// Get response from iframe and fire onComplete event when ready
this._getResponse(iframe, file);
// get ready for next request
this._createInput();
}
};
Check the the code is in iframe if not specify the iframe in form.submit(), i.e.
document.iframename.form.submit();

Categories