Wunderground Geolocation using $.ajax not appending to HTML - javascript

I am experimenting using in using $.ajax to use geolocation to input weather data into a page from Wunderground. I am able to successfully input weather data into my page when I manually enter my location into code using plain vanilla JS but want to take it a step further. I am running the following code and get an alert box asking for location but after clicking okay see no code updates to my HTML. When opening the console in dev tools I do not see any error messages.
var Geo={};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGeo,error);
}
else {
alert('Geolocation is not supported');
}
function error() {
alert("Cant find you");
}
function successGeo(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
function showPosition(position) {
var geoLat = position.coords.latitude;
var geoLong = position.coords.longitude;
var key = "8704dded63fc077d";
var ForecastURL = "http://api.wunderground.com/api/"; + key + "/forecast/q/" + geoLat + "," + geoLong + ".json";
var WeatherURL = "http://api.wunderground.com/api/"; + key + "/conditions/q/" + geoLat + "," + geoLong + ".json";
$.ajax({
url : WeatherURL,
dataType : "jsonp",
success : function(parsed_json) {
var temp_f = parsed_json['current_observation']['temp_f'];
document.getElementById("currentTemp").innerHTML = temp_f;
}
});
$.ajax({
url : ForecastURL,
dataType : "jsonp",
success : function(parsed_json) {
var fore_high = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit'];
var fore_low = parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit'];
document.getElementById("high1").innerHTML = fore_high;
document.getElementById("low1").innerHTML = fore_low;
}
});
} //ends showposition function
I have some div elements set up in the footer of index.html just so I can confirm the elements are being updated. I'll worry more about style and alignment later.
<footer> <!--//contains ajax weather data-->
<div id="high1"></div>
<div id="current_temp"></div>
<div id="low1"></div>
</footer>
I'm pretty stumped as to why I can't get a response, especially since I'm not picking up any errors in the console.

Related

Undefined variable when passing javascript variable to PHP with AJAX

I am trying to build a simple mobile app that checks database and gives user the correct venue based on their location. Essentially, I have two files: one with geolocation, JavaScript and AJAX call, and another one with php that checks the database and sends the correct result back. Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined. Why does it not pick up the coordinates (they pop up in a separate window)? How can I fix it?
Here is my geolocation and AJAX code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var latitude;
var longitude;
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
var request = $.ajax({
url: "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php?latitude=" + latitude + "&longitude=" + longitude,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#ajax").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
</script>
And here is the bit of PHP that handles these variables:
if (isset($_GET['latitude']) && isset($_GET['longitude'])) {
$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
echo "Geolocation seems to work...";
echo $latitude;
echo $longitude;
//continue here
}else{
echo "Hello. I am your geolocation and I am not working.";
}
What I get is "Geolocation seems to work...undefinedundefined"
The Geolocation API is asynchronous, so you have to wait for the result to return
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url : "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php",
data : {latitude : latitude, longitude : longitude},
type : "GET",
dataType : "html"
}).done(function(msg) {
$("#ajax").html(msg);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
remove var in both variable. Those two are not visible outside displayPosition. When you use the $.ajax call you're using latitude and longitude declared right under the $(document).raedy() but you never assign nothing to them so they're undefined.
Hope this solve your issue.
P.S. You se the values in the alert because you're using ones from position, not from your variables.
Do not use var inside your displayPosition function. You do not want to declare new variables inside the scope of the function, you want to assign values to the existing variables you declared in the global scope earlier.

Js file for find location / Address?

I need address in project. I am getting address by using Latitude and longitude with including below scripting code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
Is there any respective .js file is there to find location instead of loading above URL ?
Please give some suggestions because with out internet connection my app is not loading, It is throwing Application Error.
Click here for your query. I think it will be usefull for you.
why dont you use a function() to get the location and dispaly it within the div??
chk out below:
function Location() {
var latlng = userLatValue + ',' + userLngValue;
var locationUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latlng + "&sensor=false";
var locationRequest = $.ajax({
type : 'GET',
url : locationUrl,
async : false,
data : "json"
});
locationRequest.done(function(data) {
if(data.results.length > 0) {
userLocationName = data.results[0].formatted_address;
//alert('address: ' + userLocationName);
}
});
locationRequest.fail(function(jqXHR, textstatus, error) {
//alert("error:");});
}

extjs 4.1 download xml file using ajax

i want to download a file using extjs 4.1.
The file name is "wsnDataModel.xml".
I've tryed with all things suggested in other posts:
//function invoked clicking a button
DwDataModel : function(th, h, items) {
//direct method that build in file in the location calculated below with "certurl" (I've verified)
Utility.GetDataModel(function(e, z, x) {
if (z.message) {
//the server method should give an error message
Ext.create('AM.view.notification.toast', {
title : 'Error',
html : z.message,
isError : true
}).show();
} else {
// navigate to get data
var certurl = 'http://' + window.location.host
+ '/AdminConsole3/' + e;
Ext.Ajax.request({
method : 'GET',
url : 'http://' + window.location.host
+ '/AdminConsole3/' + e,
success : function(response, opts) {
//the following navigate and openthe file in the current browser page.
//I don't want to change the current browser page
//window.location.href = certurl;
//the same behaviour with
//document.location = certurl;
//and this don't work at all
window.open(certurl,'download');
},
failure : function(response, opts) {
console
.log('server-side failure with status code '
+ response.status);
console.log('tried to fetch ' + url);
}
}, this, [certurl]);
}
}, th);
}
the "navigation" redirect the application (i don't want to redirect the application) like this:
and I'would like to download the file like this image:
I think it's very simple. How to do that?
thank you
Very simple: this is the success function.
success: function (response, opts) {
var link = document.createElement("a");
//this gives the name "wsnDataModel.xml"
var fileName = certurl.substring(certurl.lastIndexOf('/') + 1);
link.download = fileName;
link.href = certurl;
link.click();
}

Get position coordinates for an ajax request

Currently working on a weather web-app for iOS. I'm trying to get the coordinates of the user and put the latitude and longitude in my Ajax request (on the api Wunderground) .
Here's my code (EDIT):
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(getLocation, unknownLocation);
function getLocation(pos)
{
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+ lat +","+ lon +".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
function unknownLocation()
{
alert('Could not find location');
}
});
</script>
As you can see I "simply" have to create 2 vars lat and lon and add them in my request. I tried a lot of variants but I can't get this code working.
Any idea of what I'm doing wrong ?
Thank you very much !
Your variable declarations are in the middle of the .ajax call, and are making the JavaScript structure invalid. Also, I'm not sure why you're using "function($)", normally with jQuery the $ is reserved and shouldn't be used as a function parameter.
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(onPositionUpdate);
});
function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+lat+","+lon+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
</script>

Encoding a JSONP <script src = Request

I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.

Categories