Yesod and REST Ajax - ajax

I'm using Yesod to build an Ajax app (using jQuery, though I don't think that matters too much for my question). Basically, what I'd like is for the server to send different representations of the same data depending on whether or not the XMLHttpRequest header got sent. (The point of all of this is to use a javascript library like history.js
In particular, I'd like to have a route like:
/picture/#PictureId GET
Which, when accessed without the XHR header, gets handled by going to the default layout -- or better yet, by a widget which will ultimately get wrapped by the default layout, and when accessed by an XHR request, just sends an HTML representation of the widget.
How should I approach this? I guess I can make a custom defaultLayout-like function to wrap Widgets in logic. Is that sensible, or is there a better approach?
Edit: I decided to override the defaultLayout method in the Yesod class to:
defaultLayout widget = do
req <- waiRequest
let reqwith = lookup "X-Requested-With" $ requestHeaders req
when (maybe False (== "XMLHttpRequest") reqwith) $ do
(PageContent _ _ w) <- widgetToPageContent widget
giveUrlRenderer $ [hamlet| ^{w} |]
...
But now I'm getting a type error I don't quite understand
Couldn't match type `blaze-markup-0.5.1.5:Text.Blaze.Internal.MarkupM ()'
with `()'
Expected type: HandlerT App IO ()
Actual type: HandlerT
App IO (blaze-markup-0.5.1.5:Text.Blaze.Internal.MarkupM ())

You should take a look at this chapter: http://www.yesodweb.com/book/restful-content.

Related

cfajaxproxy is sending invalid parameters?

For some reason that I don't understand, on my development machine can't call to function of a cfc component from a cfajaxproxy.
In my cfm document:
<cfajaxproxy cfc="#Application.CfcPath#.empleado"
jsclassname="ccEmpleado">
This works, and also I can instantiate an object to get all the functions of that cfc component:
var cfcEmpleado = new ccEmpleado();
But, when I try to call a function of that object:
var nb_Empleado = cfcEmpleado.RSEmpeladoNombreBIND(1,1);
Debug complains:
Error: The ID_EMPRESA parameter to the RSEmpeladoNombreBIND function is required but was not passed in.
I got this from Network tab on Chrome and figured out that something is generating an invalid parameter:
http://127.0.0.1/vpa/componentes/empleado.cfc?method=RSEmpeladoNombreBIND&_cf_ajaxproxytoken=[object%20Object]&returnFormat=json&_cf_nodebug=true&_cf_nocache=true&_cf_clientid=41C92098C98042112AE2B3AAF523F289&_cf_rc=0
As you can see, there's a parameter [object%20Object], that is messing around my request, and that's why it fails. I don't why is happening this. Other people has tested this, and it works, but in mine doesn't.
I have Coldfusion 9, Apache, Windows 8. Is is some configuration issue on Coldfusion, or a bug?
I can't tell if this is your error or not, but it might be. This was a problem that we had for awhile. You should consider using explicit names to avoid any confusion. Add the "js" in there.
<cfajaxproxy cfc="cfcEmpleado" jsclassname="proxyEmpleado">
var jsEmpleado = new proxyEmpleado();
I will try to find a link to an article about this very thing.

can't get d3.xml to POST correctly

I tried to POST/GET some Vars to a php-file via AJAX/d3.xml, but a print_r($_POST/$_GET) inside the php, tells me they're empty. Even the example on the doc won't work for me.
d3.xml("xxx.php")
.header("Content-Type", "application/x-www-form-url-encoded")
/*
.get("a=2&b=3", function(error, data) {
console.log(error);
})
*/
.post("a=2&b=3", function(error, data) {
console.log(error);
})
.on("load", createTable(data));
The console tells me that there is a POST request but under POST (on Firefox, not on Chrome) it lists the Vars in one line "a=2&b=3", instead of
a = 2
b = 3
as it usually does. What is it that I'm not getting?
First, apologies for the confusion in the comments. I was looking at the source for an old version of d3. In the newer code, it is indeed true that if you do not provide a callback to d3.xml it returns an xhr request that you can configure directly. (If you do provide a callback, it executes a GET right away as before).
You're going to hate this, so get ready. :) Your issue is because you have an extra dash in your Content-Type header. You have:
application/x-www-form-url-encoded
but it should be
application/x-www-form-urlencoded
Looking at a modified version of your jsfiddle in Firefox, I see the arguments show up in the list view as expected: http://jsfiddle.net/WaT6r/3/

breeze 1.4.8 & angular ajax adapter: how to customize ajax settings?

My code:
breeze.config.initializeAdapterInstance("ajax", "angular", true);
...
var ajaxAdapter = breeze.config.getAdapterInstance('ajax');
ajaxAdapter.defaultSettings = {
method: 'POST',
data: {
CompanyName: 'Hilo Hattie',
ContactName: 'Donald',
City: 'Duck',
Country: 'USA',
Phone: '808-234-5678'
}
};
in line 14813 of breeze.debug.js:
ngConfig = core.extend(compositeConfig, ngConfig);
compositeConfig.method has a value of 'POST' until it is overwritten, because ngConfig.method has a value of 'GET'.
I imagine this question is relevant for any ajax setting, but of course I'm mainly struggling with how to post with the angular ajax adapter, so maybe there's an entirely better way to do that? this approach feels dirty anyway, but breeze.ajaxPost.js only works with the jQuery ajax adapter, right?
6 Oct 2014 update
We recently had reason to revisit ajaxpost and have updated both the code and the documentation.
The original recommendation works. We're merely clarifying and updating the happy path.
A few points:
The ajaxpost plug-in works for both jQuery and Angular ajax adapters.
Those adapters long ago became aware of adapter.defaultSettings.headers and have blended them into your Breeze ajaxpost http calls (take heed, PW Kad).
You must call breeze.ajaxPost() explicitly after replacing the default ajax adapter as you do when you use the 'breeze.angular' service.
You can wrap a particular ajax adapter explicitly: breeze.ajaxPost(myAjaxAdapter); We just don't do that ourselves because, in our experience, it is sufficient to omit the params (breeze.ajaxPost()) and let the method find-and-wrap whatever is the active ajax adapter of the moment.
The documentation explains the Angular use case which I repeat here to spare you some time:
// app module definition
var app = angular.module('app', ['breeze.angular']); // add other dependencies
// this data service abstraction definition function injects the 'breeze.angular' service
// which configures breeze for angular use including choosing $http as the ajax adapter
app.factory('datacontext', ['breeze', function (breeze) { // probably inject other stuff too
breeze.ajaxPost(); // wraps the now-current $http adapter
//... your service logic
}]);
Original reply
AHA! Thanks for the plunker (and the clever use of the Todo-Angular sample's reset method!).
In brief, the actual problem is that breeze.ajaxpost.js extends the jQuery ajax adapter, not the angular ajax adapter. There is a timing problem.
The root cause is that you can't tell breeze.ajaxpost.js which adapter to wrap. It always wraps the default adapter at the time that it runs. As you've got your script loading now, the jQuery adapter is the current one when breeze.ajaxpost.js runs.
The workaround is to set the default adapter to the angular adapter before breeze.ajaxpost.js runs.
One way to do that is to load the scripts as follows ... adding an inline script to set the default ajax adapter to the "angular" version.
<script src="breeze.debug.js"></script>
<script>
<!-- Establish that we will use the angular ajax adapter BEFORE breeze.ajaxpost.js wraps it! -->
breeze.config.initializeAdapterInstance("ajax", "angular", true);
</script>
<script src="breeze.ajaxpost.js"></script>
Clearly this is a hack. We'll look into how we can change breeze.ajaxpost.js so you can wrap any ajax adapter at the time of your convenience.
Thanks for finding this issue, and thanks Ward for bringing it to my attention. I've updated the breeze.ajaxpost.js code to use .data as you described, and added a function you can call after adapter initialization. So now you can do:
var ajaxAdapter = breeze.config.initializeAdapterInstance("ajax", "angular");
ajaxAdapter.setHttp($http);
breeze.ajaxpost.configAjaxAdapter(ajaxAdapter); // now we can use POST
So, it's slightly less hacky.
This answer is applicable to the following plugins and version:
Breeze.Angular v.0.8.7
Breeze.AjaxPost v.1.0.6
I just saw a new plugin called Breeze.Angular.js that can work in conjunction with Breeze.AjaxPost.js
You have to modify the Breeze.AjaxPost.js in order for it to work. Breeze.Angular.js initializes your adapter when your page loads, and Breeze.AjaxPost.js will take in the adapter initialized from Breeze.Angular.js
You can learn more about the Breeze.Angular server here: breeze-angular-service
You can learn more about Breeze.Ajaxpost here: breeze-ajaxpost
Now to set this up wasn't exactly apparent, because I took both files exactly as they were in git.
1.) Reference the files in this order:
<script src="Scripts/q.min.js"></script>
<script src="Scripts/breeze.angular.js"></script>
<script src="Scripts/breeze.ajaxpost.js"></script>
2.) Go into your breeze.ajaxpost.js
Remove this line (or comment this line):
breeze.ajaxpost(); // run it immediately on whatever is the current ajax adapter
The reason why is because, this will cause your ajaxpost method to run before your breeze.angular service. When you go into the ajaxpost method, the ajaxAdapter parameter that is supposed to be passed in will be null. Removing this line appends the functionality for later in your code, so you can call it from the breeze.angular service.
3.) In breeze.angular.js go to your useNgHttp method. It should look like this:
// configure breeze to use Angular's $http ajax adapter
var ajaxAdapter = breeze.config.initializeAdapterInstance("ajax", "angular");
ajaxAdapter.setHttp($http);
breeze.ajaxpost(ajaxAdapter); // now we can use POST
When you run your program, both plugins should be able to set up the environment for you without having to include it in every javascript that makes your calls to the webapi.
Thanks guys for the plugins.

How can I pass a local variable from function to event listener function in JavaScript?

Good day!
I began writing my own basic JavaScript library for personal use and distribution a few days ago, but I am having trouble with one of the methods, specifically bind().
Within the method itself, this refers to the library, the object.
I went to Google and found function.call(), but it didn't work out the way I planned it--it just executed the function.
If you take a look at another method, each(), you'll see that it uses call() to pass values.
I also tried the following:
f.arguments[0]=this;
My console throws an error, saying it cannot read '0' of "undefined".
I would like to be able to pass this (referencing the library--NOT THE WINDOW) to use it in the event listener.
You can see it starting at line 195 of the JavaScript of this JSFiddle.
Here it is as well:
bind:function(e,f){
if(e.indexOf("on")==0){
e=e.replace("on","");
}
if(typeof f==='function'){
/*Right now, 'this' refers to the library
How can I pass the library to the upcoming eventListener?
*/
//f=f(this); doesn't work
//f.call(this); //doesn't work
//this.target refers to the HTMLElement Object itself, which we are adding the eventListener to
//the outcome I'm looking for is something like this:
/*$('h3').which(0).bind(function({
this.css("color:red");
});*/
//(which() defines which H3 element we're dealing with
//bind is to add an event listener
this.target.addEventListener(e,f,false)
}
return this;
},
Thank you so much for your help, contributors!
If, as per your comments, you don't want to use .bind(), rather than directly passing f to addEventListener() you could pass another function that in turn calls f with .call() or .apply():
if(typeof f==='function'){
var _this = this;
this.target.addEventListener(e,function(event){
f.call(_this, event);
},false)
}
Doing it this way also lets your library do any extra event admin, e.g., pre-processing on the event object to normalise properties that are different for different browsers.
So in this particular case you actually want to call JavaScript's built in bind method that all functions have.
f = f.bind(this);
f will be a new function with it's this argument set to whatever you passed into it.
Replace f=f(this); with f.apply(this);
Look at underscore code, here:
https://github.com/jashkenas/underscore/blob/master/underscore.js#L596

ChemDoodle Ajax Incompatibility with Pollen.js

I'm trying to use iChemLabs cloud services from a html5 web worker. Normally the cloudservices requires jQuery but I can't import that into a web worker so I'm using Pollen instead with a ChemDoodle Web Components library with which I have stripped out the document-related things.
jQuery.Hive.Pollen provides a nice ajax function very similar to jQuery, but I can't seem to get it to work at all. I know this problem will be tricky to solve considering that Access-control-headers need to be set to allow any of you to actually find the solution. However, I'm a beginning javascript programmer and I was wondering if my two weeks of frustration is actually a small difference. I am trying to invoke the following function:
var cloudmolecule;
ChemDoodle.iChemLabs.readSMILES('N1(C)C(=O)N(C)C(C(=C1N1)N(C=1)C)=O', function(mol){
cloudmolecule = mol;
});
Here is a link to the library code I am using, see the 'q.ajax' call and substitute jQuery = q for p = q (p is for pollen) in that block of code.
Right now I'm just trying to get the ajax call to work in an ordinary block of javascript with the plan to migrate to a web worker later.
If anybody could point out the problem to me I would be extremely grateful.
solved! turns out iChemLabs rejects these two extra headers that pollen creates:
_xhr.setRequestHeader("X-Requested-With", "Worker-XMLHttpRequest");
_xhr.setRequestHeader("X-Worker-Hive", "Pollen-JS" );
Simply comment them out
Also, Pollen ajax seems to return a JSON object containing the data in JSON format AND as a string, so do
o = JSON.parse(data.string)//data is the parameter to the callback function
The reduced ChemDoodle library (without document-related methods) will work like a charm with pollen ajax.

Resources