WP7 Phonegap download xml from cross domain url using YQL - windows-phone-7

the following code works on firefox,chrome and IE9 on my PC.
But the callback function doesn't return when I run it in WP7 device using phonegap.
function downloadXML(
$.ajax({
async: true,
cache: false,
type: 'GET',
dataType: "xml",
crossDomain: true,
url: yql_url('http://some-cross-domain-url'),
error:function(xhr, status, errorThrown){
navigator.notification.alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
},
success: function (xml) {
navigator.notification.alert("successful");
}
});
}
yql_url = function(source_url) {
return "http://query.yahooapis.com/v1/public/yql?q=select * from xml where url=\"" + source_url + "\"";
}
Does anyone point out what EXTRA has to be done to make it run on WP7 ? THX
OR let me re-frame the question,
Can someone give me a code snippet which works on WP7 with phonegap that can fetch XML from a cross domain URL.
I have been trying a lot to make it run on WP7 without any success :(

You need to set the following to true:
$.support.cors
and
$.mobile.allowCrossDomainPages
Check the jQuery Mobile Docs

Seems to be similar to Phonegap for Windows Phone jQuery ajax callback not executed
Try the following: comment everything in phonegap-1.3.0.js starting from line 3551 to the end of the file
//(function(win,doc){
//
// doc.addEventListener("DOMContentLoaded",function()
// {
// ......
// if(!docDomain || docDomain.length == 0)
// {
// //console.log("adding our own Local XHR shim ");
// var aliasXHR = win.XMLHttpRequest;
//
// win.XMLHttpRequest = function(){};
//
// var UNSENT = 0;
// ......
//
//
//})(window,document);
PS. For XSS on WP7 you also need the following flag for jQuery $.support.cors = true;
EDIT
PhoneGap 1.4.0rc1 is commited
https://github.com/purplecabbage/callback-windows-phone
Changes include fixes for XHR to local files, + fixes to allow jQM single/multipage apps function correctly.

Related

Unable to get value of the property 'content': object is null or undefined

I get this error every time i compile my PhoneGap 2.9.0 project. I copied "www" folder into my Microsoft Visual Studio 2010 Codrova Project because iw anted to test the program on WP 7(I've already tested it on Android and iOS emulators and devices).
Error:["Unable to get value of the property 'content': object is null or undefined file:x-wmapp1:\/app\/www\/index.html Line:1","DebugConsole380383071"]
As far as i've found out, this bug is fixed only if i delete cordova.js include in my index.html file. I'm hoping that fixing this bag will solve the problem of file downloading in my program, because it's not working in WP 7 now. Here is the function for file downloading:
function fileDownload(fileName, finalName) {
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry){
var sPath = fileEntry.fullPath.replace("dummy.html","") + "Appname/Cachefolded";
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
finalName,
sPath + finalName,
function(theFile) {},
function(error) {}
);
},
null);
},
null
);
};
In addition, i'm using few PhoneGap API's:
* Device
* Connection
* FileSystem
* LocalStorage
Data is downloaded via Ajax like this:
$.ajax({
url: base + "user.php?imei=" + imei,
type: 'POST',
dataType:"json",
cache: false,
success: function(data) {
fileDownload(data.img, "avatar.jpg");
}
});
I'll publish all nessesary code if you are interested in a specific part. Don't wanna post it here to keep my question readable. Thanks for any help in advance.
P.S. Line 1 of the code is:
<!DOCTYPE html>

Insert to SQL Server database from jquery mobile application using a server side script (coldfusion)

I've built a jQuery mobile app that gets its content from an external SQL server database via JSON and a server side script (ColdFusion CFC) that interfaces with the database. This app has been packaged as a native app using PhoneGap. I need to enable the jQuery mobile app to be able to write back to the external SQL server db.
Im new to mobile development but have several years of server side development using ColdFusion. I am guessing that the best way to do this is for the mobile app to send the results of the submitted form elements to a server side script for processing. I dont want the native app to send this "as a web page" but rather stay in the app to do it (via AJax I assume).
My server side script will be written in ColdFusion and handles input sanitation and database interaction...I just need to figure out what is the best way to submit from my jQuery app to the server side script, but do it while staying inside of my native application.
I'm pretty much doing the same thing. Server side Coldfuison8/MySQL, front end Jquery Mobile (, requireJS) with all forms submits routed through AJAX to avoid reloading a page.
I'm using a generic form submitter in my controller.js, which looks like this:
var ajaxFormSubmit =
function ( form, service, formdata, targetUrl, successHandler, dataHandler, errorHandler ){
$.ajax({
async: false,
type: "post",
url: service,
data: formdata,
dataType: "json",
success: function( objResponse ){
if (objResponse.SUCCESS == true ){
// alert("success!");
// this passes the response object to the success handler
// in case data needs to be ... handled.
dataHandler == "yes" ? successHandler( objResponse ) : successHandler();
} else {
// alert("AJAX failed!");
if ( errorHandler != "" ){
errorHandler();
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert("something else failed");
showErrors( [["server-request-error", "server_error"]], XMLHttpRequest, textStatus, errorThrown );
}
});
}
I'm returning results as a response object, which will contain Success = True/false, data (if there is any) and Error = error message.
A function call will look like this:
// the form
var form = $(this).closest('form'),
// trigger for cfcase inside my cfc
switcher = form.find('input[name="form_submitted"]').val(),
// which cfc to call
service = "../cfcs/form_handler_abc.cfc",
// the method in your cfc you are calling (validation/commit to database)
method = "process",
returnformat = "JSON",
// not using
targetUrl = "",
// serialized form plus any value you need to pass along
formdata = form.serialize()+"&method="+method+"&returnformat="+returnformat,
// specific error routine to run
errorHandler = function(){
// in my case, reset the whole form
cleanUp( $('form:jqmData(search="regular")'), "results" )
},
// inside my success handler I'm switching depending on submitted form
// `response` will be the AJAX object.response = whatever you send back from the server
successHandler = function( response ) {
switch (switcher) {
// form A - this is for a search form handling the results
case "getProducts":
// clean up
$('.ajaxContainer, .pagination').addClass('fade out').remove();
// AJAX data received
var makeUp = response.DATA;
// don't forget to trigger create to enhance all JQM elements you are sending
$('.results').append( makeUp ).trigger('create');
// redraw - will fire JQM updatelayout
$(window).trigger('dimensionchange');
// will set bindings on new elements
bindResults( $('.results').closest('div:jqmData(role="page")') );
break;
case "A":
// do sth else
break;
case "B":
// do sth else
break;
}
};
// now pass all of the above to the ajaxFormsubmit
ajaxFormSubmit( form, service, formdata, targetUrl, successHandler, handleData, errorHandler);
I have a number of CFCs, each with a main cfswitch and cfcase for each submitted form. I have built my backend using this sample. Took a while to get going, but now it's running more or less smooth.
Let me know if you have some questions regarding the above.

Error handling when downloading a file from a servlet

I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)

Clear IE cache when using AJAX without a cache busting querystring, but using http response header

I'm having the classic IE-caches-everything-in-Ajax issue. I have a bit of data that refreshes every minute.
Having researched the forums the solutions boil down to these options (http://stackoverflow.com/questions/5997857/grails-best-way-to-send-cache-headers-with-every-ajax-call):
add a cache-busting token to the query string (like ?time=[timestamp])
send a HTTP response header that specifically forbids IE to cache the request
use an ajax POST instead of a GET
Unfortunately the obvious querysting or "cache: false" setting will not work for me as the updated data file is hosted on Akamai Netstorage and cannot accept querystrings. I don't want to use POST either.
What I want to do is try send an HTTP response header that specifically forbids IE to cache the request or if anyone else knows another cache busting solution??
Does anyone know how this might be done? Any help would be much appreciated.
Here is my code:
(function ($) {
var timer = 0;
var Browser = {
Version: function () {
var version = 999;
if (navigator.appVersion.indexOf("MSIE") != -1) version = parseFloat(navigator.appVersion.split("MSIE")[1]);
return version;
}
}
$.fn.serviceboard = function (options) {
var settings = { "refresh": 60};
return this.each(function () {
if (options) $.extend(settings, options);
var obj = $(this);
GetLatesData(obj, settings.refresh);
if (settings.refresh > 9 && Browser.Version() > 6) {
timer = setInterval(function () { GetLatestData(obj, settings.refresh) }, settings.refresh * 1000);
}
});
};
function GetLatestData(obj, refresh) {
var _url = "/path/updated-data.htm";
$.ajax({
url: _url,
dataType: "html",
complete: function () {},
success: function (data) {
obj.empty().append(data);
}
}
});
}
})(jQuery);
Add a random number to the GET request so that IE will not identify it as "the same" in its cache. This number could be a timestamp:
new Date().getTime()
EDIT perhaps make the requested url:
var _url = "/path/updated-data.htm?" + new Date().getTime()
This shouldn't cause any errors I believe.
EDIT2 Sorry I just read your post a bit better and saw that this is not an option for you.
You say "is hosted on Akamai and cannot accept querystrings" but why not?
I've never heard of a page that won't accept an additional: "?blabla", even when it's html.
This was driving me crazy. I tried many cache busting techniques and setting cache headers. So many of these either did not work or were wild goose chases. The only solution I found which tested to work correctly was setting:
Header Pragma: no-cache
I hope it saves others with IE headaches.

AJax Testing - Add a delay

I'm trying to run some tests on some Ajax code we have written, now obviously when tested locally it runs very fast and is great. I need to enforce a delay of 3 seconds so that I can see that the loader is being displayed and the user experiance is good enough.
I have tried the following but recieve the error "Useless settimeout" any other suggestions to achieve this? Any browser plugins?
$('#formAddPost').submit(function() {
//Load the values and check them
var title = $(this).find('#Title');
var description = $(this).find('#Description');
var catId = $(this).find('#Categories');
if (ValidateField(title) == false || ValidateField(description) == false) {
$('.error-message').show();
return false;
}
$('.error-message').hide();
//Show the loading icon
$('.add-post').hide();
$('.add-post-loader').show();
//Temp for testing - allows the showing to the loader icon
setTimeout(MakeAJAXCall(title.val(), catId.val(), description.val()), 1500);
return false;
});
function MakeAJAXCall(title, catId, description) {
$.ajax({
url: "/Message/CreatePost/",
cache: false,
type: "POST",
data: ("title=" + title + "&description=" + description + "&categories=" + catId + "&ajax=1?"),
dataType: "html",
success: function(msg) {
$('#TableMessageList').replaceWith(msg);
$('.add-post-loader').hide();
$('.add-post').show();
}
});
}
As you're testing your page for a delay in the server response, can you put a delay in the server side code instead of client side?
You might be able to do that using fiddler.
The examples scripts include some samples that pause the response.
Would this tool from jsFiddle.net be helpful?
Echo Javascript file and XHR requests
http://doc.jsfiddle.net/use/echo.html

Resources