GET HTTPs request not working properly in phonegap - javascript

I'm running this app in an Android phone (Samsung Galaxy mini running on ANdroid 2.2). I'm using couchdb for my database and host it on cloudant.
On device ready, the app will make a get request to the https db server which contains feeds of data that i need to be displayed in my app. At first, it was working fine but when i try to post and add new data to my https db server, then trigger the get request method, the returned response from the server is still the same as before(the newly posted data was not included even though i checked my db server and saw that it was indeed saved). Then i tried to close and reopen the app again, which will then make a new instance of the get http request, but still, the response still is the same as the very first one and doesnt contain the new data that was added to the db server. Then, I tried to reinstall my app, then run the app again, and oddly enough, the response from the get request now contains the new data.. I don't know how that happens, and I'm not really experienced with REST api and javascript so I might be doing something obviously wrong. Here's a snippet of my code for the get request:
var getFeedsClient;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if (window.XMLHttpRequest) {
getFeedsClient=new XMLHttpRequest();
}
else {
getFeedsClient=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
getFeedsRequest();
} catch(e)
{
alert("Error on device ready: "+e);
}
}//on Device Ready
function getFeedsRequest() {
getFeedsClient.onreadystatechange = getFeedsFunction;
getFeedsClient.open("GET","https://<username>.cloudant.com/te/_design/requestfeed/_view/all",true);
getFeedsClient.send();
}
function getFeedsFunction() {
alert(" readystate: "+getFeedsClient.readyState+", status: "+getFeedsClient.status);
if(getFeedsClient.readyState == 4 && getFeedsClient.status == 200 ) {
var data = JSON.parse(getFeedsClient.responseText);
console.log("RESPONSE FROM COUCHDB "+getFeedsClient.responseText);
console.log("JSON data "+data);
//at first the total rows is 2 but when a new data was added, the total rows should be three, but that was not the case
alert("rows: "+data.total_rows);
}
}

I ran into a similar issue last week of the device caching requests. I solved it by adding a dummy unique parameter to the link like below:
function getFeedsRequest() {
getFeedsClient.onreadystatechange = getFeedsFunction;
var link = "https://<username>.cloudant.com/te/_design/requestfeed/_view/all";
var unique = (new Date).getTime();
getFeedsClient.open("GET",link + '?' + unique,true);
getFeedsClient.send();
}

Paul Beusterien's solution below worked for me with the following caveat:
An android 4.0.4. phone did not need a unique URL, but the same code running on 2.2.2 did!

Related

Socket.io stops working after multiple refreshes

I have a socket.io connected to a https server listening for javascript to emit information to it. I am finding that when I refresh, the socket is recording the connection - so if i console.log something in the on('connection', function(socket) { } part of the code, I will see a response in the console.
What I am finding though, is that on the server side, the socket.on() calls are not picking up anything.
So if I have a line in Javascript which is socket.emit('ping', msg), 'ping' will work on the server side for the first 9-10 refreshes, and then on the 11th refresh it will stop working - and it will stop working on all devices and all browsers. So if I open another browser and try to load it up, it won't work either.
I have checked to see if there are multiple connections building up or something like that, but I am not seeing anything. Any idea why this weird behaviour is happening?
Server Side
io.use(function(socket, next) {
// Authentication of the user is happening here - checking for cookies, sessions, etc.
}).on('connection', function(socket) {
// Setting up some variables and checking other stuff
var socketID = socket["id"];
var username = socketUsers[socketID];
locked[socketID] = {};
// Checking for the username
if(username == '' || typeof username == "undefined") {
// Emit some stuff back to Javascript
io.to(`${socketID}`).emit('criticalError', true);
return false;
}
else {
// We have a valid login, so connect to the server
++connected;
// This line will console log every time I refresh
console.log("Some text");
socket.on('ping', function(msg) {
// This line will console log for the first 9-10 refreshes, and then it suddenly stops working. Any ideas why?
console.log('Server was pinged by ' + username);
});
// This line will console log every time I refresh
console.log("Some other text");
}
});
Client side
var socket = io('https://example.com:1337');
$(document).ready(function() {
socket.emit('ping', true);
});
This is an interesting problem that you are facing. There are multiple points to check on - However the first problem I would suggest is with the below code:
var socket = io('https://example.com:1337');
$(document).ready(function() {
socket.emit('ping', true);
});
If this is the exact code on the client side, chances are that the socket.emit is getting called before the connection handshake goes through. This can be random as sometimes the document ready event might be delayed. Try setting a timeout for the emit event -
var socket = io('https://example.com:1337');
$(document).ready(function() {
setTimeout(function(){socket.emit('ping', true);},2000);
});
and give it a try. If this works, you found the problem. Next step is to ensure authentication is working correctly - Without the complete code, advising on this is difficult. Feel free to edit the question and share the code if your issue isn't resolved.

Cordova FileTransfer sends file but nothing received

I'm sending a video recorded via Cordova's MediaCapture plugin to a remote server via the FileTransfer plugin, but nothing - neither the file, nor any data whatsoever - is arriving at the server end. The server receives the request, but it seems to be empty.
According to Cordova, everything goes fine. Here's the readout from the success callback:
And here's my JS: (mediaFiles[0] is the captured video file)
var options = new FileUploadOptions();
options.fileName = 'foo.bar';
options.mimeType = mediaFiles[0].type;
options.params = {
mime: mediaFiles[0].type
};
var ft = new FileTransfer();
ft.upload(
mediaFiles[0].fullPath,
encodeURI("http://xxxxxx.com/receive-video.php"),
function (r) {
console.log(r);
alert('sent file!');
},
function (error) {
alert('error');
console.log(error);
},
options,
true
);
(Note the last param, trustAllHosts, is set to true since my test server is self-signed.)
Cordova clearly thinks it's sent data, but my PHP script disagrees. Here's my PHP:
file_put_contents(
'readout.txt',
"Payload\n----------\n".
file_get_contents('php://input').
"\n\nRequest\n----------\n".
print_r($_REQUEST, 1).
"\n\nFiles\n----------\n".
print_r($_FILES, 1).
"\n\nPost\n----------\n".
print_r($_POST, 1)
);
As you can see, I'm looking pretty much everywhere. All these result in empty readouts, however, in readout.txt.
What am I doing wrong?
It turned out the chunkedMode param (in options) was the culprit.
In case this helps anyone else, disable this (it's true by default) and all should be fine.
options.chunkedMode = false;
Not sure how to explain the behaviour of the empty request with it turned on, though. The param exists to send the file in chunks, to allow for progress feedback of some sort.

data send by firefox tcp socket.send() can't retrive until close the socket

I'm trying to send some data from Firefox to java desktop application .so my java class work as a server and Firefox script work as a client .when i test it using another java class which is client.java data successfully sent to server.java how ever when i use this firefox script to send data ,it actually connect to the server .but send("text"); doesn't work realtime .i mean sever shows received data when i close the socket socket.close(); . but i know there is no problem with server.java code.
this doesn't work
setTimeout(function(){socket.send("i'm firefox");},5000); // because socket isn't closed yet
this work
setTimeout(function(){socket.send("i'm firefox");},5000);
setTimeout(function(){socket.close();},6000);
but i really don't want to close the socket because i want to send lot of data one by one.
here is the complete code tested on scratchpad [-browser]
var tcpSocket = Cc["#mozilla.org/tcp-socket;1"].createInstance(Ci.nsIDOMTCPSocket);
var socket = tcpSocket.open("127.0.0.1", 5000);
setTimeout(function(){socket.send("i'm firefox");},5000);
//setTimeout(function(){socket.close();},8000);// i'm firefox text retrieve by server when run this line / when close the socket.
i think java code isn't important.but here it is.
I'm asking why do i need to close the socket to send data ? and how can i send data without close the socket ?
update
i made a Gif to show my problem here you can see data not sending real time but when socket is closed all the data flushed .
It's actually working. Your data is being received, but you're currently waiting for a new line to print your received messages:
while ((inputLine = in.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
Which currently only happens when you close the socket. Just add a new line at the end of your messages and it will work as expected:
var tcpSocket = Cc["#mozilla.org/tcp-socket;1"].createInstance(Ci.nsIDOMTCPSocket);
var socket = tcpSocket.open("127.0.0.1", 5000);
function sendMessage(msg){
socket.send(msg + "\n");
}
setTimeout(function(){
sendMessage("hi mark");
},3000);
setTimeout(function(){
sendMessage("hi johnny");
},5000);

Request fails from my web application when refreshing the Browser (Firefox). When starting new tab this issue do not happen

My application make a request to a .dll and set my extension.
[My application is a call control application. All operations are achieved, like make call from extension,set my extension, etc using request to dll(C++)]
My issue is, I make a get request from the application using javascript to the dll as follows
GET http://192.168.XX.XX/iq/VpWebExt.dll?ACTION=GETEXT&EXT=5042&REDIRECT=NO&now=1397018694640
I get the XML response successfully when i load my application in new tab. But When I reload the page, if the application try to set the extension using the above mentioned request, it does not return the XML response.
Below is the piece of code in my web app which makes the request. I get status code as "0" and httpObj.responseText as empty.
var httpObj;
var xmlhttp;
if (window.ActiveXObject) {
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
httpObj = new XMLHttpRequest();
}
httpObj.open("GET", httpUrl, false);
httpObj.send();
if ( httpObj.status == 200 )
{ httpResult = httpResult + httpObj.responseText;
}
else
{
alertAppConsole("httpObj.status = " + httpObj.status);
}
This issue happens only in "FireFox". In other browsers like IE or chrome where I tested I don't face the issue.
Also to I need to mention, when I deploy in my local machine(win 7, IIS 7.5) this issue do not happen at all.
When I deploy in my client machine (Windows server 2008 R2, IIS 7.5) this issue occurs.

XDomainRequest POST with XML...what am I doing wrong?

This is (hopefully) an easy question. I have to submit a request to a web service via POST with XDomainRequest. I have found sparse documentation for this across the internet, but I refuse to believe that nobody has figured this out.
Here is my XDomainRequest code:
var testURL = 'http://localhost:4989/testendpoint';
//let us check to see if the browser is ie. If it is not, let's
if ($.browser.msie && window.XDomainRequest) {
var xdr2 = new XDomainRequest();
xdr2.open("POST", testURL);
xdr2.timeout = 5000;
xdr2.onerror = function () {
alert('we had an error!');
}
xdr2.onprogress = function () {
alert('we have some progress!');
};
xdr2.onload = function () {
alert('we load the xdr!');
var xml2 = new ActiveXObject("Microsoft.XMLDOM");
xml2.async = true;
xml2.loadXML(xdr2.responseText);
};
//what form should my request take to be sending a string for a POST request?
xdr2.send("thisisastring");
}
My web service (WCF) takes a single parameter according to the web service's help page, that looks like this:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">String content</string>
I've gotten this to work via other http clients (mobile and desktop APIs, fiddler) by building a string that concatenates the parameter I am trying to pass to the web service with the rest of the string serialization. For example, I have tried:
xdr2.send("thisisastring");
xdr2.send("<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">thisisastring</string>");
but the onerror handler is always tripped. I don't think it has anything to do with the WCF because:
The WCF is always successful in every other client I call it from,
and
If it was the service, the onerror method would never get tripped.
It would return garbage, but it would be returning something.
When i use the console (in the dev tools in ie9) to log the responseText, it says:
LOG:undefined
So I am fairly sure that the issue is in how I use the XDomainRequest.
If anybody comes across this, I ended up converting my web services to return JSON-formatted data. Using JSON negates the need for XDomainRequest, allowing me to use the conventional ajax jquery tools instead.

Categories