I'm trying to implement a custom Google Hangouts app and am stuck trying to pass the Hangouts ID from the Hangouts app to my own app. Hangouts runs on Google's server so I believe it's a cross domain issue.
I have this code in the body of my custom Hangouts app, which is loaded in an iframe in the overall Hangouts window:
<body>
<script>
var postHangoutId = function(hangoutId) {
console.log("in function(hangoutId)");
$.post({
url: "https://www.myserver.com",
crossDomain: true,
dataType: "json",
data: {
"hangouts_id" : hangoutId
},
success: function( response ) {
console.log( response ); // server response
}
});
}
gapi.hangout.onApiReady.add(function() {
console.log("gapi.hangout.onApiReady.add");
postHangoutId(gapi.hangout.getHangoutUrl().split('/').pop());
});
window.onload = function() {
console.log("hangouts load");
console.log("onload getURL" + gapi.hangout.getHangoutUrl());
}
</script>
My App
The main goal is to get the Hangouts ID and Post it to my server. Nothing seems to be happening, so I've littered the code with console.log statements. The header, "My App", is displayed, so at least I know the custom app is running.
However, when I open Chrome's Developer Tools on the opened Hangouts window and go to the Console tab, this is all I see:
I've removed my AJAX call and rerun the app to make sure, and these errors are still there, so they aren't related to the AJAX call. As you can see, none of my logs are here. What am I doing wrong?
You need to use JSONP as dataType in jQuery Ajax Cross Domain Requests
Javascript Security blocking the requests in your code
$.post({
url: "https://www.myserver.com",
crossDomain: true,
dataType: "jsonp",
data: {
"hangouts_id" : hangoutId
},
success: function( response ) {
console.log( response ); // server response
},error : function(err){console.log(err)}
});
Related
I'm developing a java based web application. In my application, there are some data that needs to be fetched without page reload. So, I'm using AJAX in jquery framework.
Note: I'm using tomcat web server
$(document).ready(AjaxFunction);
function AjaxFunction(){
$.ajax({
type: "GET",
url : "/DemoApp/sampleData.txt",
beforeSend: function(xhr){
xhr.setRequestHeader("some-custom-header","my-name");
},
//headers: { 'some-custom-header': 'myname' },
success : function(){
console.log("Working !!!");
},
complete : function(){
setTimeout(AjaxFunction, 5000);
}
});
}
Actually the ajax request is successful. But when I try to inspect the request header using the chrome developer tools, I cannot able to find the Request header.
Expected behaviour:
Here we can see that, Request headers is available for dropArea.html
I expect the same for sampleData.txt
Actual behaviour:
Here, Request headers is not available for sampleData.txt
Issue:
The first ajax is working properly in the main.js, the second one is doing its job at first look but I think there might be a bug somewhere. I can reach the getProducts method after I click to the button.
The product_list.html file should appear on the browser screen, but it doesn't.
I get no error message on the front-end or the back-end.
This is what I noticed: After click to the button -> F12 -> Network -> products -> I can see here a status code: 200 and the product_list.html file content as response.
In case the POST ajax call succeeds and in the case I add: location.href = "/products";, the browser will load product_list.html
I use the get ajax call because i need to pass the jwt token in the req header. (I deleted the jwt authentication parts from the code below because I narrowed down the error to the $.ajax() and res.sendFile() relationship)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //I can see in the console
res.sendFile("product_list.html", {root}) //It doesn't render the html
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What causes the issue and how to solve it?
Thanks!
file should appear on the browser screen
No it does not and it should not. The file should be returned to the ajax function call in the success callback:
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
success: function (file) {
// The file is in the "file" variable above.
// Do whatever you want with it. For example you can replace
// the current page with the returned file:
document.body.innerHTML = file;
}
});
That is the whole point of AJAX - a mechanism for programmers to override the normal flow of HTTP requests that loads the response to the browser page. If it allows you to not load the response to the browser page it also means it will not automatically load the response to the browser page - because doing so will not allow you to not load the response.
If you want to automatically load the response then don't use ajax:
// Replace $.ajax(... with:
window.location.href = "http://localhost:8000/products";
However, this method does not allow you to set custom request header.
in your frontend code you do nothing with the GET /products response
the backend sendfile as the name says it just sends the file over to the requester. Being an ajax call, it must be rendered by the frontend code.
Add something like success: response => $('body').html(response)
I have created and deployed my own webservice (WCF C#). I would like to call it using JavaScript, get data and populate a Chart.
Here is the code I pasted inside of a confluence HTML macro:
<script>
function fun()
{
var request = $.ajax({
url: "http://mydomain:port/MyService.svc/testRest",
data: "m=aa",
processData: true,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (e) {
console.log('error ' + e.status + ' ' + e.responseText);
}
});
}
var x = fun();
console.log(x);
</script>
The error I receive via developer console on Google Chrome (F12):
Mixed Content: The page at 'https://myconfluencesite.com/mypage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://mydomain:port/MyService.svc/testRest?m=aa'. This request has been blocked; the content must be served over HTTPS.
I have already whitelisted the service URL http://mydomain:port/MyService.svc/testRest. Assuming I activate SSL on my domain, would that fix the issue? Are there better methods?
The main idea is to load/populate tables/charts with external data. So I first started with my own service which returns a JSON structure. If that works, I can then use that structure to populate/load a HighCharts component for example.
Change http://mydomain:port/MyService.svc/testRest to https://mydomain:port/MyService.svc/testRest. Google Chrome, rightly, does not like that you have a page served through https which then calls a service using http. So, yes, activating SSL and using it will fix the issue. I would even say that no service should ever use a non-secure channel. Have your service require ssl.
I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!
I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
});
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation?callback=run');
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);