unable to download excel file using ajax jquery - javascript

I have
$.ajax({
url: 'service url',
type: 'POST',
async : true,
contentType: false,
processData: false,
cache: false,
success: function(data){
},
error: function(err){}
});
I can see the file in my Content-disposition in the chrome inspector and the response shows an encrypted value in the inspector.
However, no file is being downloaded. What is missing here?

Content-Disposition will influence what happens when you load a resource in a browser window.
It doesn't do anything when you are handling the response manually with JavaScript.
If you want to trigger a download from that point, you'd need to handle the response, generate a data: scheme URI and set location to it.
It would be simpler to submit a form to the destination URL in the first place (unless you don't need POST in which case you can just set location to it).

Related

Ajax post doesnt work with contentType

I've got an editor that allows editing some text that has to be sent to my backend via Ajax Post request. This works fine so far with the only problem being that when I load the Text from the backend after saving it the encoding seems messed up (line breaks are not interpreted correctly). I tried setting the contentType flag in my Ajax request to contentType: "text/plain;charset=UTF-8" but after this change I'm getting this exception in my springboot controller responsible for the request url:
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'editorText' is not present
Anyone got an idea on how this flag may mess up the call ? (Before I've just had the flag set to contentType: false).
Complete Ajax call:
$.ajax({
url: "/someUrl",
type: "POST",
data: new FormData($("#uploadForm")[0]),
contentType: "text/plain;charset=UTF-8",
processData: false,
cache: false,
...
});

Cross Origin in ajax not working for .properties file in IOS (10.3.1)

I used i18n plugin for load *.properties file for translation and its working fine on android platform but same library not working on IOS 10.3.1. It gives me below error:
i have done some changes in i18n library but still its not working.
function loadAndParseFile(filename, settings) {
$.ajax({
url: filename,
async: false,
cache: settings.cache,
crossDomain: true,
jsonpCallback: 'callback',
contentType: 'text/plain;charset=' + settings.encoding,
dataType: 'text',
success: function (data, status) {
parseData(data, settings.mode);
}
});
}
In above code:
i have been added Cross-Domain 'true' and datatype 'text'.. when i changed datatype 'text' to 'jsonp' its working but it gives .properties file error.
Please check below error..
That means. file is loaded, but inner data format is different.
If you are using now JSONP instead of text, the file will be loaded as javascript code, so if contents are not valid javascript code it will fail.
Surround data with a global variable assignation or a function call:
window.variable = "_DATA_"; // or
functionName("_DATA_");
If _DATA_ are JSON format, then you don't need surround with quotes, otherwise you'll need to use "_DATA_" because without quotes it will not be valid javascript syntax.
add this line to your ajax parameters
xhrFields: {
withCredentials: true
}

image data response from jquery .ajax into new ajax call?

I'm trying to chain together the ImageOptim API with the OCR.space API.
Both great API's by the way, I highly recommend them! The issue at hand though is that the OCR api does not accept images over 1 mb or 2600x2600 px in the free tier and thus many sources will need to be optimised before being sent.
Im running this jQuery ajax call to ImageOptim from a cordova wrapped html file:
var compress = function(image) {
console.log("starting compress");
$.ajax({
url: "https://im2.io/eX4mp1E4pI/2600x2600,quality=low",
method: "POST",
data: {
file: image
},
processData: false,
contentType: false,
crossDomain: true
}).done(function(res) {
window.compressedImg = res;
formData.append("file", res);
runOCR();
}).fail(function(jqXHR, textStatus) {
console.log("Request failed: " + textStatus);
});
};
Please note:
this (in my experience), will fail in the browser due to cross domain calls being blocked in the browser but not from cordova.
OCR compatible compression not added in yet (but would require a file size as well as dimension argument)
The output from this call is a raw png as a string, i.e. what you get when you open a .png file in a text editor. I've tried loads of ways to handle this but cannot understand how to use this data in the next ajax call (below), does it need to be saved to disk and then uploaded, if so - how? (because I tried writing it to localstorage but it would still be treated as a string).
The OCR.space call;
var formData = new FormData();
formData.append("language", "MYLANGUAGE");
formData.append("apikey", "MYAPIKEY");
formData.append("isOverlayRequired", false);
function runOCR2() {
jQuery.ajax({
url: 'https://api.ocr.space/parse/image',
data: formData,
dataType: 'form/multipart',
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(ocrParsedResult) {
console.log(ocrParsedResult);
}
});
}
Please note; Vars are not set here but I keep them together in this question for clarity.
The response from this call is:
responseText: "{\"ParsedResults\":null,\"OCRExitCode\":99,\"IsErroredOnProcessing\":true,\"ErrorMessage\":\"No file uploaded or UR…"
i.e. the call works but the image parameter is not a valid image.
Any ideas on how to trea the returned string so that it is readable as an image for the next api call?
Usually when you are uploading files using formData you just pass file reference like
form.append('myfile',$("#fileInput").files[0]) and browser handles the encoding stuff behind the screens .It manually converts file to byte-stream and prepares appropriate boundary to help server distinguish where image begins and ends
but here scenario is different you don't have the file bound to any physical file control instead its created dynamically and you get a bytestream of that .To account for the above fact you need to tell browser explicitly that it's a independent raw binary stuff and should be treated as such
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format.
var blob = new Blob([res], {type : 'image/png'}); //res is the converted image ImageOptim API
var formData = new FormData();
var fileName = 'myimage.png'; //filename that server will see it as
formData.append('anything', blob, fileName);
formData.append("language", "MYLANGUAGE");
formData.append("apikey", "MYAPIKEY");
formData.append("isOverlayRequired", false);
function runOCR2() {
$.ajax({
url: "https://api.ocr.space/parse/image",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(response){alert(response);}
});
}

Is this crossdomain issue in jquery?

I'm not sure if this is crossdomain issue or not. I'm trying to use $.ajax to load file. But some file I get readyState=4 and some file I get readyState=1
This is the path where I run my jasmine test
file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html
And in the code I used jQuery.pyte to require relevant file. But it's stuck at readyState:1 when the code comes to $.ajax
if I do something like this, it returns readyState=4 correctly and print out the content inside SpecRunner.html
$.ajax({url: 'file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html', async: false}).responseText
but if I do something like this, I only get readyState=1 and nothing is returned.
$.ajax({url: 'file:///home/myname/development/path1/path2/src/main/webapp/static/js/core/application/FileThatIWant.js', async: false}).responseText
you should avoid file:// URLs in general, because browsers do not allow them in many different places. Try XAMPP it's a simple to use local webserver, you will definitively need one.
Yes, this is a cross-domain issue. You can solve this problem by forcing jQuery to use crossdomain AJAX (JSONP).
$.ajax({
url: "yoururl",
cache: false,
crossDomain: true,
data: {}, //put your GET parameters here or directly into the url
dataType: "jsonp",
processData: true,
success: function(data, textStatus, jqXHR){
//This will be executed if it worked
},
error: function(data, textStatus, jqXHR){
//This will be executed if it failed
},
timeout: 4000, //You can put any value here
traditional: true,
type: "GET"
});
jQuery will automatically add a callback parameter containing a random string (&callback=XXXXXX).
The target URL needs to output the following:
XXXXX(your_output_encoded_in_JSON);
where XXXXX is the random string. The PHP code to do so is:
echo $_GET["callback"]."(".json_encode($myoutput).");";
Make sure that the PHP (or whatever language you're using) page ONLY outputs that!
If, instead, the page you are querying is not built dynamically, such as an HTML page, you need to add the following options to the $.ajax options object:
jsonp: false,
jsonpCallback: "mycallback",
mimeType: "text/javascript",
Your .html file will contain something like this:
mycallback("<html><head></head><body>TEST PAGE. This is a double quote: \" and I didn't forget to escape it!</body></html>");
This technique is very handy to bypass the strict crossdomain restrictions hardcoded in browsers, but it only supports GET parameters. XMLHTTPRequest v2 supports cross-domain requests, but we won't be able to assume that all users have a XHRv2-compatible browser before at least 2016.
http://caniuse.com/xhr2

GAE blobstore url error: GET not supported

I am having trouble with the google app engine blob store. I am running in the development environment (ie local on my machine.)
Heres what i am doing...
once the form pops up i call into a servlet to generate the URL like this
String url = blobstoreService.createUploadUrl("test/joi");
once i have that i save it in my java scrip and then once the user submits the form i am doing this
$.ajax({ url: self.url,
type: "POST",
//crossDomain: true,
dataType: "jsonp",
//dataType: "multipart/form-data",
success:
function(response, textStatus, jqXHR)
{
alert("saved.");
}
});
}
however, when i do that i get the following exception
GET 405 (HTTP method GET is not supported by this URL) jquery.js:4
i am really struggling with this and any help would be greatly appreciated!
Apart from any other issues, the blobstore expects file uploads in multipart form format; you're attempting to post to it using jquery. If you want to do the post in javascript, you will need to format the body of the POST request appropriately.

Categories