I'm trying to get the direction_in_traffic, which isn't returned using the regular directions api. I've found that there is a field in the distancematrix api that does just that.
This code works when I run it from my own machine, but once it is online, I see errors concerning Access-Control-Allow-Origin
var durationInTraffic = function(from, to, mode, callback) {
var key = 'API-KEY';
var address = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + from + '&destinations=' + to + '&key='+ key +'&travelmode=' + mode + '&departure_time=now';
var req = new XMLHttpRequest();
req.addEventListener('load', function(){
if (typeof callback === 'function') {
callback(JSON.parse(this.responseText).rows[0].elements[0].duration_in_traffic.value);
}
});
req.open('GET',address);
req.setRequestHeader('Access-Control-Allow-Origin','https://haroen.me');
req.setRequestHeader('Access-Control-Allow-Headers','X-Requested-With');
req.send();
};
I've created the key, but at the domain verification tab it seems to "forget" what addres I've put in.
jsbin (which obviously won't work since this key isn't allowed on that domain, but I get the same error on my own domain).
The full code I'm trying this on is visible at https://github.com/haroenv/maps-checker
Thanks for your help!
So as #dandavis suggested in a comment, the reason why this didn't work is because Google wants this response to be server-side. My workaround is as follows: a php (or any server-side solution) that mirrors the request to Google. An example implementation is this:
<?php
echo file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . urlencode($_POST['from']) . '&destinations=' . urlencode($_POST['to']) . '&key='. urlencode(json_decode(file_get_contents('config.json'), true)['maps-key']) .'&mode=' . urlencode($_POST['mode']) . '&departure_time=now');
?>
And then I send a request to that script from within my main client-side script.
Related
I am wondering if it is possible to make an API call from within a design doc. I have tried the code below, however I am getting the following error message.
{"error":"forbidden","reason":"CSRF Cookie/Header mismatch"}
This is the code:
function(head, req) {
var id = req.query.id;
var contactName = 'This is the new contact name!!';
var sendString = '{"PrimaryContactName":"' + contactName + '"}';
var xhr = new XMLHttpRequest();
xhr.open('PUT", <URL>, false);
xhr.send(sendString);
var sendStatus = xhr.status;
}
Thanks!
You aren't going to be able to use AJAX from CouchDB. (it's not a web browser)
If you want changes in your database to be propagated to other data-sources, you can use the _changes feed. That will be a much more robust solution no matter how you slice it.
I'm trying to build a Google query string, make a request to that page, scrape the HTML, and parse it in a Chrome extension, which is JavaScript. So I have the following code:
var url = "https://www.google.com/search?#q=" + artist + "+" + title;
searchGoogleSampleInformation(url);
function searchGoogleSampleInformation(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
return parseGoogleInformation(xhr.responseText, url);
}
}
xhr.send();
}
function parseGoogleInformation(search_results, url)
{
var link = $(".srg li.g:eq(0) .r a", search_results).attr('href');
}
The parse method just grabs the url of the first search result (which is not want I'll end up doing, but just to test that the HTTP Request was working). But link is undefined after that line. Then I used alert(url) and verified that my query string was being built correctly; I copied it from the alert window and pasted into another tab, and it pulled up the results as expected. Then I opened a new window with search_results, and it appeared to be Google's regular homepage with no search at all. I thought that problem might be occurring because of the asynchrony of the xhr.open call, but flipping that didn't help either. Am I missing something obvious?
It's because "https://www.google.com/search?#q=" + artist + "+" + title initially has no search results in the content. Google renders the page initially with no results and then dynamically loads the results via JavaScript. Since you are just fetching the HTML of the page and processing it the JavaScript in the HTML never gets executed.
You are making a cross domain Ajax call, which is not allowed by default. You cannot make a cross domain call unless the server supports it and you pass the appropriate headers.
However, as you mentioned you are building a Chrome extension, it is possible by adding a few fields in the manifest file: https://developer.chrome.com/extensions/xhr#requesting-permission
I'm trying to write a plugin. I can not use any libraries or frameworks.
At any website (domain) I would like to start a script from my own domain.
For example:
In the code of the website under domain A I put a code starting the script from domain B
<script src="http://domain-b.com/myscript.js" type="text/javascript"></script>
The code of JavaScript (myscript.js)
type = 'GET';
url = 'http://domain-b.com/echojson.php';
data = ‘var1=1&var2=2’;
_http = new XMLHttpRequest();
_http.open(type, url + '?callback=jsonp123' + '&' + data, true);
_http.onreadystatechange = function() {
alert(‘Get data: ’ + _http.responseText);
}
_http.send(null);
Script from http://domain-b.com/echojson.php always gives the answer:
jsonp123({answer:”answer string”});
But in a JavaScript console I see an error (200) and AJAX doesn’t get anything.
Script loaders like LAB, yep/nope or Frame.js were designed to get around the same-origin policy. They load a script file, so the requested file would have to look like:
response = {answer:”answer string”};
If you use your code like you have posted it here, it does not work, because you are using apostrophs for the data variable!
You now have to pay to use the google translate api. I'm happy to pay for the service but I can't find a way to use the tts. This is what I'm doing
var GoogleTranslate = function(){
var key = "myapikey"
this.speak = function(words) {
var url = "http://translate.google.com/translate_tts?tl=es&q=" + escape(words) + "&key=" + key
new Audio(url).play();
}
}
but when I do new GoogleTranslate().speak("hola")
The requests to http://translate.google.com/translate_tts never return a response. How do I get this working?
I haven't tried your code yet, so I'm not sure if you should be waiting for the sound to load before you can play it (most likely), but I've written an article about this service recently. The part that matters here is the following:
...if your browser forwards a Referer header with any value other than an empty string (meaning it tells the service which page you clicked the link on) then [Google] will return a 404 (Not Found) http error...
Read the entire article here: Embedding text-to-speech into HTML5 games
So in fact, the service is still there, you just need to hide your referer header. One way to do that is through creating a small gateway script. There's the source for one right in the article.
I Keep getting OAuthException (#210) Subject must be a page. error even if I am using the Page Access Token and not the App Access Token.
I am using the following:
Latest JavaScript SDK from facebook (//connect.facebook.net/en_US/all.js)
Calling the /{PAGE_ID}/tabs?app_id={APP_ID}&method=POST&access_token={PAGE_ACCESS_TOKEN} using the FB.api method once the user is logged in.
My Application is not FBML but a Canvas / iFrame App. What am i doing wrong?
I have researched the web including the Stackoverflow and other facebook forums but still no answer on this. OAuth is Enabled for my Application.
Also, If i copy and paste the link in Browser it works fine. It does not if I do it using the API.
I finally got it working.
However, Instead of using the FB.api to call the link above, i used jQuery.
I used jQuery "$.getJson(url)" and it worked.
It works as below.
Construct the link as below.
"https://graph.facebook.com/{PAGE_ID}/tabs?app_id={APP_ID}&method=POST&access_token={PAGE_ACCESS_TOKEN}&callback=?"
Call the jQuery method as below.
"$.getJSON(pageUrl, OnCallBack);" where "OnCallBack" is the call back method. You can do anything that you would need in the call back. In my case it was something like below.
function OnCallBack(r, s) {
var html = "";
if (s == "success" && !r.error) {
for (p in r) {
html += p + ": " + r[p] + "<br />";
}
} else {
html = r.error.message;
}
$("#dv").html(html);
}
To anybody who gets this error again:
I have get the same error message while I use wininet to post a https request to https://graph.facebook.com/......
I just changed the verb from "POST" to "GET" , and then it works well:
//string strVerb = "POST";
string strVerb = "GET";
PS: variable "strVerb" is used as the 2nd parameter of windows function HttpOpenRequest.