jQuery ajax get response not parsed or not seen - javascript

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.

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

ColdFusion 11 with websockets can't publish a message

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);

Angularjs' $http.get only executed once in IE11

I'm learning angularjs, and as a test project I'm polling a server that returns a list of active processes (their pids) and displaying these.
The client code looks like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/angular/angular.js"></script>
<script>
function ProcessCtrl($scope, $http, $interval) {
$scope.ReloadData = function() {
var result = $http.get("processdata", {timeout:1000});
result.success(function(data,status,headers,config) {
$scope.processes = data;
});
}
$scope.ReloadData();
var stop = $interval(function(){$scope.ReloadData()}, 1000);
}
</script>
</head>
<body ng-app>
<div ng-controller="ProcessCtrl">
Processes:
<ul>
<li ng-repeat="process in processes">
{{process.pid}} is running
</li>
</ul>
</div>
</body>
</html>
This works in Firefox and Chrome, but not quite in Internet Explorer 11.
All browsers execute the ReloadData method every second, but IE11 doesn't actually fetch the process data from the server. Firefox and Chrome do fetch the data every second. I can see this also in the output from my server, which logs every request.
All three browsers execute the code in result.success, but IE11 keeps reusing the old data it got the first time, where FireFox and Chrome use the newly fetched data.
I've checked the web console in IE11 for warnings or errors, but there are none.
Edit:
As the chosen answer suggested it was a caching problem. I have made the server add a 'cache-control' header to the response with the value 'no-cache'. This has solved the problem.
It's possible that the request is cached, as it is valid to cache GET requests. FF and Chrome probably have disabled caches, because of running dev tools or other reasons. You could append a timestamp as url query string "processdata?" + (new Date()).getTime() to see if it is a caching problem.
Prettier ways to prevent IE caching can be found here:
Angular IE Caching issue for $http
I prefer to use $http.post in order to prevent any cache.

Issue using jQuery to do a google maps api call (JSON not being returned)

This is the code I was originally using and worked perfectly fine up until yesterday (which is when I noticed it but I am unsure when it actually stopped working for sure). I know this was working at the beginning of last week so sometime between then and yesterday it broke. I am running this code within a RAD called Alpha Anywhere but have tested it outside of this program (in just a HTML page) and it still didn't work. Hoping someone knows if there is a bug or if there is something I can do to fix this issue. I ran this in firefox with firebug on and that is where I saw the error letting me know that the JSON wasn't retrieved.
var $jq = jQuery.noConflict();
$jq.getJSON('http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false',function(results){
// I have code in here to calculate miles driven per state
// (as in the above code origin and destination would be filled
// with variables but I went with this basic call because even this doesn't work).
});
This following code does not work (as of right now November 11, 2013 at 10:26 PM CDT) when running it in firefox or chrome. With firebug on it shows I am not getting a response from google. However this following code does respond when ran in safari 7.0.x on Mac OSX 10.9.
<!DOCTYPE html>
<html>
<head>
<script src="http://api.jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.9.1.min.js"></script>
<script>
function getData() {
var url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Huntsville,AL&destination=Atalanta,GA&sensor=false';
var $jq = jQuery.noConflict();
$jq.getJSON(url, function (results) {
alert(results.routes[0].legs[0].distance.value);
});
}
</script>
<title>jQuery Debug of Google API</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<button onclick="getData();">click</button>
</body>
</html>
There are a couple problems here:
First, from jsonp explained:
As you may be aware you cannot directly load data files from another domain. This is a security issue that has been around for a long time and is commonly solved by sharing data through an API, REST or such. However there are ways around this ... [for example] JSONP
To do this in jQuery:
Using $.ajax, add dataType: 'jsonp', which appends callback=? to the URL
Using $.getJSON (shorthand for .ajax), add callback=? at the end of the requested URL.
That indicates that we want to use JSONP. Remove it and a vanilla JSON request will be used; which will fail due to the same origin policy.
Another issue is that some external APIs (like Google Maps Directions API), don't automatically serve JSONP. If the server doesn't know what to do with the callback parameter then the response from the API will still be JSON, not JSONP. In order to ensure the returned content is formatted correctly, you can go through a proxy server like the jsonp.guffa.com
To use it, change the request to http://jsonp.guffa.com/Proxy.ashx?url=YourEncodedURI
Where you have replaced YourEncodedURI with the encoded requested url string.
Putting it all together:
var mapsUrl = 'http://maps.googleapis.com/maps/api/directions/json' +
'?origin=Toronto&destination=Montreal&sensor=false';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl = 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodedUrl;
$.ajax({
url: proxyUrl,
dataType: 'jsonp',
cache: false,
success: function (data) {
console.log(data);
}
});
Working Demo in jsFiddle
Further Reading:
What is JSONP all about?

How to use web sockets

I'm trying to make use of Easy Websockets to come up with a chat application.
http://easywebsocket.org/
Here's the code I have right now. As you can see, I'm trying to log the message on the console every time I click on the send button. It works when I open it up on 2 browsers. But it only works for less than 1 minute.
<input type="text" id="txt"/>
<input type="button" value="send" id="sends"/>
<div id="messages"></div>
<script src="jquery171.js"></script>
<script src="easywebsockets.js"></script>
<script>
var socket = new EasyWebSocket("ws://sample.com/resource");//I do not understand this part
socket.onopen = function(){
socket.send("hello world.")
}
socket.onmessage= function(event){
console.log(event.data)
}
$('#sends').click(function(){
var txt = $('#txt').val()
socket.send(txt)
});
</script>
I got this error log from firebug:
I don't really understand what this all means. Is there something I need to setup in order to make this work?
It usually happens when the client doesn't use the same protocol version as the server. The server should specify what version it uses, socket.io by default goes with RFC6455 but it can be overridden to go with older hybi-0x.
So, check the following:
client & server implemented protocol versions
origin (e.g. localhost) is permitted by server
firewalls, internet security suites, zonealarms, that kind of stuff

Categories

Resources