HTML and Android don't work together - javascript

Here is what I am trying do:
Save sensor info from Android tablet to txt file online
Open a webpage to read that data continuously using ajax calls
Note: Website and Android app are running simultaneously
Android part:
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://.../save.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error1: " + e.toString());
}
JS part
setInterval("DisplayBall()", 500);
function DisplayBall()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("TotalTime").value = 0;
//alert(xmlHttp.responseText);
AssignResult(xmlHttp.responseText);
}
}
//xmlHttp.open("GET", "TINBCoordinates.txt", true);
//xmlHttp.send();
xmlHttp.open("GET", "read.php", true);
xmlHttp.send();
}
Why do these two interfere & make my program unresponsive?

Switch to using PhoneGap.js it will save you a lot of time.

Related

Servlet Response to Javascript in plain text shown on browser

I have my servlet sending the following response to a JS ajax call:
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print("start");
out.close();
and the call from the web page has the following code:
function update() {
var xmlhttp = new XMLHttpRequest();
var id = '${user.id}';
var height = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
height = height-40;
var params = "action=update&id=" + id + "&height=" + height;
xmlhttp.open("POST", "/Anabasis/UserControl", true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var answer = xmlhttp.responseText;
if(answer=="start"){
window.location.href = "/project/page1.jsp";
} else {
window.location.href = "/project/page2.jsp";
}
}
};
xmlhttp.send(params);
}
setTimeout(update, 10000);
If start is send back by the Servlet, the browser should be redirected to another page. This may be done without the user's doing anything since the JS request is send every 10 seconds.
Now the result is that I do not get the answer to page but just a black page with the text: "start"
Can anyone tell me what to add in order to asure that the answer gets back to the JS function?
It's better to forward your request according to your requirement, like:
RequestDispatcher rd=request.getRequestDispatcher("./project/page1.jsp");
rd.forward(request, response);
I have found the solution, sorry for the question. The code actually works fine, just in some case the Servlet gets not called by this update function but by another form from the same page. So of course the answer is not send to the function, explaining the misbehaviour.
Is there any guide on best practices concerning Servlet-Webpage communication? I guess I shall need that very much.

Using JavaScript code for navigating (InnerHTML)

I'm using this code below for the navigation system on my site, the purpose is to open an HTML page within a div .. (InnerHTML), but, when I'm clicking one of my menu links I'm getting the JavaScript notification "Problem: " (see "else" in the JavaScript code block). This code is fixed (good) for SEO aspect.
Can someone please tell me what the problem with it is? I'm trying to preserve the code as it is as much as possible.
Thank you in advance for your help!
JavaScript code:
function processAjax(url)
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
In HTML body:
<a onclick="return processAjax(this.href)" href="example.html">CLICK ME</a>
<div id="containerDiv"></div>
The server returned a non-200 response. If you're using a debugger like Firebug, Chrome Developer, or IE Developer, check the Network tab to see exactly where your XHR went, and what the response was.

xmlHttpRequest.send(Params) not working in tomcat 7

I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.

Strange CSS issue with JavaScript with JSON data

When I use hardcoded JSON string, my UI comes OK
But when I use string from Web Service, no css style runs !!!
//jsonData = '{.....}';
//extractData(jsonData); //THIS CODE WORKS
var request = new XMLHttpRequest();
request.open("GET",url);
request.onload = function(){
if(request.status == 200){
jsonData = new String(request.responseText);
alert("RESPONSE : "+jsonData);
extractData(jsonData); //THIS WON'T WORK :(
}
else
alert("Connection Issue : "+request.status);
};
request.send(null);
Can anyone point out the root cause ???
I am running this code in phoneGap for Android.

Extract Title from web page, using just the url

I want to replicate some functionality from Digg.com whereby when you post a new address it automatically scans the url and finds the page title.
I am programming in classic ASP and VBScript and using javascript. Anyone know a script to make this happen..?
Many thanks in advance..
Paul
This is somewhat of a rudimentary example. You should probably include some data verification.
The ASP page should be called something like getPageTitle.asp
<%
Response.Buffer = True
Dim strURL, objXMLHTTP, objXML, strContents
Dim objRegExp, strHTML, strPattern, colMatches, strTitle
strURL = Request.Form("url")
Set objXMLHTTP = Server.CreateObject ("Microsoft.XMLHTTP")
'Or if this doesn't work then try :
'Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.Open "GET", strURL, False
objXMLHTTP.Send
strContents = objXMLHTTP.ResponseText
Set objXMLHTTP = Nothing
Set objRegExp = New RegExp
strPattern = "<title>(.*?)<\/title>"
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
Set colMatches = objRegExp.Execute(strContents)
If colMatches.Count > 0 then
strTitle = objMatches(0).Value
Else
strTitle = ""
End If
Set objRegExp = Nothing
Response.write(strTitle)
%>
This is a basic JavaScript POST implementation. You could spruce this up a bit with any JS framework you like.
var script = "http://www.example.com/getPageTitle.asp"
var page2check = "http://www.example.com/somePageToCheck.html"
function getXMLHttpRequestObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = new getXMLHttpRequestObject();
var parameters = "url="+page2check;
http.open("POST", script, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(parameters);
var pageTitle = http.ResponseText
I hope this helps.
Send url from clientside to serverside using javascript(ajax).
Load html page by it's url using asp on serverside.
Parse html page, extract title.
Send title to clientside.

Categories