JSON file not loading on Chrome or Internet Exploror - jquery-mobile

I'm creating a jQuery web mobile application. It work fine on Firefox, but when running on Internet Explorer or Google Chrome it shows error: json file not load
$.getJSON('menu.json', function(menu) {
var processedTemplate = $.mustache($("#menuTemplate").html(), menu.menu);
$list.html(processedTemplate);
});
// .error(function(jqXHR, textStatus, errorThrown) {
// alert("error " + textStatus + " incoming Text " + jqXHR.responseText);
// });
.error(function() { alert("Sorry can't load JSON file locally in this browser!")});

Related

Cordova file-transfer plugin not working in simulator

I'm trying to get the example code for the file-transfer plugin working, it's taken straight from the Cordova docs:
function downloadFile2() {
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
// Parameters passed to getFile create a new file or return the file if it already exists.
fs.root.getFile('downloaded-image.png', { create: true, exclusive: false }, function (fileEntry) {
download2(fileEntry, url, true);
}, function () { logError('Error creating file'); });
}, function () { logError('Error creating fs'); });
}
function download2(fileEntry, uri, readBinaryData) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
console.log('Downloading ' + uri + ' to ' + fileURL);
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("Successful download...");
console.log("download complete: " + entry.toURL());
if (false && readBinaryData) {
// Read the file...
readBinaryFile(entry);
}
else {
// Or just display it.
displayImageByFileURL(entry);
}
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
function displayImageByFileURL(fileEntry) {
var elem = document.getElementById('imageElement');
elem.src = fileEntry.toURL();
}
I'm using the latest versions of the file-transfer and file plugins (1.7.1/6.0.1). I have added the domain to the Content-Security-Policy element as mentioned in the example:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: http://cordova.apache.org https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
When I run it up in the simulator (Android/iOS) from VS2017 the download fails silently. Neither the success or error callbacks are called, and it doesn't appear to generate a network request. The console log is as follows:
file system open: http_localhost_4400:Temporary
Downloading http://cordova.apache.org/static/img/cordova_bot.png to filesystem:http://localhost:4400/temporary/downloaded-image.png
That filesystem URL looked a bit odd to me, so I have tried other variants such as the full file path, using persistent storage instead of temporary, using 'cdvfile://localhost/persistent/downloaded-image.png', all with the same result. I'm at a loss as to how I can debug this further and wondering if I've missed something really obvious, so any advice appreciated...
Edit
I tried running it again today, and a dialog pooped up in Visual Studio with the message:
There is no handler for the following exec call:
FileTransfer.download("http://cordova.apache.org/static/img/cordova_bot.png", "cdvfile://localhost/persistent/downloaded-image.png", true, 1, null)
I did some more experimenting, including running it up in the VS simulator for Android. For some reason it had trouble connecting to cordova.apache.org (I was also unable to access this site in the browser on the emulator), but downloading a file from github worked correctly....

Open local files in ionic iOS

I'm trying to open an already present .pdf file on iOS [I can see the files in iBooks].
I use Ionic and the file-opener2 Cordova plugin - I use the latest versions of Cordova and the plugin.
This is the code that works perfectly on Android:
$scope.openPDF = function() {
alert("OK");
$cordovaFileOpener2.open(
'/storage/emulated/0/Download/pdf/name.pdf', // Any system location, you CAN'T use your appliaction assets folder
'application/pdf'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
};
Yes, I want to be a local file without having to download it, this is a show off app that won't have internet connection where will be running for just one day. So the files have to be local.
I have no idea how to open the file paths like in Android. Running on iOS 9.3.3., iPad Pro. Also, the device is not jail-broken.
Edit:
Well, now I'm trying to move the files from the app's folder to another one, so I can open it from there. Again, all of the code works on Android.
function openPDF(uri) {
var filePath = cordova.file.applicationDirectory + 'www/pdf/fichas/name.pdf';
alert(filePath);
window.resolveLocalFileSystemURL(filePath, function(entry) {
var fileTransfer = new FileTransfer();
var targetFile = cordova.file.externalDataDirectory + entry.name;
fileTransfer.download(
entry.toURL(),
targetFile,
function(entry) {
console.log("download complete: " + entry.toURL());
console.log("targetFile: " + targetFile);
cordova.plugins.fileOpener2.open(
targetFile,
'application/pdf',
{
error : function(error){ alert('open error ' + JSON.stringify(error)) },
success : function(){ }
}
);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}, function(error){ alert('error resolveLocalFileSystemURI ' + JSON.stringify(error)) });
};
alert(filePath); * returns: file:///var/containers/Bundle/Application/xxxx-xxxx-xxxx-xxxxxxxxxxxxxxx/NAME.app/www/pdf/name.pdf
I don't know where it fails though. I won't open anything.
edit2:
I get a FileTransfer error indeed. "
Could not create path to save dowloaded file.

Phonegap & iOS simulator - cannot save downloaded file

I'm using Phonegap/cordova and writing a Android/iOS app which will download json data from my server and store locally on device for offline usage. On android, this works perfectly. I don't have an iOS device therefore relying on iOS simulator, and it throws me a "could not create target file" type error.
downloadFile:function(path,uri){
var fileTransfer = new FileTransfer();
fileTransfer.download(
encodeURI(path),
app.getStorageLocation()+"files/"+uri,
function(entry) {
console.log("download complete: " + entry.toURL());
app.progressMove();
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false);
}
The getStorageLocation function is:
getStorageLocation:function(){
if(device.platform == 'Android'){
return cordova.file.externalApplicationStorageDirectory;
}
else if(device.platform == 'iOS'){
return cordova.file.documentsDirectory;
}else{
throw new Error('Unsupported platform: '+device.platform);
}
}
On iOS simulator, it does return the Documents directory, but the above fails to write to it. Would this just be a Simulator bug or have I done something wrong?
thanks!
I have created one file named dummy.html under the documents directory. Below is the working code snippet for downloading file. You can log path and see where its pointing. Use safari develop tool iOS simulator for inspecting. I have added file & filetransfer plugin.
function downloadFile() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {
create: true,
exclusive: false
},
function gotFileEntry(fileEntry) {
console.log(fileEntry);
var sPath = fileEntry.nativeURL.replace("dummy.html", "");
console.log(sPath);
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://developer.android.com/assets/images/home/ics-android.png",
sPath + "dummy.png",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
},
fail);
},
fail);
}
Check screenshot-
excellent! got it working.
Additionally found that not all files were problematic. Apple doesn't like custom file types nor file names with "%20" in them. Fixing all the above has worked!

Titanium Studio to Grails imge post

I am trying to POST an image to my grails application and I'm not having much luck.
My titanium code is:
function upload(){
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info(picMedia + " : " +message.value);
Ti.API.info('IN ERROR ' + e.error);
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e){
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST', 'http://localhost:8080/FYP/Profile/appUploader');
// send the data
xhr.send({
media: picMedia,
message: message.value,
});
}
My grails code is as follows:
def appUploader(){
println "MEDAI PARAMS: " + params.media
def f = request.getFile('media') ;
println "HERE: " + f
if (request.getFile(params.media).getOriginalFilename()) {
println "FROM APP: " + request.getFile('myFile').getOriginalFilename()
return
}
}
Im getting error from the mobile app and error on the "if" line in the web app.
What am i doing wrong?
we had the same problem in one of our apps. The difficulty is that titanium is not really able to handle binary files in that case.
We did the following:
create base64 encoded string of the image on client side
post this string to the backend
decode base64 to image again
We analyzed a lot of network traffic and in most cases titanium tries to send the file but due to javascript its alway converted into some kind of ascii and this is not usable by the server side.

Phonegap MobileJQuery AJAX Posts Twice while debugging

Hope there is some out there that can help!,
While debugging a WCF service that a phonegap application connects to it seems to post twice.
When the application runs normally no Break points etc it all works fine and i only receive 1.
It appears to me that ajax reposts itself if no response is returned from the server after a few seconds.
I will need to confirm this threw wireshark but just wanted to know if anyone else has come accross this before.
$.ajax({
type: "POST",
url: ServicePATH ,
data: JSON.stringify({ objs: arrayobj, parm2: var2, parm3: var3, parm4: 1 }),
contentType: "application/json",
dataType: "json",
success: function (data, textStatus, jqXHR) {
CallonSuccess(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error ' + textStatus);
console.log('XMLHttpRequest ' + XMLHttpRequest);
var str = '';
for (prop in XMLHttpRequest) {
str += "prop " + prop + " value :" + XMLHttpRequest[prop] + "\n"; //Concate prop and its value from object
}
console.log(str);
console.log('errorThrown ' + errorThrown);
console.log('passing ' + JSON.stringify({ objs: arrayobj, parm2: var2, parm3: var3, parm4: 1 }));
}
}).done(function () { console.log('Finished ajax'); });
Thanks Lmac
Perhaps no solution (see update below) for you but the same behaviour here.
Without the jquery Mobile framework everything works okay, with the framework embedded it fetches my json file a second time. In Chrome's Console you can see it under Network: GET status 200 and GET status 304 (not modified).
I have the option to throw out jQuery Mobile and I surely will. But would be also interested in knowing what's happening there.
UPDATE:
I had the xmlhttprequest within the $(document).ready(function() { }); It seems as if both jQuery and jQuery Mobile react to that.
If I put the script at the end of the site and make my xmlhttprequest outside the ready-method it fetches my json file only once.

Resources