AngularJS $http.jsonp Geoserver with custom callback - javascript

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

Related

response undefined when calling google api thru emberjs

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.

Javascript: How did I get here? (Viewing data sent by server, non-AJAX.)

I've got a React-based app that works like this: The user makes a request for "foo", the server returns basic page info (applicable to all pages on the site), and when the client receives this (DOMContentLoaded), it does an AJAX call for the internal details "foo" and renders that.
But is it possible, if I send the data on the first request, to skip the AJAX call? (I tried this previously but was very new to React, which is how I came up with the current scheme. It's come up again because now I'm handling previously saved items.) So, I'm in my DOMContentLoaded listener, and I can see (in the Browser|Network|Response area of Chrome) all the data that has been sent by the server. It's everything I need, and it's right there, but I can't find a way to access it in Javascript.
The searches I've done have almost all turned up AJAX requests. (I am using JQuery, if that helps.) Obviously I can handle loading saved data using the same gag I'm currently using, and maybe that's a an all-around better approach.
So, once again, the question is: Is it possible to look at the response from a non-AJAX place? If it is possible, is it advisable?
Update: Let me walk through an example scenario.
The user goes to "/foo".
The server response is {:some "json"}.
In the Javascript onReady, I can do this:
console.log(window.location);
and I'll see "/foo". But can I see {:some "json"}? And how? Contrast with the AJAX call version:
The user goes to "/foo".
The server response is nothing (i.e., a 200 but no body).
The Javascript onReady has:
$.ajax({
url: "/foo/data"
type: "GET",
success: function (req) {...} //req has {:some data} in it!
So, when I make an AJAX call, I get the request. Is there any way to get that {:some data} on a non-AJAX call? This doesn't work, but I could see something like:
x = window.response();
or
x = Response.last();
Neither of those things exist, of course. I hope that clarifies what I'm looking for.
You could drop a script tag on your server-rendered page that includes a global var accessible by your script bundle. e.g.,
<script>
var myGlobalVar = { ... server data ... } <!-- // note: this is rendered raw by your server
</script>
<script src="myScriptBundle.min.js"></script>
Or, alternatively you could look into server-side rendering, which is possible with React. Check out the implementation in Redux: http://redux.js.org/docs/recipes/ServerRendering.html

transormRequest only for a specifc request in angularJS

I wanted to pass multipart/formdata through a $resource in angular in order to post an image.
I followed the magic answer founded here AngularJS: Upload files using $resource (solution)
But this solution apply for all requests in my modules. And I want it to apply only for one $resource or two. If possible I want to keep JSON for the others requests. In fact I'm using nested properties and I would like to keep it.
Is here any way to do it ?
Thanks
As per $request documentation, the transformRequest() can be applied per method; you will have to redefine the method though. Some sample code would be:
var MyResource = $resource("url", {
myPost: {
method: "POST",
transformRequest: function(data) {
// code from http://stackoverflow.com/questions/21115771/angularjs-upload-files-using-resource-solution
}
}
);
This is the barebone setup, you will probably need some adjustments. It would be used as (again the simplest case):
MyResource.myPost(formData); // formData contains properties and the image(s)

Prototype AJAX Post Parameters missing randomly

Alright, so i have a .NET application that uses the Prototype library to make AJAX calls to webmethods in the page-behind to retrieve data. This application has been up and running for quite awhile with no issues. Recently a new user began using the application and experiencing some weird issues.
Basically, what happens is he can use the application fine for awhile and then it just starts throwing errors on AJAX calls stating parameters are missing to the webmethod. Here is the error:
System.InvalidOperationException - Unable to perform the requested action: Invalid web service call, missing value for parameter: 'fleet'.
at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary'2 parameters)
at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary'2 parameters)
AT SYSTEM.WEB.SCRIPT.SERVICES.RESTHANDLER.INVOKEMETHOD(HTTPCONTEXT CONTEXT, WEBSERVICEMETHODDATA METHODDATA, IDICTIONARY`2 RAWPARAMS)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)
It isn't just one call that messes up but any ajax call randomnly and it always seems to be the first parameter in the webmethod that is called "missing." leading me to believe the post data isn't gettin back somehow? (related?: JQuery Ajax post parameters sometimes not sent on IE).
I have never been able to recreate this issue, nor has any other user experienced it. This leads me to believe it is something specific on this users system that is causing the issue. Unfortunately they are a rather important user so i need to attempt to solve this problem. The user has IE8 as their browser. Here is the code that makes the ajax call using prototype:
function gAjax(url, params, onSuccess, onError, onException, onComplete) {
new Ajax.Request(url,
{
method:'post', //Post
contentType:"application/json; charset=utf-8", //As JSON
postBody:Object.toJSON(params), //Post Body is JSON string
sanitizeJSON:true, //Sanitize the JSON
onComplete:onComplete, //Set user on complete
onSuccess:onSuccess, //Set user on success
onFailure:onError, //Set user on error
onException:onException //Set user on exception
});
}
onComplete, onSuccess, onError, onException are function callbacks. params is an object like the following:
{'fleet':'fleetVal','bin':1234}
Url is the method, such as Bin.aspx/LoadBinInfo. This method is defined in the backend as follows:
<System.Web.Services.WebMethod()> _
Public Shared Function LoadBinInfo(ByVal fleet As String, ByVal bin As Integer) As Dictionary(Of String, Object)
'.....
'Returns a dictionary of info
End Function
If anyone has any ideas as to what is happening i would greatly appreciate any input! I can't seem to find any information in my research to lead me to the possible cause. Again it seems to only happen to this one user, so maybe its a browser setting on his end (any ideas what setting?). But then again its sporadic for him even, but once it starts happening it happens constantly until he closes out the browser and starts over.
I'm answering here because it seems I don't have enough reputation as to comment rather than answering.
It's not very clear what is missing from the request, but I'd go on checking the web logs (or setting some sort of logging) to see what the system is actually receiving. According to your description of the problem, the request is somehow missing the 'fleet' parameter. But you are not sending such value isolated in the request, you're sending all data in the post body as a serialized JSON string.
So, either the data passed to gAjax is not correct/complete, or something strange is happening on your server.
I obviously suspect that it's the former, but anyway you should try to log and debug on both ends.
For a start, I'd do something like this:
function gAjax(url, params, onSuccess, onError, onException, onComplete) {
params['debug']=Object.toJSON(params);
new Ajax.Request(url,
//....
That will add the JSON string to the request so you can check exactly what is being sent.
Hope this helps!

Can I add a parameter to a PrototypeJS Ajax request using Ajax.Responder?

I'm trying to secure my AJAX calls by appending a session token (to be matched by a browser cookie by the server) as a parameter to every single AJAX request made from my web app.
I'd like to avoid having to specify the token as an additional parameter in every single Ajax.Updater() request, as that could get onerous very quickly. So I thought it might be more effective to have this token appended to every request globally, automatically.
I'm wondering whether Ajax.Responder could handle this. It seems as though it should be able to intercept any Ajax request before it's made, and modify the parameters to add the token before it's sent out. But, I have no idea how I'd go about accomplishing it. Would I need to prototype 'Ajax.Responder', and 'burn in' an additional parameter? Or is there an easier way?
My understanding of Ajax.Responder is a little weak, so if somebody could clarify why this would or wouldn't be possible in their answer, it would be greatly appreciated.
I ran into a similar problem, and ended up implementing a simple addParameters() method extension for the Ajax.Request class to get this done for both GET and POST requests.
You can check out the implementation here: https://gist.github.com/3212413.
Feedback welcome!
Prototype sets the parameters array before it calls the Responders callbacks so you can't just add the item you want to the parameters hash. You could append your variables to the url, for example this will add a cache buster random number to every request...
Ajax.Responders.register({
onCreate: function(o,x) {
o.url += (o.url.include('?') ? '&' : '?') + "rnd=" + Math.floor(Math.random()*1000000000);
}
});
this is how I implemented for a POST request, inspired by Gavin's answer:
Ajax.Responders.register({
onCreate: function(request) { // add form_key to ajax request
var formKey = $('form_key');
var parameters = request.parameters;
parameters.form_key = formKey.value;
request.options.postBody = Object.toQueryString(parameters);
}
});

Categories

Resources