I'm working on a Project for pedestrian navigation. For blind people, I'd like to tell them if there are any objects in the same street as they are, so they can orientate themselves.
I have a Json-file full with coordinates of trees from a city. I query geonames (with $.ajax) to get the nearby streets of the trees and want to store this information in a file. A json-file would be great, but I have no idea how to do this.
Can anyone tell me how I can create such a file? It has to be made only once.
Or do you know an alternative to store the data in a better way?
What I tried so far in js:
function writeToJson(streetNames){
$.ajax({
type: 'POST',
url: "scripts/treeStreets.php",
data: streetNames,
dataType: 'json',
error : function(parameters){
console.log("error");
console.log(parameters);
},
success: function(){
console.log("success");
}
});
}
And the php-script:
$streetNames = $_POST[streetNames];
file_put_contents('/live%20access/data/treeText.txt', $streetNames);
But this gives me an error.
You need to write a service in a language like PHP, Ruby, Python or Java. JavaScript has no ability to create a file on either the client or server so you'll need a service that the AJAX operation can call which will write the data to disk.
Related
I have a Python script, which does some computations and makes a figure. Then, I am using mpld3 to generate an HTML version of this figure and save it (e.g., figure.html). The Python computations are launched via the AJAX request to the HTTP server. In my JS file, I use the jQuery.load() method to insert the plot into HTML:
$("#includedContent").load('/figure.html');
In this way, everything seems to work fine. The question is can I do the same thing without saving the figures? I tried to return a figure as a response, here is my modified AJAX request:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/main.py",
data: JSON.stringify({ 'sim_dur': input }),
success: function (response) {
figure = response.figure;
var child = document.createElement('div');
child.innerHTML = figure;
child = child.firstChild;
document.getElementById('includedContent').appendChild(child);
}
});
If I assign an HTML-like string to child.innerHTML, the code works correctly. But when I try to assign it a figure (which has a string type as well), it is not showing on the HTML page. I'm new to JS, so I apologize if it is something basic. I did some research and it seems that people usually save the results in other answers, so maybe it is a common way to do it and what I am trying to do is not right.
In my experience, mlpd3 will only work when the client (browser) is loading the page. Once the page is loaded, updating or creating an mpld3 figure using an ajax call won't create the figure for you. I personally struggled with that for some time and then gave up. I am sure one can patch things up but then you'll be stuck to your own mpld3 patched version
I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:
${data.id}
I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.
Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.
Any help would be great! I think I can use AJAX, but unsure on how this would look.
here the AJAX sample.
$.ajax({
method: "POST",
url: "some.php",
data: { id: data.id}
})
.done(function( response) {
console.log(response);
//TODO:process your response here if receive response from php file.
});
I am attempting to teach myself some JQuery/REST/Google API by putting together a simple page that does the following:
Authenticates with Google
Validates a token
Gets a list of Google Calendars for the user
List events for a selected calendar
Add an event for a selected calendar
I have #1 through #4 working (although no doubt in an ugly manner), and am getting tripped up on #5. Here's the JQuery ajax call:
var url = 'https://www.googleapis.com/calendar/v3/calendars/[MY_CALENDAR_ID]/events?sendNotifications=false&access_token=[GOOGLE_API_TOKEN]';
var data = { end: { dateTime: "2012-07-22T11:30:00-07:00" }
, start: { dateTime: "2012-07-22T11:00:00-07:00" }
, summary: "New Calendar Event from API"
};
var ajax = $.ajax({ url: url
, data: data
, type: 'POST'
}).done(addEventDone)
.fail(function (jqHXR, textStatus) {
console.log("addEvent(): ajax failed = " + jqHXR.responseText);
console.log(jqHXR);
});
The results are a global parseError: "This API does not support parsing form-encoded input.". The first four steps are all using GET ajax calls, so I'm not sure if that is what is tripping me up.
Here's the API in question: https://developers.google.com/google-apps/calendar/v3/reference/events/insert
I think I may be doing things the long and hard way, and my new approach is to tackle this using the javascript API instead of going straight at it with manual JQuery and REST. This is the approach I am attempting going forward http://code.google.com/p/google-api-javascript-client/wiki/Samples#Calendar_API, although I would still love to use this as a learning opportunity if there is something simple I am screwing up in the code above.
Thanks for any help, insights, pointers, etc. I will post updates if I make any progress using the javascript API.
Interestingly, I just answered a similar question here. Your intuition to use Google's JS client library is a good one. It's going to handle OAuth 2 for you, which is a requirement if you're going to do any manipulation of the Calendar data.
My other answer has both a link to a blog post that I authored (which demonstrates configuration of the client and user authorization), as well as an example of inserting a Calendar event.
you need to set contentType: "application/json", to do JSON.stringify for your data and method : 'POST'
var ajax = $.ajax({
url: url,
contentType: "application/json",
data: JSON.stringify(data),
method : 'POST',
});
I'm looking for a way to return a single JSON/JSONP string from a cross-domain "AJAX" request. Rather than request the string and have JQuery return it as a generic object automatically, I want to get a hold of the string BEFORE that conversion happens. The goal here is to parse it myself so I can turn it straight into new objects of a certain type (e.g. a Person object).
So, just to make this clear, I don't want any string-to-generic-object conversion going on behind the scenes and this must work using a different domain.
Here's a non-working example of what I would like to do:
$.ajax({
type: 'GET',
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'text',
success: parseToPerson
});
function parseToPerson( textToParse ) {
// I think I can do this part, I just want to get it working up to this point
}
I'm perfectly happy if JQuery isn't involved in the solution, as long as it works. I would prefer to use JQuery, though. From what I've read, the javascript techniques used to get JSONP data (dynamically creating a script element) would probably work, but I can't seem to get that to work for me. I control the domain that I am requesting data from and I can get the data if I change the dataType in the AJAX call to 'JSONP', so I know that is working.
If your data is being retrieved from another domain, you will need to use JSONP (there are other options, but JSONP is by far the easiest if you control the service). The jQuery call will look like this:
$.ajax({
// type: 'GET', --> this is the default, you don't need this line
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'jsonp',
success: parseToPerson
});
The actual request that goes to your service will be http://www.someOtherDomain.com/GetPerson?callback=arbitrary_function_name. On the service side, you will need to return data like this:
arbitrary_function_name("the string (or JSON data) that I want to return");
So you'll need to inspect the querystring parameters, get the value of the callback parameter, and echo it out as if you're calling a Javascript function with that name (which you are), passing in the value you want to provide through the service. Your success function will then get called with the data your service provided.
If you're deserializing the returned data into a Javascript object, you might be better off returning JSON data than a string, so the data your service returns might look like this:
arbitrary_function_name({
"name":"Bob Person",
"age":27,
"etc":"More data"
});
That way you don't have to worry about parsing the string - it'll already be in a Javascript object that's easy to use to initialize your object.
Not sure how this will work in conjuction with jsonp, but maybe converters is what you're looking for?
$.ajax(url, {
dataType: "person",
converters: {
"text person": function(textValue) {
return parseToPerson(textValue);
}
}
});
using
http://maps.google.com/maps/api/geocode/json?address=xyz
we get a json file
I am wondering how can i maniupluate the results in javascript? How do i create the results object in javascript?
http://code.google.com/apis/maps/documentation/geocoding/index.html#JSONParsing
this doesnt really explain how they get the myJSONResult
You can use eval to parse the JSON into a JavaScript object, but this isn't recommended for security reasons. Use a JSON parser to turn the JSON string into a JavaScript object that you can manipulate.
Using eval:
myJSONResult = eval("{}");
Using the above linked parser:
myJSONResult = JSON.parse("{}");
The way you get the JSON is using an AJAX retrieval. This can be accomplished using hand coded JavaScript, but is far far easier using jQuery. Here's a quick example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({ url: "http://maps.google.com/maps/api/geocode/json",
type: "GET",
dataType: "json",
data: { address: "1600+Amphitheatre+Parkway,+Mountain+View,+CA", sensor: "false" },
success: function(data, textStatus, XMLHttpRequest) {
console.log(textStatus);
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
}});
});
</script>
BUT BUT BUT this will NOT work, because of the same origin policy. The way around that is to use a server side language of your choice (Perl, PHP, ColdFusion, ASP) to act as a proxy. That way the url value would be "yourproxy.php", "yourproxy.cfm", "yourproxy.asp" or whatever. That script would simply take the request it receives, act as a user agent to send the request to Google and retrieve the response (aka the URL that is the url value in the code above), and send out the results to your script.
The jQuery library handles the JSON processing for you, or you can use the information provided by Bob along with the hand rolled AJAX listed above. Note that hand rolled AJAX will need the same proxy solution to be able to get information from Google.
Also note that the Geocoding API you linked to is not meant for lots of dynamic queries. They lead you to the API V2 Client Geocoder, the API V3 Client Geocoder, and the Maps API for Flash Client Geocoder.