Ajax Json problems with Jquery in Firefox - javascript

I am experiencing some troubles using ajax in my jQuery call in order to produce a json response. Basically I am trying to get all the images in a specific directory. Below is my jQuery code, and this works fine for directories with less than about 50 images, but once the number of images is greater than that, Firefox will just abort the request. This works fine in Safari, Chrome, IE. Either they are doing something wrong and Firefox is doing it right, and I am making an error, or this is one of the rare times when Firefox is the culprit. I have tried $.getJSON and disabling caching of the ajax requests, but that does not seem to work either. Any help will be greatly appreciated and thanks in advance.
var activeRequest = false;
var error = "The system could not read the directory at this time.";
var current = this.location['href'];
var filesCache = {};
function addFile(list, varToAdd, path, id){
if (typeof varToAdd != 'undefined' && varToAdd != null ){
var imagePath = path;
var srcPath = path+"/"+varToAdd['file'];
imagePath = "/cms/images/thumbs/"+imagePath+varToAdd['file'];
var filename = varToAdd['file'];
if(filename.length >18){
filename = filename.substr(0, 15)+"...";
}
var fileInfo = '<li id ="'+varToAdd['file'].replace('.', '')+'">';
fileInfo += '<a class = "thumb" href="'+srcPath+'" target="_blank"><img src="'+srcPath+'" width="'+varToAdd['width']+'" height="'+varToAdd['height']+'" alt="'+varToAdd['file']+'" /></a>';
fileInfo += '<ul class="fileInfo"><li title="'+varToAdd['file']+'">'+filename+'</li><li>'+varToAdd['dims']+'px</li><li>'+varToAdd['size']+'kb</li></ul>';
fileInfo += '</li>';
list.append(fileInfo);
delete fileInfo;
}
else
return false;
}
function lookupFiles(path){
var cleanPath = decodeURIComponent(path);
cleanPath += "/";
var urlLookUp = '/cms/images/lookup/file/?path='+encodeURIComponent(cleanPath);
var loader = $(".folder-contents .header");
$.ajaxSetup({
cache: false
});
var ajaxRequest = $.ajax({
type: 'GET',
url: urlLookUp,
data: path,
dataType: 'json',
beforeSend: function (request) {
if(!activeRequest)
loader.addClass('loading');
else
return false;
},
error: function(XMLHttpRequest, textStatus, errorThrown){
loader.addClass('error').removeClass('loading');
alert(error);
},
success: function(response, status, XMLHttpRequest) {
list = $(".folder-contents > ul.files");
if(typeof response != 'undefined' && response != null){
if(status == 'success' && (typeof response.files != 'undefined' && response.count > 0)){
list.empty();
$.each((response.files), function(index, value) {
addFile(list, value, path, response.searchTerm);
});
//list.append('</ul>');
}
else if (status == 'success' && (typeof response.files != 'undefined' && response.count == 0)){
list.empty();
list.append('<li class = "noresults">There are no images in this folder</li>');
}
else{
formLabel.addClass('error').removeClass('loading');
alert('Error');
}
}
loader.removeClass('loading');
}
});
/*
var json = $.getJSON( urlLookUp+"format=json&jsoncallback=?", function ( data ) {
console.log( data );
} );
*/
}
$(document).ready(function() {
$("a.directory").live('click',function(ev){
ev.preventDefault();
if($(this).hasClass('open')){
$(this).addClass('empty').removeClass('open').html('-');
lookup($(this).attr("title"));
}
else if($(this).hasClass('close')){
$(this).addClass('open').removeClass('close').html('+');
$(this).parent().find('ul').remove();
}
});
$("a.folder").live('click',function(ev){
ev.preventDefault();
lookupFiles($(this).attr("title"));
});
$(".files li").live('click', function(ev){
ev.preventDefault();
// send ckeditor back what image was selected - url from jquery selector & callBack from the view
var fileUrl = $(this).find('a').attr("href");
var callBack = window.CKEditorFuncName;
window.opener.CKEDITOR.tools.callFunction(callBack, fileUrl);
window.close();
});
});

Related

How to find out why some files won't upload?

Using the code below, I can successfully upload an xlsx file without any issues, but when I try to upload a csv version of the same file it never hits the controller. So I tried other csv files and some of them work fine and others don't hit the controller.
No errors are raised so I don't really know what to do to troubleshoot this further. I'm not even sure how to isolate whether the issue is happening after asp.net gets the request but before it hits the controller, or whether it's before it even gets posted. Any suggestions on what I can look into next?
Html:
<div>
<input type="file" name="file" id="uploadFile" />
</div>
JavaScript:
$('#uploadFile').on('change', function (e) {
var files = e.target.files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++)
data.append("file" + x, files[x]);
$.ajax({
type: "POST",
url: '/Home/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (result) {
if (result)
alert('File uploaded.');
else
alert('Error uploading file :(');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
} else {
alert("This browser doesn't support HTML5 file uploads :(");
}
}
});
Controller:
[HttpPost]
public JsonResult UploadFile()
{
try
{
if(Request.Files.Count == 0)
throw new ArgumentException("No file to upload!");
var fileContent = Request.Files[0];
if(fileContent != null && fileContent.ContentLength > 0)
{
Session["ImportFileId"] = ImportFiles.Save(fileContent.InputStream);
return Json(true);
}
else
return Json(false);
}
catch(Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(false);
}
}

Why don't work my function xmlParser(). Help me please

Hello everybody. I have a problem with my code. I use the jquery framework. When I want to call $.ajax(requestOptions), function xmlParser(xml) don't working.
I try to find a resolve this problem, but I can't nothing find.
$(document).ready(function () {
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser //Calling function
};
function xmlParser(xml) {
$("#load").fadeOut();
$(xml).find("Valute").each(function() {
$("#outputListValutes").append(
"<option value=" + $(this).find("CharCode").text() + ">" + $(this).find("CharCode").text() + "</option>");
});
};
$.ajax(requestOptions);
$("#clear").click(function() {
var sumValue = document.getElementById("sum").value = "";
var resValue = document.getElementById("result").value = "";
});
$("#convert").click(function(xml) {
//var selectCurrency = $("#inputListCurrency").val();
//findData(xml);
}(requestOptions));
function findData(xml) {
var decimalOnly = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/;
try{
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if(value == "") throw new Error("Empty value");
else if(!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if(value < 0) throw new Error("Value isn't to be below zero");
else if(isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function() {
if(shortName == $(this).find("CharCode").text()) {
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch(e) {
alert(e);
}
}
});
change the success parameter of the request to use the xmlParser function (forgot () ):
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser(data) //Calling function
};
I found the solution this promlem. I am happy.
var courseFilePath = "xml/Course_Currency_02-07-2014.xml";
var listCurrency = [];
function insertOptions(){
for (var i = 0; i < listCurrency.length; ++i){
$("#outputListCurrency").append(
"<option value=" + listCurrency[i] + ">" + listCurrency[i] + "</option>");
}
}
function xmlParser(xml){
$("#load").fadeOut();
$(xml).find("Valute").each(function(){
var value = $(this).find("CharCode").text();
listCurrency.push(value);
});
listCurrency.sort();
};
function findData(xml){
var decimalOnly = /^\s*-?[0-9]\d*(\.\d{1,2})?\s*$/;
try {
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if (value == "") throw new Error("Empty value");
else if (!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if (value < 0) throw new Error("Value isn't to be below zero");
else if (isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function(){
if (shortName == $(this).find("CharCode").text()){
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch (e){
alert(e);
}
}
$(document).ready(function(){
$.ajax({
type: "GET", //The method of sending for data
url: courseFilePath, //It is reference on xml file
dataType: "xml", //The type of data
success: function(xml){
xmlParser(xml);
insertOptions();
}
});
//insertOptions();
$("#clear").click(function() {
document.getElementById("sum").value = "";
document.getElementById("result").value = "";
});
$("#convert").click(function() {
var selectCurrency = $("#inputListCurrency").val();
$.get(courseFilePath, findData, "xml");
});
});

Ajax call at last

in my jquery function i have two ajax call with serverside method and its working fine,
problem is ajax call at last amd after ajax line of code run but this lines of code depand on
function Rbook(b) {
var one = $(b).attr("data-oneislcc");
var two = $(b).attr("data-twoislcc");
var trip1 = $(b).attr("data-oneinfo");
var trip2 = $(b).attr("data-twoinfo");
var owflt = "l";
var inflt = 'r';
var owjdata = $(b).attr("data-ow");
var iwjdata = $(b).attr("data-iw");
var llccreturn, rlccreturn;
var lres, rres;
$("#fadeing").css("display", "block");
$("#fade").css("display", "block").css("height", $(document).height / 2);
if (one == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip1 + "','flt':'" + owflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
lres = response.d;
if (response.d == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
llccreturn = owlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
llccreturn = ownonlcc(owjdata);
}
if (two == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
if (rres == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
rlccreturn = iwlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
rlccreturn = iwnonlcc(iwjdata);
}
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}}
var owlcc = function (jdata, oldfare) {
//Some Calulation
retrun 'farechange';
}
var ownonlcc = function (jdata) { //Some Calulation
retrun 'nofarechange'}
var iwlcc = function (jdata, oldfare) { //Some Calulation
return 'farechange'}
var iwnonlcc = function (jdata) { retrun 'nofarechange'}
if run this code its run this line of code then rest so condition not validate
i dont know where i m doing wrong
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
It looks like you don't understand asynchronous javascript. When you do an ajax call, it sends the request, then continues running the code and only later runs the success handler. Otherwise, it wouldn't be able to do anything at all until the response came back, since javascript is single-threaded.
The Rbook function does the following: First, get lots of information from the DOM; then, send some ajax requests (and set handlers to run when the response comes back); then possibly make some changes to the DOM, depending on the values of llccreturn and rlccreturn (but they're still undefined). It's only when the ajax response comes back and the success handler is run that these variables are set, but by then it's too late.
If you want to run some code after hearing the ajax response, put it in the success handler (or call it from the success handler). In this case, it's further complicated by the fact that you don't want to run the code until both ajax responses have arrived, and also by the fact that you might just run iwnonlcc or ownonlcc synchronously instead of doing an ajax call. I'd say the easiest way to fix this would be to wrap the code you want to run at the end inside a function and an if block like this:
function dataWasReceived() {
if (llccreturn !== undefined && rlccreturn !== undefined) {
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
}
}
Then, every time you set the value of llccreturn or rlccreturn, call this function:
rlccreturn = iwlcc(data[0], data[1])
dataWasReceived();
and:
rlccreturn = iwnonlcc(iwjdata);
dataWasReceived();
etc.
I'm also concerned about this line (appears twice):
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
You probably wanted to apply the argument as an object, not a JSON string representing that object:
data: {ALcode: trip2, flt: inflt},
(Incidentally, the string you gave wasn't valid JSON anyway, since it used ' instead of ".)

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.

confirm box from a controller

Have a requirement to call the confirm box in JSP, following is my code in controller,
if(!(nesting)){
bla.add("Do you want to Load anyway?");
context.getFlowScope().put("bla", bla);
context.getFlowScope().put("uldSelector", uldSelector);
return;
}
h = uloService.processDomBatch(histInfo, dl, items);
the above will add the error to flowscope and returns, but, I wantto call a confirm box instead and then depending yes/no, I should continue through...
is there a way to do this?..any help is greatly appreciated!
Thank you!
Yes #user1609085 you can do it with AJAX and JavaScript something like this:
function question(val) {
var chk = document.forms[0].chk
var box = valBox(chk)
var resp = confirm("Do you want to Load anyway?")
if(resp) {
if(box == null) { return }
else {
$.ajax({
type: 'GET',
url: 'controllerMethod?action=controllerMethod',
data: 'uldSelector='+val,
cache: false,
success: function(data) {
alert("histInfo")
},
error: function(data) {
alert('ERROR: ' + data)
}
})
}
}
}
function valBox(b) {
var cnt = -1
for(var i = b.length-1; i > -1; i--) {
if(b[i].checked) {
cnt = i
i = -1
}
}
if(cnt > -1) return b[cnt].value
else return null
}
And you box only put onclick="question(this.value)"
I hope help you :)

Categories