transormRequest only for a specifc request in angularJS - javascript

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)

Related

AngularJS $http.jsonp Geoserver with custom callback

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

AngularJS JQuery Ajax form submission Equivalent

Lately I have jumped into angularjs and its wonderful so far. I have been sending AJAX requests through $http service. Today I was shocked to find that there is no simple way to do it (to the best of my knowledge). Seaching through google and SO took me nowhere with convoluted complex solution.
Though I ended up using JQuery for now, am curious if something like JQuery ajax, capable of sending form is really available. Here is simple JQuery code to illustrate what am talking about
$.ajax({
type: "POST",
url: formUrl,
data: formData,
success: function(data)
{
$scope.form = $sce.trustAsHtml('<div class="alert alert-success">Succesfully Registred. You will be taken home in 5 seconds!</div>');
$timeout(function(){
$window.location.href= "#home";
}, 10000);
}
});
There is an equivalent in angular, here is a link to a jsfiddle with an example implementation: http://jsfiddle.net/dmcquillan314/boo5tn62/
The function on line 11 is an example of how to send a request to a rest api:
$scope.sendToResource = function() {}
To enable this feature just change the function in the directive to point to this factory and it will send a request to the api url configured in the factory.
In order to test this with an api you'll have to change the factory to match your server
here are some links to relevant documentation:
https://docs.angularjs.org/api/ngResource/service/$resource
https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/auto/service/$provide
Let me know if anything is unclear or you require any further explanation. Hopefully this should help you get started.

How do I assign a JSON response from this API I'm using to elements on my page?

I'm trying to use the API from https://developer.forecast.io and I'm getting a JSON response, this is the first time I'm using an API and all I really need to know is, how do I assign the JSON response I get back from their API to elements on my page. Thanks!
This is done with a script-tag in my header:
script(src='https://api.forecast.io/forecast/APIKEY/LAT,LON')
http://api.jquery.com/jQuery.ajax/ you need to add a success callback, at the bottom of that page are examples you can look at.
EDIT
ok i saw that you are using a script tag with the request, since the api is outside your current domain you need to make a JSONP request
$(document).ready(function(){
$.ajax({
url: 'https://api.forecast.io/forecast/APIKEY/LAT,LON',
dataType: 'jsonp',
success: function(data){
//do whatever you want with the data here
$("body").append(JSON.stringify(data));
}
});
});
off course you need to make some tweaks to that piece of block but you get the idea
What you're looking for is DOM manipulation. DOM is the HTML Document Object Model, an object representation of the HTML comprising a document. There are a lot of ways to go about this, but one of the more popular Javascript libraries for performing this task is jQuery. See their help documentation category on manipulation for more information.
OK, based on your clarification, you're not yet using AJAX. I say "not yet", because you're going to need to. Again, I'll recommend jQuery for that, and their own documentation as the best resource. For a simple "get", your easiest option is the getJSON method.
So, at a very simple level you might do something like:
$(function(){
$.getJSON('url_to_api', function(data) {
$("#SummaryBox").append("<div>" + data.hourly.summary + "</div>");
}
});

YUI 3 - Set global request headers for Ajax

I've mostly worked with jQuery before and I'm new to YUI. I wish to set a custom header for each Ajax request using either IO or DataSource in YUI 3. I want the header to be inserted automatically for each request. In jQuery I could accomplish this with $.ajaxPrefilter like so:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var value = 'blah';
if (value) {
jqXHR.setRequestHeader("My-Custom-Header", value);
}
});
I found these pages in the online documentation for YUI 3 but I just don't "get it". How can I accomplish this?
http://developer.yahoo.com/yui/3/examples/io/io-get.html
http://developer.yahoo.com/yui/3/api/io.html
Check out the "header" method in the io module: API docs
I haven't tested it, but you should be able to do something like this:
YUI().use('io', function(Y) {
Y.io.header('X-My-Header', 'My Custom Value');
Y.io(/*...*/); // Should have the X-My-Header HTTP header
});
Note that this will only apply to the current YUI instance. So if you have another YUI().use(/.../) statement, you'll need to set the header again.
If you need it to provide headers across instances, you should define your own module that wraps the Y.io functionality. Check out this gist to get a sense of what that entails.
I honestly don't think it is good idea to do it "JQuery style". Either way you need to provide configuration object, so few more characters doesn't make much difference.
But the worst part is that when someone else will see your code he will not have idea where the additional headers come from and he will probably waste hours of his life.
If you still want to have default headers somewhere, do it Javascript way like so:
Y.myDefaultIOCfg={"My-Custom-Header":value}
...
var cfg=Y.merge(Y.myDefaultIOCfg, {
method: 'GET',
data: 'foo=bar'
})
request = Y.io(uri, cfg)
This way you explicitly say that you are using some object as a pattern for the config object and additional header definition can be found there.
I don't know YUI syntax very well, but try this:
YUI().use("io-base", function(Y) {
var cfg, request;
cfg = {
methos: 'GET',
data: 'foo=bar',
headers: {
'My-Custom-Header': value
}
}
request = Y.io(uri, cfg);
});

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