Easiest way to consume text returned from a REST service - rest

I need to display on my Web page a simple text string returned from a REST service. I am currently using an XMLHttpRequest:
<div id="returnedText"></div>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.status == 200 && xhr.readyState == 4) {
document.getElementById("returnedText").innerHTML=xhr.responseText;
}
};
xhr.open("GET",url,true);
xhr.send(null);
</script>
Isn't there a lighter way? I considered using a script tag but the Web service in question doesn't support JSONP. I also did a naive attempt with an iframe (putting the REST url as src) but it didn't work.

I did another attempt with iframes and actually this works fine:
<iframe src="url"></iframe>
Where url is the REST service call.
I must have done something wrong the first time (maybe an authentication issue).

Well the iframe route is clunky since you'd be loading the REST response into it and then reaching into it via JS to get the response. What's more, it would cause a visible load in the browser's address bar area. AJAX came along to do away with the iframe hack :)
JSON-P requires about as much setup as AJAX and if your server doesn't support the callback, that's a none starter.
AJAX needn't be thought heavy. Kick it into its own utility function or, even better, use a library, which makes requests like these do'able in one line. jQuery example:
$.get('some/path').done(function(response) { /* do something */ });

Related

Downloading a PDF from an HTTP POST call

Here is what I'm trying to accomplish (IE 9+, Chrome, FF, Safari) without the use of JQuery:
Make an http POST call to my API endpoint with some data
Server dynamically generates a PDF and returns the PDF as a binary attachment
Browser does default download behavior and downloads the PDF without refreshing the page
Basically I want to get the behavior similar to <a href="test.pdf"> but for a dynamically generated PDF after making a POST call instead of a GET call.
I've tried lots of different things, but they either didn't work cross browser (such as using $window.open() with a blob URL), were blocked by popup blockers (any $window call outside of the click scope), or didn't cause the PDF to be automatically downloaded (any $http POST solution).
I finally found one solution that seems to work which creates a form using javascript and submits it.
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', myurl);
var params = {foo: 'bar'};
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
This successfully accomplishes the 3 steps above, but now I've run into a new problem. There is no way to determine when the PDF file has been successfully downloaded. This is preventing me from removing the form and from displaying a friendly 'Please wait...' message to the user. There is also the additional problem that submitting the form cancels any outstanding ajax requests as well which isn't optimal.
I have full control over both the server and the client, so what's the best way to fix this? I don't want to have to save the PDF on the server so passing back a url and doing a second GET request from the client won't work in this case. Thanks!
You can make an server response behave as a download by applying some HTTP headers:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="SOME_NAME.pdf"
Content-Transfer-Encoding: binary
If you're initiating the download through JS only (instead of having the user click a download link), then check out this question for some caveats.
Update: Syntax for POST
Better Update: Form solution with iframe target
You can detect that your server-side script has finished (and subsequently, that the download is ready to begin) by having the form target an iframe. I believe this should also fix the issue of cancelling outstanding Ajax calls, but I'm not certain. Here is the code to do it (just stick this into your code example after the for loop and before document.body.appendChild(form);):
var frame = document.createElement('iframe');
frame.setAttribute('id', 'pdfFrame');
frame.onload = function(){
document.body.removeChild(form);
document.body.removeChild(frame);
alert('Download ready!');
}
document.body.appendChild(frame);
form.setAttribute('target', 'pdfFrame');
You can replace my alert with your code to remove the 'Please wait...'.

Incoming Phone call to make a Popup inside of SugarCRM?

Hello I am trying to make a module that will make a popup window inside of SugarCRM when we receive a phone call. I have seen that some others have accomplished this already (expensive paid modules) and I am hoping to get some insight on the actual popup triggering part....
Our phone system has an API that sends an HTTP post to a URL when we have an incoming phone call.
Inside of SugarCRM, in my Modules code, I am not sure how I can use this HTTP POST from my Phone to do the Popup, the reason is I do not see how it can be fast enough, If I were to set a Cron job to check a page every 1 minute, that would still be too slow.
So does anyone have any ideas how the other similar Phone integration modules are doing it and having the Popup happen almost immediately as the phone call comes in?
Any ideas on how to do such a task? I am planning to do a Desktop application that just sits in the Tray and waits for the POST but seeing others have been able to get the same result inside of SugarCRM without a separate program really interests me.
I am working in a company that has created a expensive paid module to accomplished this, but I can give you hints for 2 ways to achieve this ;-)
1) With GenericHook
in custom/modules create a logic_hooks.php and a YOURCHOICEHERE.php
in the logic hooks create an after ui hook
$hook_array['after_ui_frame'] = Array();
$hook_array['after_ui_frame'][] = Array(1, 'Display Javascript for Telephone','custom/modules/YOURCHOICEHERE.php','GenericHooks', 'displayTelephoneJS');
and in YOURCHOICEHERE.php
class GenericHooks {
function displayTelephoneJS() {
if(!$_REQUEST['to_pdf']) echo '<div id=\"telephone_div\"></div>
<script type=\"text/javascript\" src=\"custom/somewherewhereyouwant/Telephone.js\"/></script>';
// you yould also add a stylesheet here
}
}
in the Telephone.js you can do what ever you want for example:
function Telephone_poll() {
$.post("some.php?poll=1,function(data){
if(data != 0)
{
var result= JSON.parse(data);
//HERE you can do manipulate your telephone_div and populate it with response data "result" from the call to some.php
$('#telephone_div').html("<span>HELLO<span>");
$('#telephone_div').show();
//Here you can also add styles and so on
}
setTimeout("Telephone_poll()", 1000); //restart the function every 1000ms
});
}
Telephone_poll(); //initial start of script
2) An other approach would be creating a demon/service from a php file that reruns itself.
Here you would need some way to identify users and Phones to ensure the popup is displayed for the correct user/phone.

URL fragment lost as part of SAML token authentication; workaround / standard pattern?

Several web application authentication protocols (like WS-Federation and the SAML protocol, i.e., so-called 'passive' protocols, and apparently also ASP.NET Forms authentication, see this StackOverflow question, and AppEngine, see this GWT bug comment) lose the original 'URL fragment', i.e. the part after the #-sign.
What happens is roughly the following: in a clean browser (so no cached info/cookies/login information) I open URL (1) http://example.com/myapp/somepage?some=parameter#somewhere. This makes the browser request (2) http://example.com/myapp/somepage?some=parameter, the server redirects me to my identity provider (including URL (2) in the authentication request), and ultimately I'm redirected back to where I came from, which is URL (2): that is the only URL that the server knows about. But I wanted to go to URL (1), and the URL fragment ('anchor') has been lost along the way, actually in the first step already.
This seems to be a fundamental limitation of these protocols, since the server never sees the URL fragment at all.
I know that it according to specifications that the browser requests (2) from the server, when I navigate to (1), leading to this fragment-losing limitation on the SAML protocol, WS-Federation, etc. My question is: how do I work around this limitation?
The obvious workaround is to avoid URL fragments, as suggested in this answer. However, for our specific web application that is not nice, since we use bookmarkable URL fragments in our single-page GWT application, to make sure that a navigation within our application does not cause the page to reload.
My question: What other workarounds or standard patterns are there for this situation?
(I'm specifically interested in a GWT + SAML protocol solution.)
You basically have two options:
avoid using location.hash (use HTML5's pushState instead, at least on browsers that support it; and/or propose a way to generate permalinks within your app – Google Groups does that)
do the redirection using JavaScript. I.e. instead of sending a redirect from the server, send an empty HTML page with some script that takes the full URL (with the hash) and does the redirection using location.assign() or location.replace(). With a bit of luck (depending on the servers), you'll be redirected to that full URL after authentication.
You can of course do both: if the link is a deep-link into the app, then do the redirect (i.e. assume there's no hash), otherwise send a page with JS to make sure you don't lose any state present in the hash.
And finally the obvious third solution, far from ideal: don't do anything, and try to educate users that when they needed to (re)authenticate then they should re-paste the URL or re-click the link or re-click the bookmark.
According to RFC 1738 anchor tags are not sent by the client to the server, when requesting for a resource.
Anchor tags are used to identify a location within a resource and not a different resource on the server. In order to identify the location in the resource, the client needs to fetch the complete resource from the server, and this process need not involve transfer of information about the fragment (as it does not mean anything to the server).
If you do wish to send the fragment character (#) to the server, then you'll need to encode it in the query string, or the client(browser) will simply ignore that section of the URL when it sends the request to the server.
EDIT:
I don't know any real solution but to work around this issue you need to save your full return URL (with anchor tags) somewhere on the client side, because server don't know anything about anchors. For that you could use SessionStorage (http://www.w3schools.com/html/html5_webstorage.asp) to temporary store ReturnUrl until login process is completed. Please note that it won't be supported on older browsers (like <= IE7).
In that case workaround would look something like this:
<script>
if(typeof(sessionStorage) == 'undefined')
{
sessionStorage = {
getItem: function(){},
setItem: function(){}
};
}
window.onload = function ()
{
var key = 'ReturnUrl';
//try to get last returnUrl with anchors
var returnUrl = sessionStorage.getItem(key);
//if we got something, do the navigation
if(returnUrl !== undefined && returnUrl !== document.URL)
{
//clean it up
sessionStorage.setItem(key, null);
//navigate to last URL
window.location = returnUrl;
}
else
{
//store url
sessionStorage.setItem(key, document.URL);
}
}
</script>
PS. Bear with me if there are some syntax errors because I wrote it down from top of my head and didn't try it.

Simplest example for sending post data via links in Zend Framework

Starting with Zend and I´d like to know what is the simplest way of sending POST data to another page, not by forms, but by some link in my view instead. Thanks :)
You can't send POST data through a link. At least not through a normal link. Link can only carry GET data.
If you need to send POST over a link it's most certainly a design flaw.
If you're 100% sure, that you need it, you can do that using jQuery and onclick event. It`s not possible to do it without javascript. Other option would be to send it using form with hidden fields with single submit button visible - that would even work without javascript.
Normal hyperlinks in HTML are sent with GET requests and are not supposed to change the state of the resource being accessed. This is known as being idempotent. You can repeat the request over and over, and the result of each succeeding request to the same URL is the same as the first one.
POST requests don't have this restriction and are intended for when the user needs to change something (such as creating a new resource.)
It's not possible to send a POST request via a normal HTML link. And even if you find a way, it breaks an almost universal expectation that web users have. What are you trying to accomplish? Maybe there's a better way.
But to answer your question, you could use something like jQuery to capture the "click" event and make it do a POST request:
$('.my-link').click(function() {
var url = $(this).attr('href');
var data = {};
$.post(url, data, function() {
window.alert('success!');
});
return false;
});
If your URL has any query parameters, i.e. "?foo=bar&baz=bum", then you'd probably need to strip them off of the URL and pass them as a second parameter to the $.post() function. This is left as an exercise for the reader. ;-)

Jquery ajax post headers question (I think)

I think this is easy, but I'm not sure what the right syntax is. I am posting a form via JQuery ajax - you know
$j.ajax({
type: "post", etc.....
But I need to make sure the form is capable of being processed if Java is disabled. Is there a "header" in the ajax send that can be used to identify it as aposed to a normal post so that on completion whether ajaxed or normal php post I can return to the sending page. If not ajaxed I can use if($update): header('location: ...'); endif; but if I use that with the ajax request it stops the ajax success function. Hope makes sence
Yes, jQuery sets a custom header when doing an AJAX request:
X-Requested-With : XMLHttpRequest
EDIT russp's server side PHP code:
define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if( IS_AJAX_REQUEST )
{ //This is an AJAX request, do AJAX specific stuff }
else
{ //This is not an AJAX request }
Don't really know about the headers, but maybe the easier solution is to simply call the url of the processing page with an extra parameter when you're doing it in an ajax context?
The page can then simply check if the parameter is present or not and take appropriate action, depending on it.
You'll have to do a lot or working around, but you can use a combination of <noscript> and javascript code to get what you need.
See WWW FAQs: How do I detect JavaScript in the user's browser?
Hope that helps you get started.
The usual way to handle ajax form requests is to write the form to work without any kind of JS so if you are in a basic php file you would start with
<?php
if(count($_POST) > 0) {
//process form entries
} else {
//output form
}
?>
Then you would add some jQuery to hijack the submit click so
$('input[type=submit]').live("click", function(e) {
e.preventDefault();
//ajax post here
//IE
return false;
});