Javascript, generate result to text file - javascript

This is a sample javascript code from http://locationdetection.mobi to detect geo location using google API.
(Original zip file contains a php file, html, and this javascript code)
As you see in the code below, on the last part of this javascript code there is one line of code to render the result of location detection to html file.
How to generate result into a text file instead of render to browser?
// this is called when the browser has shown support of navigator.geolocation
function GEOprocess(position) {
// update the page to show we have the lat and long and explain what we do next
document.getElementById('geo').innerHTML = 'Latitude: ' + position.coords.latitude + ' Longitude: ' + position.coords.longitude;
// now we send this data to the php script behind the scenes with the GEOajax function
GEOajax("geo.php?accuracy=" + position.coords.accuracy + "&latlng=" + position.coords.latitude + "," + position.coords.longitude +"&altitude="+position.coords.altitude+"&altitude_accuracy="+position.coords.altitudeAccuracy+"&heading="+position.coords.heading+"&speed="+position.coords.speed+"");
}
// this is used when the visitor bottles it and hits the "Don't Share" option
function GEOdeclined(error) {
document.getElementById('geo').innerHTML = 'Error: ' + error.message;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(GEOprocess, GEOdeclined);
}else{
document.getElementById('geo').innerHTML = 'Your browser sucks. Upgrade it.';
}
// this checks if the browser supports XML HTTP Requests and if so which method
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response;
}
}

You can't create text files from the frontend, well at least not without configuring some flags in the browser, so you need to send the data to your backend language, create the file and then download it

Related

Unable to retrieve geolocation

I am trying to run a Javascript code to retrieve a device's geolocation. When I try to run the code from the localhost (127.0.0.1) the code runs as expected, opening a pop up to ask the user to enable location services. However, when I try to host this code or access it using the local IP address (192.168.x.y), the code fails with an error
Any ideas as to why it works for localhost and not otherwise.
Here's the JS Code
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
Thanks.
Recent versions of Chrome require secure protocols for some features. Fore example a page must be served up httpS for it to be able to obtain the user's geolocation.
The restriction is relaxed for localhost to enable dev/debugging.

Error sending Post request ASP.Net Using AJAX & JavaScript (not jQuery)

I am having issues sending a Post request ASP.Net using AJAX and JavaScript. My intentions are to send multiple values to a database and insert them. I have an html page with the following functions calling ASP request using AJAX.
.html file:
// Builds AJAX request and sends it to ASP page
function sendInfo(x,y,z){
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=stateChanged;
xmlhttp.open("POST","Update.asp",true);
xmlhttp.send("addy="+encodeURIComponent(x)+
"&lat="+encodeURIComponent(y)+
"&lng="+encodeURIComponent(z));
}
// Checks the ready state of the sent response
function stateChanged() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
else {
document.getElementById("txtHint").innerHTML="Error with ready state: " + xmlhttp.readyState + " and status: " + xmlhttp.status;
}
}
Here is my .asp file:
<%
conn = Server.CreateObject("ADODB.Connection");
conn.Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" + Server.MapPath("Project.mdb"));
var addy=Request.Form("addy");
var lat=Request.Form("lat");
var lng=Request.Form("lng");
var sql="INSERT INTO Location_Info (Address,Latitude,Longitude)"
sql= sql + " VALUES "
sql= sql + "('" + addy + "',"
sql= sql + "'" + lat + "',"
sql= sql + "'" + lng + "')"
rs = conn.Execute(sql);
Response.Write("Your record has been placed into the database.");
rs.Close();
conn.Close();
%>
Whenever I run my page and enter the proper information to be sent, it only returns the else case of "Error with ready state: 4 and status: 500". This status of 500 is a general error and I am unsure of how to debug my program, as I have even tried commenting everything in the .asp file and only having 'Response.Write("text");' code, but to no avail, still status:500 error.
If someone can help me with what I am doing wrong, it would be greatly appreciated.

Check for an specific .js file being served in response

I need to detect whether an specific .js file was served in a http response and additionally, check the domain it came from, like this:
I need to automatically detect the lack of the js file and email the incidence
I tried Net::Http, rest-client, mechanize and a lot of gems, they just return the html header. It seems I need to monitor http traffic with tools like PhantomJS and checking for the file, but is there any rubyesque way of doing this?
Thanks in advance
I ended with the phantomjs approach. A ruby script iterate over a database table and then calls this phantomjs script for each record representing an URL
This is the phantomjs script
var page = require('webpage').create(),
system = require('system'),
address,
isScript = false;
var fs = require('fs');
// main
analizePage(system.args[1]);
//open page.
//onResourceRequested event, compares domain of each one with 'my.domain.net'
//append to a log file: -1 for failed url, 1 for script presence, 0 for no script presence
function analizePage(address){
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address ' + address);
fileWriter(-1, address);
}
else
{
if (!isScript){
fileWriter(0, address);
}
else
{
fileWriter(1, address);
}
console.log('Has script: ' + isScript);
}
phantom.exit(0);
});
page.onResourceRequested = function (req) {
try {
var link = document.createElement('a');
link.setAttribute('href', req.url); //extract asset's domain from URL
if (link.hostname == 'my.domain.net') {
isScript = true;
}
} catch(e) {
console.log("PAGE OPEN ERROR: " + e);
}
};
}
function fileWriter(type, line){
try {
fs.write("scriptlog.csv", type + ',' + line + ',' + Date.now() + ',' + system.args[2] + '\n', 'a');
} catch(e) {
console.log("FILE ERROR: " + e);
}
}

CGI File Writing File w/only Read Permissions

My web server sends a xmlhttprequest to write a JSON file whenever a button is clicked. However, the file has only read permissions when written. Also, this ONLY happens when the web server asks the cgi script to execute. However, if I try executing this cgi script myself from command line, the file is written with both read and write permissions. Is there any way I can allow the web server to make this cgi script write a file with full permissions?
As requested, here is the part of my code which sends the xmlhttprequest and fetches/the json file.
<script>
function loadXMLdoc() {
var xmlhttp = new XMLHttpRequest();
var url = "/cgi-bin/run.cgi"
var id = document.getElementById("inputId").value;
var mutation = document.getElementById("inputMutation").value;
var position = document.getElementById("inputPosition").value;
var json;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
$.getJSON("data.json",function(result){
$.each(result, function(i, field){
output = "<h1>Output<h1>"
for (var f in field){
output+="<p>Identifier: " + field[f]["value"]+" Position: "+field[f]["position"]+" Mutation: "+field[f]["mutation"]+"</p>"
}
});
});
document.getElementById("test_container").innerHTML = output
}
}
xmlhttp.open("GET", url+"?id=" + id + "&mutation=" + mutation + "&position=" + position, true);
xmlhttp.send()
}
</script>
And here's the part in run.cgi which writes the file.
write_file = open("%s/data.json" %(root_directory), 'w')
write_file.write('{"results": [\n')
for i,result in enumerate(results):
write_file.write('\t{"value": "%s", "mutation": "%s", "position": "%s"}' % (result["value"], result["mutation"], result["position"]))
if i != len(results) - 1:
write_file.write(",")
write_file.write("\n")
write_file.write("]}")
write_file.close()

Getting the responseText from XMLHttpRequest-Object

I wrote a cgi-script with c++ to return the query-string back to the requesting ajax object.
I also write the query-string in a file in order to see if the cgi script works correctly.
But when I ask in the html document for the response Text to be shown in a messagebox i get a blank message.
here is my code:
js:
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function getresponse () {
XMLHttp.open
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
XMLHttp.send(null);
}
XMLHttp.onreadystatechange=function(){
if(XMLHttp.readyState == 4)
{
document.getElementById('response_area').innerHTML += XMLHttp.readyState;
var x= XMLHttp.responseText
alert(x)
}
}
</script>
First Names(s)<input onkeydown = "javascript: getresponse ()"
id="fname" name="name"> <br>
Surname<input onkeydown = "javascript: getresponse();" id="sname">
<div id = "response_area">
</div>
C++:
int main() {
QFile log("log.txt");
if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
{
return 1;
}
QTextStream outLog(&log);
QString QUERY_STRING= getenv("QUERY_STRING");
//if(QUERY_STRING!=NULL)
//{
cout<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<< QUERY_STRING.toStdString()<< "\n";
outLog<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<<QUERY_STRING<<endl;
//}
return 0;
}
I'm happy about every advice what to do!
EDIT: the output to my logfile works just fine:
Content-type: text/plain
The Query String is: fname=hello&sname=world
I just noticed that if i open it with IE8 i get the query-string. But only on the first "keydown" after that IE does nothing.
You don't have to use javascript: in on___ handler, just onkeydown="getresponse();" is enough;
IE>=7 supports XMLHttpRequest object, so directly checking if XMLHttpRequest exists is better than checking whether navigator is IE. Example:
if(XMLHttpRequest) XMLHttp=new XMLHttpRequest();
else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
inside your getresponse() function, try to add below code at the beginning (before open):
try{XMLHTTP.abort();}catch(e){}
Because you're using a global object, you may want to "close" it before opening another connection.
Edit:
Some browser (maybe Firefox itself?) do not handle non-"text/xml" response very well in default state, so to ensure things and stuffs, try this:
function getresponse () {
try{XMLHttp.abort();}catch(e){}
XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain");
XMLHttp.send(null);
}
My problem had nothing to do with the code...
I was testing my script on the local IIS7 and I opened the html-page with double-clicking on the file. But you have to open the webpage via browser (localhost/mypage.htm) because otherwise for the browser the html and the executable have different origins. which is not allowed.

Categories