Ajax request to pages within a windows phone app - windows-phone-7

I am building a windows phone mobile app with phonegap. I need to get some content from a particular page within the application...This is what I have for now:
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject('Msxml2.XMLHTTP');
} catch (err2) {
try {
req = new ActiveXObject('Microsoft.XMLHTTP');
} catch (err3) {
req = false;
}
}
}
return req;
}
var first_req = getXMLHTTPRequest();
var firsturl = '/books/Col.xml';
first_req.open('GET', firsturl, true);
first_req.onreadystatechange = createResponse;
first_req.send(null);
function createResponse()
{
if (first_req.readyState == 4) {
if(first_req.status == 200)
{
navigator.notification.alert(
'sucess',
doNot,
'success',
'Worked'
);
}
else {
navigator.notification.alert(
"request.status = "+first_req.status,
doNot,
'Error',
'Try Again'
);
}
it doesn't work, the else block runs and alerts request.status = 0
Any help would be really appreciated

Related

How can I send a synchronous ajax request to my server in onunload function

I need to send a ajax request to my server before web page close, my send code is below.
SendByAajx = function(msg) {
var response;
var xmlHttpReg;
if(window.XMLHttpRequest){
xmlHttpReg = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Unsupported borwser");
}
if(xmlHttpReg != null) {
xmlHttpReg.open("get", "https://127.0.0.1:57688/test"+'?'+msg, false);
xmlHttpReg.send(null);
if(xmlHttpReg.readyState==4){
if(xmlHttpReg.status == 200) {
var data = JSON.parse(xmlHttpReg.responseText);
if(typeof(data.errorcode) == "number" &&
data.errorcode != 0) {
throw("response error:" + data.errorcode);
}
response = data.result;
} else {
throw new Error("Error");
}
}
}
return response;
}
When I call this function in a button onclick event, it works.
function GetOnClick() {
try{
var result = SendByAajx (“data”);
} catch (e) {
//alert(errorInfo);
}
SetButtonDisabled(false);
}
But when I call this function when the page is unloaded, it doesn't work.
<body onload="javascript:OnLoad();" onunload="javascript:OnUnLoad()">
function OnUnLoad() {
try{
var result = SendByAajx(“data”);
} catch (e) {
//alert(errorInfo);
}
}
When I debug the application, the JS execution stops after this line:
xmlHttpReg.send(null);
It didn’t go to the next line:
if(xmlHttpReg.readyState==4)
The “data” is also not sent to the server.
What is wrong with my program, can ajax be called in an onunload function? What should I do to make it work?

Ajax and ActiveXObject

why when I run this code on local server, req.send(sData) doesn't work?
It runs alert1 but doesn't run alert2;
function initialize() {
var req;
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (oc) {
req = null;
}
}
if (!req && typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
}
return req;
}
function getData(sUrl, sData) {
var req = initialize();
req.open("POST", sUrl, false);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
alert("1");
req.send(sData);
alert("2");
return req.responseText;
}
sUrl and sData are the same as the original website sends.

Facebook check in and windows phone

I've got a script that essentially gives the user the ability to check in to a specific location when they click it. Upon clicking it, it checks them into the same location each time.
On desktop this works fine and I suspect it works on Android too. I have a WP and thus obviously I want to get it working on there. This feature is pretty much going to be used exclusively on mobile so getting it working cross-device is important.
Now, to the actual issue. Upon clicking the check in button on WP it loads a blank page and hangs there. Whilst this may be a signal that it perhaps has checked in, when I look it hasn't. So it's hanging there and doing nothing.
This is the URL it's hanging on: https://m.facebook.com/dialog/oauth?display=touch&domain=www.staffscuesociety.com&scope=publish_stream&api_key=API_KEY&app_id=APP_ID&locale=en_US&sdk=joey&access_token=ACCESS_TOKEN&client_id=CLIENT_ID&redirect_uri=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D18%23cb%3Df35fef827217048%26origin%3Dhttp%253A%252F%252Fwww.staffscuesociety.com%252Ff166245837c3b6e%26domain%3Dwww.staffscuesociety.com%26relation%3Dopener%26frame%3Df398a7113310e64&origin=2&response_type=token%2Csigned_request
and this is the code:
var button;
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() {
FB.init({
appId : '260445377421174',
channelUrl : '//www.staffscuesociety.com/checkin/channel.html'
});
button = document.getElementById('checkinWidget');
if (!button) return;
if (!getPost()) {
allowCheckin();
} else {
allowUndo();
}
};
function setPost(value) {
var d = new Date();
d.setDate(d.getTime() + (10 * 60 * 1000));
document.cookie = 'post=' + escape(value) + ';expires=' + d.toUTCString();
}
function getPost() {
return getCookie('post');
}
function getCookie(key) {
currentcookie = document.cookie;
if (currentcookie.length > 0) {
firstidx = currentcookie.indexOf(key + '=');
if (firstidx != -1) {
firstidx = firstidx + key.length + 1;
lastidx = currentcookie.indexOf(';', firstidx);
if (lastidx == -1) {
lastidx = currentcookie.length;
}
return unescape(currentcookie.substring(firstidx, lastidx));
}
}
return '';
}
function checkin() {
allowNothing();
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me/permissions', function (permissions) {
if (permissions.data.length > 0 && permissions.data[0].publish_stream) {
FB.api('/me/feed', 'post', { message: null, place: '117072761683514' }, function(post) {
if (!post || post.error) {
showError();
} else {
setPost(post.id);
allowUndo();
}
});
} else {
allowCheckin();
}
});
} else {
allowCheckin();
}
}, {scope : 'publish_stream'});
}
function undo() {
allowNothing();
FB.api('/' + getPost(), 'delete', function(response) {
setPost('');
allowCheckin();
});
}
function allowNothing() {
button.onclick = function() { };
button.className = 'pressed';
}
function allowCheckin() {
button.onclick = checkin;
button.className = '';
}
function allowUndo() {
button.onclick = undo;
button.className = 'pressed tick';
}
function showError() {
button.className = 'pressed error';
}
}

send two ajax requests one after another

im working on an HTML5 project that uses multiple canvases,
after the user finishes drawing using the canvas i save them as images to the server.
this is what i have:
function saveViaAJAX()
{
$("#dvloader").show();
document.getElementById("search-result").innerHTML="saving first image...";
var saveCanvasFront = document.getElementById("collage-front");
var canvasDataFront = saveCanvasFront.toDataURL("image/png");
var postDataFront = "canvasData="+canvasDataFront;
var debugConsole= document.getElementById("search-result");
var saveCanvasBack = document.getElementById("collage-back");
var canvasDataBack = saveCanvasBack.toDataURL("image/png");
var postDataBack = "canvasData="+canvasDataBack;
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?option=com_canvas&format=raw&task=savecanvas',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
var ajax2 = new XMLHttpRequest();
ajax2.open("POST",'index.php?option=com_canvas&format=raw&task=savecanvas',true);
ajax2.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
document.getElementById("search-result").innerHTML="saving second image..";
ajax2.send(postDataBack);
}
}
ajax2.onreadystatechange=function()
{
if (ajax2.readyState == 4)
{
document.getElementById("search-result").innerHTML="canvases saved successfully";
setTimeout('top.location.href="index.php"', 4000)
$("#dvloader").hide();
}
}
ajax.send(postDataFront);
}
im sure there is a more elegant way to achieve this. i just want to make sure both requests are successful.this is why im calling them serially, one after the other.
is this correct ?
Thanks
this worked for me
// JavaScript Document
function saveViaAJAX()
{
if(some condition){
alert("false");
return false;
} else {
if (confirm('confirm')) {
callAjax();
}
}
}
function callAjax(){
document.getElementById("process").innerHTML="processing...";
ajax0();
}
function ajax0()
{
var postData = "";
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?....',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
document.getElementById("process").innerHTML="next process...";
ajax1();
}
}
ajax.send(postData);
}
function ajax1()
{
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?...',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
if (ajax.status==403){
document.getElementById("process").innerHTML="error: " + ajax.status + " retry...";
setTimeout( ajax1(), 3000 );
} else if (ajax.status==200 || window.location.href.indexOf("http")==-1 || ajax.responseText != 'failed'){
document.getElementById("process").innerHTML="processing...";
ajax2();
} else {
document.getElementById("process").innerHTML="error: " + ajax.status;
}
}
}
ajax.send(postData);
}
function ajax2()
{
var canvasData = saveCanvas.toDataURL("image/png");
var postData = "canvasData="+canvasData;
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?...',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
if (ajax.status==403){
document.getElementById("search-result").innerHTML="error: " + ajax.status + " retrying...";
setTimeout( ajax2(), 3000 );
} else if (ajax.status==200 || window.location.href.indexOf("http")==-1 || ajax.responseText != 'failed'){
document.getElementById("search-result").innerHTML="processing....";
ajax3();
} else {
document.getElementById("search-result").innerHTML="error: " + ajax.status;
}
}
}
ajax.send(postData);
}
function ajax3()
{
var postData = "";
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?...',true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
if (ajax.status==403){
document.getElementById("search-result").innerHTML="error: " + ajax.status +
" retrying...";
setTimeout( ajax3(), 3000 );
} else if (ajax.status==200 || window.location.href.indexOf("http")==-1 || ajax.responseText != 'failed'){
document.getElementById("process").innerHTML="success";
}
else{
document.getElementById("process").innerHTML="error:" + ajax.status ;
}
}
}
ajax.send(postData);
}
write both ajax request to two functions. call those functions in the main like this.
fun main(){
//read the canvas code
ajax1();
ajax2();
}
fun ajax1(){
//your call
}
fun ajax2(){
//your call
}

How to use AJAX in Dart with async = true

I found a reference for an XMLHttpRequest
final req = new XMLHttpRequest();
req.open('GET', '${Sections.home}/data/$name', false);
req.send();
_htmlBody = req.responseText;
Full Source
But this is for async = false, is there a working example of async = true?
There is an example at https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/samples/belay/bcap/bcap_client.dart
void privateInvoke(String ser, String method, String data,
SuccessI ski, FailureI fki) {
if (urlRegex.hasMatch(ser)) {
var req = new XMLHttpRequest();
req.open(method, ser, true);
req.on.readyStateChange.add(void _(evt) {
if (req.readyState == 4) {
if (req.status == 200) {
ski(req.responseText);
} else {
fki(new BcapError(req.status, req.statusText));
}
}
});
req.send(data);
return;
} else {
super.privateInvoke(ser, method, data, ski, fki);
}
}
also another asynchronous example in https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/client/samples/total/src/ServerChart.dart
XMLHttpRequest request = new XMLHttpRequest();
request.on.readyStateChange.add((Event event) {
if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
callback("data:image/png;base64,${StringUtils.base64Encode(request.responseText)}");
}
});
...
request.open("POST", url, true, null, null);
request.setRequestHeader("Content-type", "text/plain");
request.overrideMimeType("text/plain; charset=x-user-defined");
print("Chart request: ${data}");
request.send(data);

Resources