ColdFusion 11 with websockets can't publish a message - javascript

I'm trying to get websockets working with ColdFusion. I am unable to send or receive messages and I am at a loss as to why. Am I missing something? Do I need to have any other programs installed? I am using Adobe ColdFusion Builder 3 Developer Edition.
Here is the code I am attempting to use.
Websocket.cfm
<cfwebsocket name="mycfwebsocketobject" onmessage="MessageHandler" subscribeto="stocks" >
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function MessageHandler(message)
{
alert(message.data);
}
function publishstock()
{
mycfwebsocketobject.Publish('stocks', 'I sent a message!');
}
setInterval('publishstock()',1000);
</script>
Application.cfc
<cfcomponent>
<cfset this.name="Websocket">
<cfset this.wschannels=[{name="stocks"}]>
</cfcomponent>
My goal is to get the MessageHandler function to trigger without explicitly calling it. I have no idea what is wrong and I have matched my code up perfectly with many examples on the web. I have been unsuccessful in both Chrome and Firefox.
I think that the real problem might have something to do with my machine. I found a demo online that worked perfectly, but when I downloaded the source it no longer worked. Is there a way to test for this?
Resources:
https://www.youtube.com/watch?v=Ys6BGrYJhNg
http://www.adobe.com/devnet/coldfusion/articles/html5-websockets-coldfusion-pt1.html

Your setInterval('publishstock()',1000);
Should be:
setInterval(function(){publishstock();},1000);

Related

Not a valid origin for the client from Google API Oauth

I'm receiving this error from Google API Oauth:
idpiframe_initialization_failed", details: "Not a valid origin for the client: http://127.0.0.…itelist this origin for your project's client ID
I'm trying to send a request from this local path:
http://127.0.0.1:8887/
And I already added this URL to the Authorized JavaScript origins
section:
This is my code:
<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<!-- END Pre-requisites -->
<!-- Continuing the <head> section -->
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'MY CLIENT ID.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
//scope: 'https://www.google.com/m8/feeds/'
});
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function() {
// signInCallback defined in step 6.
auth2.grantOfflineAccess().then(signInCallback);
});
</script>
<!-- Last part of BODY element in file index.html -->
<script>
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
<!-- ... -->
</body>
</html>
How can I fix this?
Reseting Chrome cached solved it for me. Long press on Reload button, then Empty Cache and Hard Reload.
Note: Make sure your Chrome Dev tools panel is open otherwise long press wont work.
I had a very similar issue to yours. I tried to add multiple whitelisted ports from localhost and nothing was working. Ended up deleting the credentials and setting them up again. Must have been a bug on googles end for my setup.
If it's all the same to you, try adding http://localhost:8887 to your authorized JavaScript origins instead. Had that error myself at some point and this fixed it. Know that you will have to use this URL for your request as well event though it translates to http://127.0.0.1:8887/.
I read on several places on the web people use to redo the creation of the credentials to get it to work.
So I did, I created a new credential for the same project and used my new user-id and it worked perfectly... Looks like the edition of the whitelist is a bit flacky...
Nb: I also used localhost instead of 127.0.0.1, IPs are not valid.
I fiddled around for about 10 minutes and then it finally worked when I tried
http://localhost/ in the browser (instead of 127.0.0.1)
Added the url at every place you can do white-lists at:
https://console.developers.google.com/apis/credentials/
I had this same issue; but this is what worked for me:
Open console.developers
Open the project name
Click on the credentials
Under the "name", click on the "web client 1"
Under the "URLs", add "http://localhost:3000"
just my 2 cents.. was able to get it working after deleting and recreating the credentials. Just as suggested above.
In case anyone missed this, next to the save button it does say:
Note: It may take 5 minutes to a few hours for settings to take effect
Waiting fixed this issue for me.
"Not a valid origin for the client" seems to be over-used by Google's API, i.e. it's misleadingly used for authentication errors too.
For people seeing the error, check that the credentials are correct.
(This might explain why it works for some people after re-creating credentials - in some cases, the original credentials might not have been correct).
I solved via adding both http://localhost and http://localhost:8083.
Okay so this is super embarrasing, but for me I was following the docs for the Google Sign-in Web package for a Flutter app, and where it says:
On your web/index.html file, add the following meta tag, somewhere in the head of the document: <meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">
I had copied what was listed as my Client ID and pasted it at the beginning and had therefor duplicated the apps.googleusercontent.com portion of the content label in the meta tag. So it might help to make sure you haven't duplicated that!
I just went through all of these solutions before realizing I was putting in
https://localhost:3000
and my dev server was serving up
http://localhost:3000
Stupid, I know, but someone else will probably make the same mistake and perhaps this comment will help them :)
What worked for us was adding a non-localhost domain to the authorized origins. My colleague had his localhost-domains working after adding a non-existing local domain, e.g. http://test-my-app.local.
It might be in case, while you are using same email id for creating client id and for sign-in through webpage

jQuery ajax get response not parsed or not seen

The problem is that jQuery does not receive the response by the server, and I can't figure out why. This is my setup, Windows 7 64bit:
ext.js:
$('#button').click(function(){
var string= $('#string').val();
$.get('http://localhost:3000',
{"input":string},
function(data){
alert(data);
$('#feedback').text(data);
});
})
099.html:
<doctype html>
<html lang="en">
<head> <!-- charset title style -->
<meta charset="uft-8"/>
<title>jQuery 099</title>
</head>
<body><!-- tables, div's bad, html 5 is better: -->
<input type="text" id="string" value=""/>
<input type="button" id="button" value="ajax"/>
<br/>
<div id="feedback"></div>
</body>
<script type="text/javascript" src="./js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="./js/ext.js"></script>
</html>
server.js:
var express = require('express');
var app = express();
app.get('/', function(req, res){
console.log("got");
console.log(req.query.input);
var content = req.query.input;
res.send(content);
});
app.listen(3000);
I run node 0.10 from command line using
C:\dev\nodejs\0.10\servers\stackoverflow>node server.js
In my FF browser i type
http://localhost:3000/?input=hi
and i get a blank screen containing hi,
which is good. Also node.js prints got and then hi on the command line
I run 099.html from notepad++ > run > chrome > so it runs on a completely other drive but surely it doesn't need to be in a server, right? When i type something XYZ the textfield and click ajax button, node responds on the console XYZ, which is good: the request is discovered by node, so it would send a response, but i don't see the response in my html.
The expected behavior was an alert and my div gets filled in the html and displays XYZ.
What obvious point am i missing?
I'm stuck for 2 hours now and couldnt find a similar question perhaps because of my not knowing jquery.
ps the 099 is from the newboston youtube tutorial and jquery is from the jquery site. i don't know the express version, it's a fairly new one.
ps2: the jquery $.get() api is too vague:http://api.jquery.com/jquery.get/ states: "A callback function that is executed if the request succeeds." well, can i conclude that the request succeeded because the nodejs console reacted to it, and if so, why did the callback function not execute.
ps3: the last argument is dataType, perhaps node responds in a way $.get did not expect? any datatype suggestions?
EDIT: yesterday i dusted off my tomcat and put the above files into it and jquery runs like a charm.
How stupid of me, assuming that a file on a disk can communicate over http to a server, what was i thinking.
the essence of ajax is "listening for the asynchronous response" (for example http://msdn.microsoft.com/en-us/magazine/cc163479.aspx), so the file needs to reside in something that establishes an IP address of some kind obviously. Sorry for polluting the Internet, case closed.
You cannot alter port number when issuing ajax request - this is Same origin policy restriction. See what you can do with SocketIO instead.

executing js via cfhttp

Im trying to execute a some JS code via a background task.
Im using a gateway which works similar to paypal, i.e. once payment details are taken a response is sent back to a listener on my server (this could be immediate or several minutes later)
Once a response is received by the listener (listener.cfm), using cfhttp im calling a file (runPixCode.cfm) which has some trigger code.
Because runPixCode.cfm is not rendered by the browser the JS is not executing.
Also to prove whether this worked or not, im getting the JS to call another file (provethisiscalled.cfm) which write a log to a txt file.
If i put the following straight after the cfhttp call, i can see an entry in the log file. This assures me there is no issue with the JS providing its rendered by the browser.
<cfoutput>#cfhttp.FileContent#</cfoutput><cfabort>
However, doesnt work with a background task. I dont know how else to deal with this, any suggestions appreciated.
listener.cfm
--Does a bunch of logic--
<cfif paymentsuccessful>
<CFHTTP URL="www.mysite.com/runPixCode.cfm" METHOD="post" timeout="12" resolveurl="true">
<CFHTTPPARAM NAME="TrackingId" VALUE="#trackingId#" TYPE="FormField">
</CFHTTP>
</cfif>
runPixCode.cfm
<SCRIPT language="JavaScript">
var axel = Math.random()+"";
var a = axel * 1000;
document.write('<IFRAME SRC="http://www.mysite.com/provethisiscalled.cfm?codearea=landing&num='+ a + '?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>');
</SCRIPT>
<NOSCRIPT><IFRAME SRC="http://www.mysite.com/provethisiscalled.cfm?codearea=landing&num=1" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME> </NOSCRIPT>
provethisiscalled.cfm
<cfloop collection=#ARGUMENTS.triggerParams# item="key">
<cfset docLogging = docLogging & chr(13) & "#key# = " & ARGUMENTS.triggerParams[key]>
</cfloop>
<cffile action="append" file="c:\serverlocation\someDir\triggerlog.txt" output="#docLogging#" addnewline="YES" >
Writing an iframe is not going to work, nor is javascript, because all of these processes are being called by applications, not by browsers.
So with that, you have to get creative. First, what are you really attempting to do?
If your purpose is to determine whether or not a file has been called or executed, use <cflog> or write an entry to a database.
If you are trying to pass an HTTP call from listener.cfm to runPixCode.cfm, use <cfhttp> instead of an iframe.
If your purpose is actually to execute JavaScript as part of this automated process (it isn't, but this is cool), you can execute JavaScript in your CF/Java server through Rhino, which is not incredibly simple, but you can get code snippets by googling. Rhino is included with ColdFusion as js.jar, so there are no special files to download to make it work.

calling a webservice error

I am trying to follow the this tutorial ( http://www.codeproject.com/KB/webservices/CallWebServiceFromHtml.aspx ) and learn to call a web service from a web page. However, I´m getting an error in the Firebug console:
service is not defined
InitializeService() onload() event =
load
service.useService("http://tm.a...smx?WSDL",
"TryggMedisinWebService");
This is the relevant code I´m using.
<script language="JavaScript">
function InitializeService() {
service.useService("http://tm.arnett.no/tryggmedisinwebservice/tryggmedisinwebservice.asmx?WSDL", "TryggMedisinWebService");
}
var spm, kategori, fylke;
function SendQuestion(){
spm = document.send_question.spm.value;
kategori = document.send_question.kategori.value;
fylke = document.send_question.fylke.value;
service.TryggMedisinWebService.callService("Send_Question", spm, kategori, fylke);
}
function ShowResult(){
alert(event.result.value);
}
</script>
<body onload="InitializeService()" id="service" style="behavior:url(<?php bloginfo('template_directory'); ?>/webservice.htc)" onresult="ShowResult()" <?php body_class(); ?>>
I would appreciate any help i can get on troubleshooting this.
Thanks!
This is using .htc file and as far as I know it's supported only by IE browsers.
To have it work in other browsers, switch to using ordinary AJAX - for example jQuery provides excellent interface.
Here is link to good article explaining how to consume web service using jQuery:
http://www.c-sharpcorner.com/UploadFile/sridhar_subra/116/
Didn't personally test it, but from what I've seen the information there is accurate and to the point.

ExternalInterface

Hey, so I'm having a bunch of trouble getting ExternalInterface to work, which is odd, because I use it somewhat often.
I'm hoping it's something I just missed because I've been looking at it too long.
The flash_ready function is correctly returning the objectID, and as far as I can tell, everything else is in order.
Unfortunately, when I run it, I get an error (varying by browser) telling me that basically document.getElementById(<movename>).test() is not a valid method.
Here's the code:
javascript:
function flash_ready(i){
document.getElementById(i).test('success!');
}
Embed Html (Generated):
<script type="text/javascript">
swfobject.embedSWF("/chainmaille/includes/media/flash/upload_image.swf", "/chainmaille/includes/media/flash/upload_image", "500", "50", "9.0.0","expressInstall.swf", {}, {allowScriptAccess:'always', wmode:'transparent'},{id:'uploader_flash',name:'uploader_flash'});
</script>
<object type="application/x-shockwave-flash" id="uploader_flash" name="uploader_flash" data="/chainmaille/includes/media/flash/upload_image.swf" width="500" height="50"><param name="allowScriptAccess" value="always"><param name="wmode" value="transparent"></object>
AS3 :
package com.jesseditson.uploader {
import flash.display.MovieClip;
import flash.external.ExternalInterface;
import flash.system.Security;
public class UI extends MovieClip {
// Initialization:
public function UI() {
Security.allowDomain('*');
ExternalInterface.addCallback("test", test);
var jscommand:String = "flash_ready('"+ExternalInterface.objectID+"');";
var url:URLRequest = new URLRequest("javascript:" + jscommand + " void(0);");
navigateToURL(url, "_self");
}
public function test(t){
trace(t);
}
}
}
Swfobject is being included via google code, and the flash embeds just fine, so that's not the problem.
I've got a very similar setup working on another server, but can't seem to get it working on this one. It's a Hostgator shared server. Could it be the server's fault? Anybody see any obvious syntax problems?
Thanks in advance!
The Flash isn't actually finished constructing yet. You're calling your flash_ready callback from the constructor, and so the JS is trying to call in before the object is on the stage. Move your flash_ready call to, say, an Event.ADDED_TO_STAGE listener and it should start working.
Ok, so after further investigation, it appears that there was a problem with multiple instances of the flash object, because I was cloning it to a lightbox. I have gotten it working now.
Just spent 5 hours fighting with this. It was all really frustrating. In my case the solution was very very simple and I would have never guessed it.
So first of for all of you who have never seen the flash player debugger running on files inside your browser finding this link that walks you through the setup has resulted in a somewhat magical experience :)
Now to my ExternalInterface discovery: There was a sandbox violation inside the same domain. This meant that flash cannot access www.yourdomain.com from yourdomain.com. The weird thing of course is that you are not explicitly calling the domain with ExternalInterface.
Anyhow, the solution was very simple: add this to my .htaccess file and that was it!
# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) http://www.youtdomain.com/$1 [R=301,L]
Hope this helps someone
Is flash_ready receiving the objectID that you are expecting?
Also, why use:
var jscommand:String = "flash_ready('"+ExternalInterface.objectID+"');";
var url:URLRequest = new URLRequest("javascript:" + jscommand + " void(0);");
navigateToURL(url, "_self");
When this is designed to do that:
ExternalInterface.call("flash_ready", ExternalInterface.objectID);
Post your source (pre-generatred). When your browser says [Flash].Method is not a function, 99% of the time it means that you tried calling a function in Flash before the .swf was ready for it. I see that you tried to do that, but clearly its not working so something must be off. So post your pre-rendered source and I am sure we can find the problem.

Categories

Resources