phantomjs render_multi_url.js modify output filenames - javascript

I'm trying to modify this script: https://github.com/ariya/phantomjs/blob/master/examples/render_multi_url.js so that instead of "rendermulti-1.png (and so on)" the output files will be named for the web pages they are caps of.
Here's what I tried.
// Render Multiple URLs to file
var RenderUrlsToFile, arrayOfUrls, system;
system = require("system");
/*
Render given urls
#param array of URLs to render
#param callbackPerUrl Function called after finishing each URL, including the last URL
#param callbackFinal Function called after finishing everything
*/
RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) {
var getFilename, next, page, retrieve, urlIndex, webpage, pagename ; //<--
urlIndex = 0;
webpage = require("webpage");
page = null;
// replace forward slashes with underscores //<--
pagename = arrayOfUrls[urlIndex].replace(/\//g,'_'); //<--
getFilename = function() {
// return "rendermulti-" + urlIndex + ".png"; //<--
return pagename + ".png"; //<--
};
next = function(status, url, file) {
page.close();
callbackPerUrl(status, url, file);
return retrieve();
};
retrieve = function() {
var url;
if (urls.length > 0) {
url = urls.shift();
urlIndex++;
page = webpage.create();
page.viewportSize = {
width: 800,
height: 600
};
page.settings.userAgent = "Phantom.js bot";
return page.open("http://" + url, function(status) {
var file;
file = getFilename();
if (status === "success") {
return window.setTimeout((function() {
page.render(file);
return next(status, url, file);
}), 200);
} else {
return next(status, url, file);
}
});
} else {
return callbackFinal();
}
};
return retrieve();
};
arrayOfUrls = null;
if (system.args.length > 1) {
arrayOfUrls = Array.prototype.slice.call(system.args, 1);
} else {
console.log("Usage: phantomjs render_multi_url.js [domain.name1, domain.name2, ...]");
arrayOfUrls = ["www.google.com", "www.bbc.co.uk", "www.phantomjs.org"];
}
RenderUrlsToFile(arrayOfUrls, (function(status, url, file) {
if (status !== "success") {
return console.log("Unable to render '" + url + "'");
} else {
return console.log("Rendered '" + url + "' at '" + file + "'");
}
}), function() {
return phantom.exit();
});
The script runs, but names all files after the first supplied URL and ignores anything after the '/'.
I suspect I'm making some basic error, possibly something to do with scope, but when I move the new variable into the getFileName function things break.
Any help at all will be appreciated.
Thanks!

There are calls to urls.shift() so it's not a good approach to compute filname with arrayOfUrls.
You're true : '/' is an invalid character so you have to replace it with a generic token (as ?, ...).
Alos, because page.open already contains url, it's better to use it to compute filename.
A solution could be :
// Render Multiple URLs to file
var RenderUrlsToFile, arrayOfUrls, system;
system = require("system");
/*
Render given urls
#param array of URLs to render
#param callbackPerUrl Function called after finishing each URL, including the last URL
#param callbackFinal Function called after finishing everything
*/
RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) {
var getFilename, next, page, retrieve, urlIndex, webpage, pagename ; //<--
urlIndex = 0;
webpage = require("webpage");
page = null;
getFilename = function(url) {
return url.replace(/\//g,'_')+ ".png"; //<--
};
next = function(status, url, file) {
page.close();
callbackPerUrl(status, url, file);
return retrieve();
};
retrieve = function() {
var url;
if (urls.length > 0) {
url = urls.shift();
urlIndex++;
page = webpage.create();
page.viewportSize = {
width: 800,
height: 600
};
page.settings.userAgent = "Phantom.js bot";
return page.open("http://" + url, function(status) {
var file;
file = getFilename(url);
if (status === "success") {
return window.setTimeout((function() {
page.render(file);
return next(status, url, file);
}), 200);
} else {
return next(status, url, file);
}
});
} else {
return callbackFinal();
}
};
return retrieve();
};
arrayOfUrls = null;
if (system.args.length > 1) {
arrayOfUrls = Array.prototype.slice.call(system.args, 1);
} else {
console.log("Usage: phantomjs render_multi_url.js [domain.name1, domain.name2, ...]");
arrayOfUrls = ["www.google.com", "www.bbc.co.uk", "www.phantomjs.org"];
}
RenderUrlsToFile(arrayOfUrls, (function(status, url, file) {
if (status !== "success") {
return console.log("Unable to render '" + url + "'");
} else {
return console.log("Rendered '" + url + "' at '" + file + "'");
}
}), function() {
return phantom.exit();
});

yes, I think you could just modify this method
getFilename = function() {
return "rendermulti-" + urlIndex + ".png"; //<--
return pagename + ".png"; //<--
};
to customer your output file names.
PS. I want to ask some ones, do you get this issue:
if you give this js to render 90 html files, but most time it couldn't render them all, I need execute many times to finished all those 90 files.
and I try to split my html files into small array, then to call this js to render, but in this js file, there is a exit method, it would exit my process. so I couldn't loop all these small html file url array to finish them one time.

Related

How to Open a URL/link in between a running ajax call and destroy all running ajax call?

I am working on Web page having an ajax call to the server and from the server(Controller) again a WCF service is called(which takes time) for fetching some data.
Inside server(Controller) i called to service in Parallel by using Task and async-await.
My problem is:
after opening the page that has code for calling the controller and WCF service, I can't redirect my tab/page to another URL by clicking on anchor tab present in UI. until ajax call result is retrieved.
UI CODE:
$(function () {
if (AutomationType.toLowerCase() === "desktop") {
$.ajax({
async: true,
url: "/" + AutomationType + "/Home/GetAllController",
data: { "hostName": hostname},
type: 'POST',
dataType: 'json'
}).success(function (response) {
debugger;
})
}
});
i have tried to abort the ajax call also as below,
$(function() {
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(i, jqXHR) { // cycle through list of recorded connection
jqXHR.abort(); // aborts connection
$.xhrPool.splice(i, 1); // removes from list by index
});
}
$.ajaxSetup({
beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); }, // annd connection to list
complete: function(jqXHR) {
var i = $.xhrPool.indexOf(jqXHR); // get index for current connection completed
if (i > -1) $.xhrPool.splice(i, 1); // removes from list by index
}
});
})
// Everything below this is only for the jsFiddle demo
$('a').click(function () {
$.xhrPool.abortAll();
});
Server(Controller) Code
public async Task<JsonResult> GetAllController(string hostName)
{
string IsControllerRunning = string.Empty;
var currentHost = string.Empty;
var currentRunId = string.Empty;
var currentStatus = string.Empty;
var ipDns = string.Empty;
Stopwatch sw = new Stopwatch(); sw.Start();
List<List<ExecutionStepResult>> returnresultArray = new List<List<ExecutionStepResult>>();
List<Task<IEnumerable<ExecutionStepResult>>> taskList = new List<Task<IEnumerable<ExecutionStepResult>>>();
Debug.WriteLine("starting 1 " + sw.Elapsed);
var resultArray = hostName.TrimEnd('^').Split('^');
for (int i = 0; i < resultArray.Length; i++)
{
string host = resultArray[i];
Task<IEnumerable<ExecutionStepResult>> task = new Task<IEnumerable<ExecutionStepResult>>(() => getServiceResultByTask(host));
task.Start();
taskList.Add(task);
}
foreach (Task<IEnumerable<ExecutionStepResult>> taskitem in taskList)
{
try
{
Debug.WriteLine("calling task " + sw.Elapsed);
IEnumerable<ExecutionStepResult> val = await taskitem;
returnresultArray.Add(val.ToList());
}
catch (Exception ex)
{
returnresultArray.Add(new List<ExecutionStepResult>() { new ExecutionStepResult() { IsError = true, ErrorMessage="true" ,CustomMessage = ex.Message.ToString() } });
}
}
for (int i = 0; i < resultArray.Length; i++)
{
string host = resultArray[i];
currentHost = host.Split('|').GetValue(1).ToString();
currentStatus = host.Split('|').GetValue(2).ToString();
currentRunId = host.Split('|').GetValue(0).ToString();
ipDns = host.Split('|').GetValue(3).ToString();
List<ExecutionStepResult> exeResponse = returnresultArray[i].ToList();
if (exeResponse.Count() > 0 && (currentStatus != "3" || (currentStatus == "3" && exeResponse[i].ErrorMessage == "true")))
IsControllerRunning += host + "|" + exeResponse[0].CustomMessage + "^";
else if (exeResponse.Count() > 0 && currentStatus == "3" && exeResponse[0].ErrorMessage == "false")
IsControllerRunning += host;
}
Debug.WriteLine("end " + sw.Elapsed);
sw.Stop();
return Json(IsControllerRunning, JsonRequestBehavior.AllowGet);
}
calling WCF service:
private IEnumerable getServiceResultByTask(string hosts)
{
using (var service = new RemoteCommandClient())
{
try
{
System.Threading.Thread.Sleep(15000);
string currentHost = hosts.Split('|').GetValue(1).ToString();
string currentStatus = hosts.Split('|').GetValue(2).ToString();
string currentRunId = hosts.Split('|').GetValue(0).ToString();
string ipDns = hosts.Split('|').GetValue(3).ToString();
IEnumerable<ExecutionStepResult> result = service.ExecuteRemoteWithRunId("CHECK_CURRENT_EXECUTION", Convert.ToInt32(currentRunId));
return result;
} catch (Exception ex)
{ throw ex; }
}
}
Still, I don't know how to open /redirect a page URL if an ajax call is running on the server. I am using signalR in the same page also. Please help.

Get the name of the uploaded file

I am new to AngularJS1 and Js. Here i am uploading a file which will be saved on my drive as well as in mongodb. What I am trying to do is to get the uploaded file name which can easily be seen here in attached picture. Kindly help me out with this.
$scope.uploadedFileList.push(p);
$('#addproFile').ajaxfileupload({
action: 'http://' + window.location.hostname + ':' + window.location.port + '/api/upload',
valid_extensions : ['md','csv','css', 'txt'],
params: {
dummy_name: p
},
onComplete: function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
/* $scope.nameString = uploadedFileList.join(',');
$scope.$apply();*/
},
onCancel: function() {
console.log('no file selected');
}
});
This is my controller
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true == settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )
this is my ajax file upload function

Using JQuery when and deferred returning undefined still

I'm new to using $.when and $.Deferred(), and I can't seem to get them to work
What I'm trying to do is run a few functions, and when they've all finished trigger a final function
Here are a couple of options I've tried
Option 1 - Returning d1.getRating is not a function (this is a function further up in the script) following docs from JQuery as I understood them
// Set Deferred
var d1 = $.Deferred();
// Return movie information
if (idResp[0].type === "movie") {
// Output Slug
traktSlug = 'movies/' + idResp[0].movie.ids.slug;
// Output
$.when(d1).done(function (ratingValue) {
console.log('Rating Is: ' + ratingValue);
outputIMDb(showCheckIn, traktSlug, ratingValue);
});
// Get Rating
d1.getRating(idResp[0].type, idResp[0].movie.ids.trakt);
}
Option 2 - Returning ratingValue is undefined
// Return movie information
if (idResp[0].type === "movie") {
// Output Slug
traktSlug = 'movies/' + idResp[0].movie.ids.slug;
// Output
$.when(getRating(idResp[0].type, idResp[0].movie.ids.trakt)).done(function (ratingValue) {
console.log('Rating Is: ' + ratingValue);
outputIMDb(showCheckIn, traktSlug, ratingValue);
});
}
Any suggestions or a nudge in the right direction would be much appreciated
Full source code can be viewed on GitHub
UPDATE
I realised after reading the JQuery docs again that resolve() is not the name of a generic function, so I modified my code, but I'm still getting ratingValue is undefined back
Updated Option 1 Code
// Set Deferred
var d1 = $.Deferred();
// Return movie information
if (idResp[0].type === "movie") {
// Output Slug
var traktSlug = 'movies/' + idResp[0].movie.ids.slug;
// Output Div
$.when(d1).done(function(ratingValue) {
console.log('Rating Is: ' + ratingValue);
outputIMDb(1, traktSlug, ratingValue);
});
// Get Rating
d1.resolve(getRating(idResp[0].type, idResp[0].movie.ids.trakt));
}
UPDATE 2
Sorry, my apologies for not including the getRating function. As follows
// Get Rating
function getRating(type, id, season = 0, episode =0) {
var slugType = "";
switch (type) {
case "movie":
slugType = "movies";
break;
default:
slugType = "movies";
break;
}
var request = new XMLHttpRequest();
request.open('GET', 'https://api.trakt.tv/' + slugType + '/' + id + '/ratings');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('trakt-api-version', '2');
request.setRequestHeader('trakt-api-key', APP_KEY);
request.onreadystatechange = function () {
if (this.readyState === 4) {
// Get Response and put in array
var ratingsResp = JSON.parse(this.responseText);
// Return Rating
return Math.round(ratingsResp.rating * 10);
} else {
return 0;
}
};
request.send();
}
The main thing to do is to write getRating() to return a promise. You could promisify XMLHttpRequest() but it's much easier to use jQuery.ajax().
Here it is, based on the original code on GitHub :
function getRating(type, id, season=0, episode=0) { // mmm, formal defaults - odd for browser-based javascript.
var slugType;
switch(type) {
case 'movie':
slugType = 'movies';
break;
default:
slugType = 'movies';
}
return $.ajax({
url: 'https://api.trakt.tv/' + slugType + '/' + id + '/ratings',
headers: {
'Content-Type': 'application/json',
'trakt-api-version': '2',
'trakt-api-key': APP_KEY
},
dataType: 'json'
}).then(function(response) {
return Math.round(response.rating * 10);
}).then(null, function(xhr, textMessage, errorThrown) {
console.error('getRating error: ', textMessage);
return $.when(0); // error recovery.
});
}
Then, use jQuery.ajax() in the main routine too :
chrome.storage.local.get('access_token', function(result) {
var ACC_TOK = result.access_token;
if (ACC_TOK && typeof ACC_TOK !== undefined) {
if (tabURL.includes('imdb.com')) {
$.ajax({
url: 'https://api.trakt.tv/search/imdb/' + tabURL.match(/tt\d{7}/),
headers: {
'Content-Type': 'application/json',
'trakt-api-version': '2',
'trakt-api-key': APP_KEY
},
dataType: 'json'
}).then(function(idResp) {
if(idResp[0].type === 'movie') {
return getRating(idResp[0].type, idResp[0].movie.ids.trakt).then(function(ratingValue) {
console.log('Rating Is: ' + ratingValue);
outputIMDb(1, 'movies/' + idResp[0].movie.ids.slug, ratingValue);
});
} else {
console.log("Type: " + idResp.type);
}
}).fail(function(xhr, textMessage, errorThrown) {
console.error(textMessage);
});
}
}
});
Note that because jQuery.ajax() returns a promise, there's no need to generate/resolve your own jQuery.Deferred()s.
Code above may not be 100% correct but should go a considerable distance to a working solution.

How can I recursively use phantomjs netlog.js to catch all url responses with ".js" and output the responses?

I have currently edited the netlog.js code to what is shown below:
"use strict";
var page = require('webpage').create(),
system = require('system'),
address;
var resUrl;
if (system.args.length === 1) {
console.log('Usage: netlog.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];
page.onResourceRequested = function (req) {
console.log('requested: ' + JSON.stringify(req, undefined, 4));
};
page.onResourceReceived = function (res) {
resUrl = res["url"]
if (resUrl.indexOf(".js") !== -1){
console.log('\nJS Call URL:' + resUrl);
var page2 = require('webpage').create(), address2 = resUrl;
page2.onResourceRequested = function (req2){
console.log('\tLevel 2 requested: ' + JSON.stringify(req2, undefined, 4));
};
page2.onResouceReceived = function (req2){
console.log('\t Level 2 URL:' + req2["url"]);
};
}
else{
console.log('URL:' + resUrl);
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
phantom.exit();
});
}
However, it only outputs 1 Level of URL responses. I would like it to re-run netlog.js on those URLs with .js as that is what I am trying to do with the if (resUrl.indexOf(".js") !== -1) onwards piece of code. I cannot understand why a second webpage instance will not be created, and be able to re-run the code.

Ajax File Upload Not Working for IE8

I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).
I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.
The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?
Here is my code:
//Uploading a file
$("#uploaded_file").change(function() {
var filename = $(this).val();
if(isAcceptable(filename)) {
$.ajaxFileUpload
(
{
type: "POST",
url:'GenerateServlet',
secureuri:false,
fileElementId:'uploaded_file',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
fillTemplate(data);
}
}
)
}
else if(filename.length > 0){
$("#uploaded_file").val("");
alert("Invalid File! Please select another file")
}
});
$("#upload_link").click(function() {
document.getElementById('uploaded_file').click();
return false;
});
Here is the upload function:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
Console.log(form);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})
That is a typical Microsoft security measure (e.g. to stop automated uploads).
That means you have to originate an upload from an actual user-pressed button click.
Style the button to make it look like a link instead.

Categories