I am trying to call google api for getting place suggestions from ember js. like below: this is the service module
fetch(){
let url=`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY`
return Ember.RSVP.resolve(Ember.$.ajax(url,{
method: 'GET'
}))
.then(
(response)=>{
console.log("google suggested places:",response);
return response;
})
*the above url when served with API_KEY and pasted in browser, a JSON response is returned with the suggested places.
also, i am seeing JSON response in newtwork tab of developer tools but the .then is not able to capture that resonse, and printing in console as response undefined.
ref : https://developers.google.com/places/web-service/autocomplete#place_autocomplete_results
And in console i am seeing " Failed to load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY: No 'Access-control-Allow_origin'header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
What am i doing wrong?
You are using Ember.RSVP.resolve wrong. It returns a Promise which resolves immediately with value passed as first argument. So in your case it resolves with return value of Ember.$ajax(). I'm not quite sure if this function exists. I guess you meant Ember.$.ajax() which is just an alias for jQuery.ajax(). But this one should return a jqXHR object. So I have no idea why your code is not throwing for Ember.$ajax() is not a function or why response is undefined and not a jqXHR object.
But nevertheless your approach to wrap the ajax call in a promise is wrong. Also I would say using jQuery.ajax is not best practice. There are some work ongoing to make jQuery optional in ember.js and you don't want to couple your application with it.
I would recommend using ember-fetch or ember-ajax.
The above approach doesnt work, so for any who wants to have maps suggestions on ember application , follow this
https://www.npmjs.com/package/ember-cli-g-maps
It is perfectly working.
Related
I'm trying to make a $http.jsonp request in angularjs to a geoserver wfs which expects the callback name to be "parseResponse", however I can see the request being made being controlled by angular and set to their standard such as "angular.callbacks._0"
The vendor parameters for the WFS can be found at
http://docs.geoserver.org/maintain/en/user/services/wms/vendor.html#wms-vendor-parameters which demonstrates that the callback can be set by setting format_options=callback:myCallback in the URL, and by default is set to "parseResponse", however Angular seems to disregard this and add its own callback parameter regardless, which results in the http call failing as parseResponse is undefined
This has left me in the unusual position of having to set the callback name to "angular.callbacks._0" in the URL to get a response from the request, which is obviously a messy solution if i want to make any other calls to this WFS (which I do/will be doing)
http://jsfiddle.net/ADukg/15394/
myApp.controller("searchCont",function($scope, $http,$sce){
$scope.name = 'Superhero';
jsonSchools = "http://inspire.dundeecity.gov.uk/geoserver/inspire/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=inspire:SCHOOL_CATCHMENTS_PRIMARY&%20srsName=EPSG:27700&bbox=338906.9,732790.9,338907.1,732791.1&&outputFormat=text/javascript&format_options=callback:angular.callbacks._0";
//jsonSchools = "http://inspire.dundeecity.gov.uk/geoserver/inspire/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=inspire:SCHOOL_CATCHMENTS_PRIMARY&%20srsName=EPSG:27700&bbox=338906.9,732790.9,338907.1,732791.1&&outputFormat=text/javascript&format_options=callback:parseResponse";
var trustedUrlSchools = $sce.trustAsResourceUrl(jsonSchools);
$http.jsonp(trustedUrlSchools).then(function (response) {
$scope.schools = response.data.features;
console.log($scope.schools);
});
});
I've set up a JS Fiddle to demonstrate the problem, with the first URL demonstrating the working interim solution and the second commented out URL showing how the URL should in theory look. Notable if you copy the URL itself without the format_options parameter it will still also default to parseResponse
Lastly I came across a previous stackoverflow issue which looks similar at (how to custom set angularjs jsonp callback name?) but it didn't seem to help and gave generic method undefined errors.
Any help or direction on this problem would be appreciated, I have thus far tried setting jsonpCallbackParam in the http request but to no avail. Hoping this is an oversight on my part that I can put down to inexeperience.
Thanks in advance
I'm trying to do a getJSON call to a page within my domain that is simply a json array, which is not returning anything given the script in my webpage:
<script>
$('#genButton').click(function() {
console.log("click");
$.getJSON("http://mygithub.github.io/repository/quotedb.json", function(data){
console.log("executing");
var entry = data[Math.floor(Math.random()*data.length)];
console.log(entry);
$("#quoteDisplay").text(entry);
}).fail(function() {
console.log( "error" );
});
})
</script>
When the button is clicked, the console logs the "click", but never logs "executing", but also doesn't log any errors related to the getJSON. The debugger also never pauses within the getJSON function.
My question is, 1. Is it valid for quotedb.json to be literally a webpage with just a single json array? Or does the page need to be annotated in some way so that the getJSON request knows where to pick up the json from? 2. If (1) is fine, then are there any other reasons you can see why nothing from the getJSON return function would appear?
The json is again one array of json objects, in the form:
{
"character": ""
"quote": ""
}
EDITS
With the edited code, it now outputs "click" followed by "error" from the .fail() method of the $.getJSON call now.
I tried removing the ?callback? section of the url as suggested below, which did not work.
The /repository/ section of my url seems to be necessary to access the file.
Try without ?callback=? at end of url, see jQuery.getJSON()
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
Occasionally, an ajax request to Flickr's api will fail. I'm not sure if I'm doing something wrong here - or if I'm just not handling things correctly - but the code works over 90% of the time. When it doesn't work, I get the following error message from Firefox's console:
TypeError: jQuery19109306644694293944_1362865216185 is not a function
(I am letting jquery generate the callback, which is why the callback is named like that.)
This is the code that sometimes fails:
function getAppropriateSize(photo){
console.log("In getAppropriateSize");
/** stuff. query is defined here **/
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&api_key='+flickrKey+'&photo_id='+query.id,
dataType:'jsonp',
jsonp:'jsoncallback',
timeout:3000,
success: function(sizes){
console.log("In success - getAppropriateSize");
/**determine the correct size**/
flickrURL = sizes.sizes.size[currVal].source;
},
error: function(xmlhttprequest,textstatus,msg){
console.log("In error - getAppropriateSize");
/* handle error*/
}
});
}
I've checked what's returned when this happens and JSLint says it's valid javascript. flickrURL also gets set to a valid URL. I'm pretty mystified about what's causing this error - any help would be appreciated.
Edit: I was messing around and this time getAppropriateSize just received two separate messages from flickr for one call. The first one was
({stat:"fail", code:1, message:"Photo not found"})
The second one was the a full response from the server that also produced the TypeError mentioned above. However, the second response found the photo and gave me the sizes.
If you copy and past the following url to your browser:
http://finance.google.com/finance/info?client=ig&q=MUTF_CA%3ATDB900
it will output an string no problem. (that is what i wanted to retrieve from the following ajax call)
But if i do the following:
this.getQuote = function() {
$.get('http://finance.google.com/finance/info?client=ig&q=MUTF_CA%3ATDB900', callback);
}
var callback = function(data){
alert(data);
}
It gave me an "500 Internal Server Error". I checked using firebug console.
Did i do something wrong in the ajax call?
Thanks.
As Shadow_boi already guessed, the problem is due to the same origin policiy, which always applies to ajax requests. You need to use JSONP to fix the problem.
See this fiddle for solution: http://jsfiddle.net/cb9c3/
I use JSONP on a client to get data from a server using a WCF service that can return results using HTTP GET (It gets a 'callback' parameter which is a 'function name' and returns callback({data}), you know... JSONP).
Everything works, but if I enable caching (using 'AspNetCacheProfile')on one of the service's operations - then something is wrong, and I'm not sure what...
The way I get the JSONP is by using a function I picked up some time ago from a question here on SO (http://stackoverflow.com/questions/2499567/how-to-make-a-json-call-to-a-url)
function getJSONP(url, success) {
var ud = 'fc_' + + Math.floor(Math.random()*1000000),
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
This creates a random id ('fc_xxxx') then assigns it as a function inside the window object, then use it as the 'callback' parameter for the url of the dynamic javascript that is injected to the document, and then the 'ud' function runs, removes the script and calls the 'success' callback function with the received data.
When using it on normal uncached operations from the service, it usually takes about 200ms to get back the response, and it works ok. The cached responses takes ~10ms -
and I get an error that the 'fc_XXXXX' function is undefined.
It's as if the response is "too fast" for it.
I also tried using jQuery.getJSON() - and, again the callback doesn't trigger.
In all cases when I look at the network traffic in Firebug - I can see the GET request, and I can see that the right data does in fact gets returned.
Does anybody have an idea how can I make it work right with the cached responses...?
I got it! The name of the response-function is different on each call (on both my manual jsonp implementation and that of jQuery).
The name of the function is part of the response from the server (as that's part of how jsonp works...).
So, if the response is a cached response - it will actually return the old name of the function (which will no longer exist on the client's context).
So I just need to give a constant name for the callback function in this case and it should bee fine. :)