how can i export the geolocation output to log file? - javascript

I have this code it displays the geolocation (Longitude: xx Latitude: xx Accuracy: xxx) ..how can I output the results into a log file log.txt when any body visit the url
<!-- <xml version="1.0" encoding="utf-8"> -->
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Geolocation API Demo</title>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport"/>
<script>
function successHandler(location) {
var message = document.getElementById("message"), html = [];
html.push("<img width='512' height='512' src='http://maps.google.com/maps/api/staticmap?center=", location.coords.latitude, ",", location.coords.longitude, "&markers=size:small|color:blue|", location.coords.latitude, ",", location.coords.longitude, "&zoom=16&size=512x512&sensor=false' />");
html.push("<p>Longitude: ", location.coords.longitude, "</p>");
html.push("<p>Latitude: ", location.coords.latitude, "</p>");
html.push("<p>Accuracy: ", location.coords.accuracy, " meters</p>");
message.innerHTML = html.join("");
}
function errorHandler(error) {
alert('Attempt to get location failed: ' + error.message);
}
navigator.geolocation.getCurrentPosition(successHandler, errorHandler);
</script>
</head>
<body>
<div id="message">Location unknown</div>
</body>
</html>

This is the javascript code which will send the data asynchronously to the server.
function successHandler(location) {
var message = document.getElementById("message"), html = [];
html.push("<img width='512' height='512' src='http://maps.google.com/maps/api/staticmap?center=", location.coords.latitude, ",", location.coords.longitude, "&markers=size:small|color:blue|", location.coords.latitude, ",", location.coords.longitude, "&zoom=16&size=512x512&sensor=false' />");
html.push("<p>Longitude: ", location.coords.longitude, "</p>");
html.push("<p>Latitude: ", location.coords.latitude, "</p>");
html.push("<p>Accuracy: ", location.coords.accuracy, " meters</p>");
message.innerHTML = html.join("");
//Send this to server
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","script.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send("latitude="+location.coords.latitude+"&longitude="+location.coords.longitude+"&accuracy="+location.coords.accuracy); // pass data, assuming lat, long, acc are respective js variables
}
function errorHandler(error) {
alert('Attempt to get location failed: ' + error.message);
}
navigator.geolocation.getCurrentPosition(successHandler, errorHandler);
Retrieve the data on server side and save with below PHP code (script.php)
<?php
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$accuracy = $_POST['accuracy'];
$string = $latitude." - ".$longitude." | ".$accuracy; // this will turn into 00000 - 00000 | 0.25
$myfile = file_put_contents('log.txt', $string.PHP_EOL, FILE_APPEND);
?>

For this you will need a server side that can store data locally on its system. I would suggest that you use PHP or whatever other server side language you know.
You will write a program that will receive an object, or perhaps just 2 variables and will store it into a file.txt.
This should not be very hard, if you are confused you should look up JavaScript AJAX calls.

For java here is the code.
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","file.jsp?latitude="+location.coords.latitude+"&longitude="+location.coords.longitude+"&accuracy="+location.coords.accuracy,true);
xmlhttp.send();
In Jsp (file.jsp) write. Better to write java code in servlets not in JSP.
java.io.File file = new java.io.File("d://filename.log");
java.io.FileWriter writer = new java.io.FileWriter(file);
writer.write(request.getParameter("latitude")+" "+request.getParameter("longitude")+" "+request.getParameter("accuracy"));
writer.flush();
writer.close();

Related

Displaying Order History without using tables

i am new to UI devlopment.I use to do coding but i have been asked to get the value from xml and display order history without using tables.I am getting xml from jax-rs and want to display on html.
My Xml is:
<orderHistory>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039011
</detail_url>
<lineItemCount>ssolineItemCount</lineItemCount>
<order_id>7039012</order_id>
<sort_date>1448316</sort_date>
<status>Shipped</status>
<store_label>SSO Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>11.76</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039009
</detail_url>
<lineItemCount>tsolineItemCount</lineItemCount>
<order_id>7039009</order_id>
<sort_date>1448316</sort_date>
<status>Cancelled</status>
<store_label>Teacher Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>15.25</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orderHistory>
My Html is like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function init() {
// put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly
//xmlhttp = new XMLHttpRequest();
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/NewShot/schl-api/myresource/com/";
xmlhttp.open('GET', url, false);
xmlhttp.send();
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
//alert('Inside');
var xmlData = xmlhttp.responseXML;
if (!xmlData) {
xmlData = (new DOMParser())
.parseFromString(
xmlhttp.responseText,
'text/xml');
}
// alert('Content'+xmlData);
var store , O_url ,status,total,description,tracknum,litncount,trackhrf,subdate,sdate,durl,elements;
var conference = xmlData
.getElementsByTagName("orders");
for (var i = 0; i< conference.length; i++) {
// alert('In For');
store = conference[i].getElementsByTagName("store_label")[0].firstChild.data;
O_url = conference[i].getElementsByTagName("order_id")[0].firstChild.data;
status = conference[i].getElementsByTagName("status")[0].firstChild.data;
total = conference[i].getElementsByTagName("total")[0].firstChild.data;
description = conference[i].getElementsByTagName("description")[0].firstChild.data;
tracknum = conference[i].getElementsByTagName("tracking_num")[0].firstChild.data;
litncount = conference[i].getElementsByTagName("lineItemCount")[0].firstChild.data;
trackhrf = conference[i].getElementsByTagName("tracking_href")[0].firstChild.data;
subdate = conference[i].getElementsByTagName("submitted_date")[0].firstChild.data;
sdate = conference[i].getElementsByTagName("sort_date")[0].firstChild.data;
durl = conference[i].getElementsByTagName("detail_url")[0].firstChild.data;
//alert(date+" "+name+" "+url);
elements +="StoreType::"+store+ "<br>" +"OrderUr::"+ O_url + "<br>" +
"Status::"+status+"<br>"+"Total Bill::"+total+"<br>"+""+"Item Description::"+description+"<br>"+"Trackinh Number::"+tracknum+"<br>"+
"LineItemCount::"+litncount+"<br>"+"Tracking Link::"+trackhrf+"<br>"+"Submission Date::"+subdate+"<br>"+"Sort Date::"+sdate+"<br>"+"DetailUrl::"+durl+"<br><br>";
}
document.getElementById("demo").innerHTML= elements;
/* date = conference[0]
.getElementsByTagName("date")[0].firstChild.data;
name = conference[0]
.getElementsByTagName("name")[0].firstChild.data;
url = conference[0]
.getElementsByTagName("url")[0].firstChild.data;
*/
// alert('Name'+name+'Date'+date+'url'+url);
} else {
name = "";
date = "";
url = ""
alert("Invalid Employee ID");
}
} else {
alert("Error ->" + xmlhttp.responseText);
}
}
</script>
</head>
<body onload="init()">
<h1>Call Scholastic Service </h1>
<table>
<tr>
<input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
</table>
<p id="demo"></p>
</body>
</html>
I want to display value without using table in following format:
Store Label: <Value> LineItem Count:<Value>
OrderId: <Value> LineItem Count:<Value>
Status Times: <Value> Tracking Link:<Value>
Total: <Value> Submission Date:<Value>
Description: <Value> Date Sorting:<Value>
Tracking Number:<Value>
Detail Url:<Value>
I tried using but it was not proper.
Thanks

XMLHttpRequest with php will not work

I've been trying to get this solved for 2 weeks now and still have no success.
JavaScript:
var quotenum = 0;
var xmlhttp = null;
var rt = "";
function ChangeQuote() {
quotenum++;
xmlhttp = null;
//alert("quotenum= "+quotenum);
if (quotenum === 0) {
document.getElementById("quote").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
rt = xmlhttp.responseText;
//alert("quote= "+rt);
alert("request number= " + xmlhttp.length);
document.getElementById("quote").innerHTML = rt;
}
};
xmlhttp.open("Get", "getquote.php?q=" + quotenum, false);
//xmlhttp.open("GET", "getquote.php?XDEBUG_SESSION_START=netbeans-xdebug&q=" + quotenum, false);
xmlhttp.send();
//var thediv = document.getElementById("quote");
return false;
}
PHP:
error_reporting(E_ERROR | E_PARSE);
$q="";
$q = intval($_GET['q']);
$link=mysqli_connect("localhost","root","sequence","babylon");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT quotetext FROM quote where quotenum='".$q."'";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo $row["quotetext"];
}
Can anyone see anything wrong with this?
Using WAMP I can see the correct result when I run the PHP file in a browser.
I also try to use Jquery instead.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var quotenum = 0;
// var xmlhttp = null;
// var rt = "";
function ChangeQuote() {
quotenum++;
$.ajax({
url: "getquote.php?q="+quotenum,
method: "get",
data: {
q: quotenum
}
}).done(function (data) {
alert(data);
document.getElementById("quote").innerHTML = data.quotetext;
});
return false;
}
</script>
The only noticable error I see is you inlining your js with the script tag that has a src attribute.
HTML 4.01 Specification:
The script may be defined within the
contents of the SCRIPT element or in
an external file. If the src attribute
is not set, user agents must interpret
the contents of the element as the
script. If the src has a URI value,
user agents must ignore the element's
contents and retrieve the script via
the URI.

javascript notification checker script Uncaught Reference Error

I have this notification checker and i don't know whats wrong with this js code, i have errors on checkMessage() : Uncaught Reference Error: checkMessage is not defined
the js code:
function checkMessage(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() //when the request is submitted...
{
if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
{
if(xmlhttp.responseText>0){ // if the response text is greater than 0
document.title="("+xmlhttp.responseText+")"+"My Social Network - Welcome";
document.getElementById('checkMsg').innerHTML="<b>" + xmlhttp.responseText+" Notifications</b>";
}
else
document.title="My Social Network - Welcome";
document.getElementById('checkMsg').innerHTML="No notifications";
}
}
xmlhttp.open("GET","checkMessage.php?user_id="+"1",true);
xmlhttp.send();
}
the checkmessage.php code:
<?php
include 'dbm.php'; //database settings from an external file
$user = $_SESSION['user'];
$get_count_messages = mysql_query("SELECT message FROM notifications ");
$row = mysql_num_rows($get_count_messages); // count how many rows the query returned
echo "$row"; //return the value
?>
The html code:
<html>
<head>
<script type="text/javascript" src="notifications.js"></script>
<script type="text/javascript">
setInterval("checkMessage()", 1000);
</script>
</head>
<body>
<div id="checkMsg"></div>
</body>
</html>
It's just a simple example to make a difference betwen the number of notifications
if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
{
var title = "";
var message;
if(xmlhttp.responseText > 0)
{
title += "(" + xmlhttp.responseText + ")";
if(xmlhttp.responseText > 1)
message = "<b>" + xmlhttp.responseText + " Notifications</b>";
else
message = "<b>" + xmlhttp.responseText + " Notification</b>";
}
else
message = "No notifications";
title += "My Social Network - Welcome";
document.title = title;
document.getElementById('checkMsg').innerHTML= message;
}
I think your setInterval function should look like:
setInterval(checkMessage, 1000);
Because setInterval expect a function as parameter.

XMLHttpRequest not working - no errors

I am trying to get this simple request working but I am not having much luck.
I have the "test.txt" file in the server folder as my html file containing the script provided below.
I viewed the file in Chrome, Firefox and IE11 with the same result. I can only see the "Initial text in the html page.." text from the html page. No errors and the text from my test.txt file is not getting displayed.
Could anyone please point me what the issue with my code is?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp:
}
function process(){
if(xmlHttp){
try{
xmlHttp.open("GET","test.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
catch(e){
alert( e.toString() );
}
}
}
function handleServerResponse(){
output = document.getElementById('output');
if(xmlHttp.readyState==1){
output.innerHTML += "Status 1: server connection established <br />"
}
else if(xmlHttp.readyState==2){
output.innerHTML += "Status 2: request received <br />"
}
else if(xmlHttp.readyState==3){
output.innerHTML += "Status 3: server processing <br />"
}
else(xmlHttp.readyState==4){
if(xmlHttp.status=200){
try{
text = xmlHttp.responseText;
output.innerHTML += "Status 4: request is finished and response is ready<br />"
output.innerHTML += text;
}
catch(e){
alert( e.toString() );
}
}
else{
alert( xmlHttp.statusText );
}
}
}
</script>
</head>
<body onload="process()">
Initial text in the html page..<br>
<br>
<div id="output">
</div>
</body>
</html>
Ok, I figured it out....
it was one typo and one ommision
return xmlHttp: -> should be ; instead
and forgot "else"
else(xmlHttp.readyState==4){ -> should be else if (xmlHttp.readyState==4){

xmlHttp.responseText Unknown Error define

I have create a javascript in an html (using xmlHttp.responseText) page where I am requesting a value from an aspx page that queries for a usernumber of a username in the database (MSSQL). when i load the html (IE8), i got this "Unknown Runtime Error Line: 30". What supposed to be causing the problem? need help. Here is my code:
Here is the HTML page and the Javascript:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showUsernum(str)
{
var xmlHttp;
if (str=="")
{
document.getElementById("textExists").innerHTML="";
return;
}
if (window.xmlHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp=new xmlHttpRequest();
}
else
{// code for IE6, IE5
xmlHttp=new ActiveXObject("Microsoft.xmlHttp");
}
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
//alert(str);
document.getElementById("textExists").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("GET","http://localhost/Base_Data/default.aspx?q="+str,true);
xmlHttp.send();
}
</script>
</head>
<body>
<form action="" method="post">
<label>UserName
<input type="text" name="textUser" id="textUser" onchange="showUsernum(this.value)">
</label>
</form>
<br/>
<div >
<form name="form1" method="post" action="">
<label>
<div id="textExists">Exists?</div>
</label>
</form>
</div>
</body>
Here is my ASP code.
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
SqlConnection conn;
string connection = ConfigurationManager.ConnectionStrings ["BaseData"].ConnectionString;
conn = new SqlConnection(connection);
string sql = "SELECT USERNUM FROM useraccount WHERE USERNAME ='" + Request.QueryString["q"] + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
string contNm = Convert.ToString(cmd.ExecuteScalar());
Response.Write("textExists=" + contNm );
conn.Close();
}
Really appreaciate any response. Thank you.
The problem is that you're trying to assign whole page, including <html> tag and everything, into a single DOM element and IE doesn't really like that.
To have the server send only raw HTML without whole document you need to clear the Response. In addition you are not disposing properly of the database objects and you are exposed to SQL Injection attacks, so optimized code would be:
string connection = ConfigurationManager.ConnectionStrings ["BaseData"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
string sql = "SELECT USERNUM FROM useraccount WHERE USERNAME=#user";
string contNm = "";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#user", Request.QueryString["q"]);
contNm = Convert.ToString(cmd.ExecuteScalar());
}
Response.Clear();
Response.Write("textExists=" + contNm);
Response.End();
conn.Close();
}

Categories