I'm having an issue with something similar to this and have followed the suggestions but the date is not returning correctly or at all. I think the issue is with the response i.e. the data I'm trying to retrieve.
$(document).ready(function() {
$.getJSON ( "<MYURL>", function(response) {
var location = response["properties"]["name"];
var temp_c = response.temperature;
$(".conditions").html("Current temperature in " + location + " is: " + temp_c + "C");
console.log(response);
});
});
This is the format it is being returned in if I run the link direct from the browser
{"type":"FeatureCollection","crs":{"type":"name",
"properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},
"features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-7.62806,42.32008]},
"properties":{"id":"63797","name":"Xunqueira de Espadanedo",
"municipality":"XUNQUEIRA DE ESPADANEDO",
"province":"Ourense","type":"locality",
"days":[{"timePeriod":{"begin":{"timeInstant":"2016-08-09T20:08:30+02"},"end":
I've been racking my brains all day on this and dont seem to be getting anywhere so any assistance would be appreciated in pointing me int he right direction
Related
I have a need to automate data collection for users who visit specific pages of my site. To do this, I'm querying the LDAP. The LDAP query works just fine when I double click on the file locally (.vbs). However, when I double click on it while it's on the server, it doesn't work (as would be expected). However, I'm as new as new can get to writing VBScript.
After reading a few articles I modified the code and changed the extension to .asp. I ended up with this:
<%
On Error Resume Next
'Create the Array that will be passed
Dim employee(7)
'Employee System Related Info
Set objSysInfo = CreateObject("ADSystemInfo")
employee(0) = objSysInfo.SiteName
'Employee specific information
strUser = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
employee(1) = objUser.sAMAccountName
employee(2) = objUser.givenName
employee(3) = objUser.sn
employee(4) = objUser.displayName
employee(5) = objUser.telephoneNumber
employee(6) = objUser.title
Return employee
%>
In the JavaScript function which would call this .asp file via ajax, I am able to get the employee number which I think could be received by the .asp file and do the rest of the query.... However, I'm not even sure if I'm returning everything correctly in the VBScript. Furthermore, I'm not even sure if I should be using a GET or POST AJAX call. Can someone point me in the right direction?
Updated 03/22/2017 at 10AM CDT
I've finally gotten back to the office and tried to play around. I'm still a little lost. I've made some updates to the code below you'll see the javascript and the VBScript
FIRST the JavaScript:
var employee = {};
function getEmp() {
var ldapUserName = ADSystem.UserName;
$.ajax({
type: "POST",
data: ldapUserName,
url: "https://here.is.my/url.asp",
success: $.ajax({
type: "GET",
dataType: "json",
success: function(responseText) {
employee = responseText;
},
error: function() {
alert("No Data Received");
}
}),
error: function() {
alert("Connection Failed");
}
});
}
Now here is the updated VBScript based on a few things I read and the suggestions from here:
<%
Public Function empDemo(username)
On Error Resume Next
'Create the Array that will be passed
Dim employee(7)
'Employee System Related Info
Set objSysInfo = CreateObject("ADSystemInfo")
employee(0) = objSysInfo.SiteName
'Employee specific information
strUser = objSysInfo.username
Set objUser = GetObject("LDAP://" & strUser)
employee(1) = objUser.sAMAccountName
employee(2) = objUser.givenName
employee(3) = objUser.sn
employee(4) = objUser.displayName
employee(5) = objUser.telephoneNumber
employee(6) = objUser.title
response.write "{ site: " & employee(0) & ","
& "empNum: " & employee(1) & ","
& "empFName: " & employee(2) & ","
& "empLName: " & employee(3) & ","
& "empFullName: " & employee(4) & ","
& "empExt: " & employee(5) & ","
& "empTitle: " & employee(6) & "}"
End Function
%>
Currently, I'm getting the alert stating "No Data Received". What am I doing wrong?
Instead of "return Employee", have you tried:
response.write employee
or maybe
response.write employee.sAMAccountName
Is this VB6? Not sure what libraries are available in classic asp, so you might have to manually write the data in JSON form... i.e...
response.write "{ name: " & employee.sAMAccountName & "}"
EDIT: Just finished up the project. New link is up here! http://codepen.io/myleschuahiock/full/pyoZge/
I'm in the process of making a Weather Widget App for my Free Code Camp. Everything except the "city" is a static placeholder. I'm using the Open Weather Api, which makes us to a latitude and longitude. For debugging purposes, I placed the longitude and latitude of my area underneath the time placeholder.
My problem is that when I statically input the lat and lon on my API link, it works just fine. It returns "Mandaluyong City", a nearby city where I live:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
But when I do this, where I dynamically add mylatitude and mylongitude, to complete the API link:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
I always get "Moscow" as my city.
Please take a closer look at my Javascript/JQuery code here!
http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
Thank you very much! Much appreciated!
Easy solution for you.
Move the $.getJSON() into your if condition, why attempt to query the weather if the client blocks the location?
As Jaromanda X has pointed out:
navigator.geolocation.getCurrentPosition is asynchronous. So, you're calling $.getJSON before the location is actually determined.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.geo').html(position.coords.latitude+ " " +position.coords.longitude);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
});
}else{
$(".geo").html("Please turn on Geolocator on Browser.")
}
});
I hope this helps. Happy coding!
Added
getName(mylatitude, mylongitude);
and changed
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
to
function getName(mylatitude, mylongitude){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
}
http://codepen.io/anon/pen/Yqzvbd?editors=0010
You can use third-party IP API that provides the name of the city. With use jQuery function $.getJSON()
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather';
var APPID = 'APPID';
var ipAPI = 'http://ip-api.com/json/';
$.getJSON(ipAPI).done(function(location) {
$('.geo').html(location.lat + " " + location.lon);
$('.city').html(location.city);
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
APPID: APPID
}).done(function(weather) {
$('#temperature').html(weather.main.temp - 273.15);
})
})
OpenWeatherMap provides the temperature in Kelvin on this I did weather.main.temp - 273.15 to get Celsius
I have a little application that allows users to search for locations on a mac submit comments to a CartoDB SQL database (PostgreSQL) http://docs.cartodb.com/cartodb-platform/sql-api.html using an HMTL form, JavaScript and SQL (and a little PHP to make the API connection to CartoDB). It works great for vast majority of users, but some submissions are not coming through.
I have no idea why the SQL submissions are working sometimes and not others, works perfectly every time for me. Although I have tracked one issue down to Safari 5.1, but I think it must be happening in other browsers too. The main problem is I can't see any errors ANYWHERE, so it's impossible to track down.
So here are my questions:
1. Is there any way of catching SQL errors and preventing the form from being submitted?
2. Is there any way of seeing SQL errors so I can track down the problem?
Below is a snippet of the code I am using to submit the comments:
var tblName = "comment_collection"
var usrName = "***dney"
// FORM
$("#allSubmitBtn").click(function (e) {
//CHECK IF has a comment
if (!notEmpty(document.getElementById('description1'))) {
alert('Please enter a comment.');
return false;
}
if (!notEmpty(document.getElementById('latlongit1'))) {
alert('Sorry, there has been an error, please search for a location again.');
return false;
} else {
currentNeighborhood = $('#neighborhoodName1').val();
parcel = $('#parcel_id1').val();
address = $('#pre_address1').val();
userAddress = $('#UserAddress1').val();
phoneNum = $('#phone1').val();
emailAdd = $('#emailAddress1').val();
userType = $('#userType1').val();
otherUser = $('#otherUserType1').val();
currentDescription = $('#description1').val();
latlongy = $("input[name='latlongit1']").val();
explainType = $('#explainType').val();
currentProject = selectedCity.name;
commentType = new Array();
$("input:checkbox[name=commentType]:checked").each(function () {
commentType.push($(this).val());
});
var sql = "INSERT INTO " + tblName + " (the_geom, project, description, name,comment_address,parcel_id,phone_number,email_address,comment_type,comment_type_other,user_type,user_type_other,profile_address,flag,loved) VALUES (ST_SetSRID(ST_GeomFromGeoJSON('";
// var a = layer.getLatLng();
// console.log(a);
var sql2 = '{"type":"Point","coordinates":[' + latlongy + "]}'),4326),'" + currentProject + "','" + (currentDescription.replace(/'/g, "''")).replace(/"/g, "''") + "','" + (currentNeighborhood.replace(/'/g, "''")).replace(/"/g, "''") + "','" + address + "','" + parcel + "','" + phoneNum + "','" + emailAdd + "','" + commentType + "','" + explainType + "','" + userType + "','" + otherUser + "','" + userAddress + "','false','0')";
var pURL = sql + sql2;
console.log(pURL);
submitToProxy(pURL);
alert("Your Comments have been submitted");
return true;
}
});
here is the Github repo the tutorial is based off. Security is a MAJOR issue and is mentioned right off the bat with this tutorial. It is more of an illustration than anything, anyone implementing it should modify the scripts to be more secure.
Check out this pull request and try to create a solution from it. It addresses the issue to a degree. It moves more of the query into the PHP scripts and only allows field names in from the browser.
https://github.com/enam/neighborhoods/pull/4
This is incredibly dangerous/bad code. You're building sql on the client and sending it to the server to be executed. What's to stop someone from popping up their js console and doing submitToProxy('DROP DATABASE DATABASE()')?
Boom goes your site, boo hoo, too bad.
And even if you DON'T nuke this code from orbit, just to be sure it's really dead, and keep using it, you can't trap SQL exceptions, because they occur on the server, not in your client. At best your SERVER has to check for errors, and send back an appropriate message, e.g.
result = run_query(dangerous ql from user);
if (error occured) {
return json_encode('error' => true, 'reason' => 'someone set us up the bomb'));
} else {
return json_encode('error' => false, 'data' => query results);
}
and then your client-side ajax has to do
$.ajax(....
success: function (data) {
if (data.error) { alert('boom!'); }
else {... do stuff with data ...}
I have this javascript code that is meant to run inside the google chrome console. It constantly checks a json formatted response. If anywhere in the response BestPrice equals max_price then it will purchase it using some API. The problem I am having is about 10 seconds after running it I get 'ERR_INSUFFICIENT_RESOURCES'.
I suppose it is from too many requests? I need it to loop through as fast as possible, so if it can't be instant, is there a certain request limit?
Code:
function snipebot(page, max_page, max_price){
$.getJSON('http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&LegendExpanded=true&Category=2&PageNumber=' + page, function(data){
$.each(data, function(index, item){
if (item['BestPrice'] <= max_price){
$.get('http://www.roblox.com/Item.aspx?id=' + item['AssetId'], function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= item['BestPrice']){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + item['BestPrice'] + '] #' + new Date().toTimeString())
});
} else {
console.log("Detected purchase.");
}
});
};
setTimeout(function(){
snipebot(page + 1 > max_page ? 1 : page + 1, max_page, max_price);
},100);
console.log("!checked");
});
});
};
snipebot(1, 4, 50);
When you call snipebot, it makes a request, and looking at the URL you're using, it gets an array back. Then for each item in the array, you are spawning another snipebot call. Each of those calls would in turn spawn more snipebot calls and so on. So, yeah, the ERR_INSUFFICIENT_RESOURCES error isn't really surprising.
I'm having difficulty juggling values in jQuery, as most of jQuery is done in an external script, and I'm not sure when I'm in functions and not in functions, so it's hard to tell when global vars are set and not set.
This one in particular is puzzling me, and I'm absolutely stumped, logically to me it should work, but there seems to be something capping it at some point, and disregarding the values I'm trying to store.
I've concluded this, as the error I'm having is that inside the second getJSON call, I'm getting a 'val' undefined issue, but Javascript console isn't showing any javascript errors, just getting an undefined log when I log to the console and also print the object in an alert.
Just need a fresh set of eyes, feel like this is probably something simple, but I've been looking at the code so long that I can't seem to fathom it.
Any help is greatly appreciated.
var post_ids = new Array();
var i = 0;
var val;
$.getJSON("/client-ajax/last-ten-posts.php", function(data){
$.each(data, function(k, val) {
post_ids.push(val.id);
});
});
$.getJSON("/client-ajax/last-ten-posts.php?post-id=" + post_ids[0], function(val){
alert(val.title+"");
$("#postContainer").empty();
$("#postContainer").append("<p class='title'>" + val.title + "</p><div class='post-icon'></div><pre>" + val.content + "</pre><p class='footnote'>Posted by " + val.firstname + " " + val.surname + " at <time datetime='2014-06-10'>08:52</time> GMT+00 on the <time>10-06-2014</time></p>");
});
UPDATE:
I edited the code slightly in light of #N0ir's answer, but to no success. The done method ensure that actions are taken once the async process is complete, but although this is the case, val is still undefined. The code I've tried is below for examination and dissemination.
$.getJSON("/client-ajax/last-ten-posts.php", function(data){
$.each(data, function(k, val) {
post_ids.push(val.id);
});
}).done(function(){
$.getJSON("/client-ajax/last-ten-posts.php?post-id=" + post_ids[0], function(val){
alert(val.title+"");
$("#postContainer").empty();
$("#postContainer").append("<p class='title'>" + val.title + "</p><div class='post-icon'></div><pre>" + val.content + "</pre><p class='footnote'>Posted by " + val.firstname + " " + val.surname + " at <time datetime='2014-06-10'>08:52</time> GMT+00 on the <time>10-06-2014</time></p>");
});
});
UPDATE - Network Return on call for JSON:
GET http://*****************.com/client-ajax/last-ten-posts.php [HTTP/1.1 200 OK 154ms]
GET http://*****************.com/img/home.jpg [HTTP/1.1 304 Not Modified 152ms]
GET http://*****************.com/img/about.png [HTTP/1.1 304 Not Modified 142ms]
GET http://*****************.com/img/about-repeat.jpg [HTTP/1.1 304 Not Modified 147ms]
GET http://*****************.com/img/blog.jpg [HTTP/1.1 304 Not Modified 146ms]
GET http://*****************.com/img/portfolio.jpg [HTTP/1.1 304 Not Modified 210ms]
GET http://*****************.com/img/contact.jpg [HTTP/1.1 304 Not Modified 209ms]
GET http://*****************.com/client-ajax/last-ten-posts.php [HTTP/1.1 200 OK 207ms]
You wanna do somethign like this:
var post_ids = new Array();
var i = 0;
var val;
$.getJSON("/client-ajax/last-ten-posts.php", function(data){
$.each(data, function(k, val) {
post_ids.push(val.id);
});
$.getJSON("/client-ajax/last-ten-posts.php?post-id=" + post_ids[0], function(result){
alert(result.title+"");
$("#postContainer").empty();
$("#postContainer").append("<p class='title'>" + result.title + "</p><div class='post-icon'></div><pre>" + result.content + "</pre><p class='footnote'>Posted by " + result.firstname + " " + result.surname + " at <time datetime='2014-06-10'>08:52</time> GMT+00 on the <time>10-06-2014</time></p>");
});
});
So that the second getJSON call happens after the first one is finished.
So I found the issue, turns out fetchAll() in php's PDO returns an array, so when creating the JSON from the array, the JSON needs to be accessed through the first element of the array, like so:
val[0].content
rather than:
val.content