AJAX returns net::ERR_CONNECTION_REFUSED - ruby-on-rails

I am having a RAILS API.
when i am calling from terminal it is giving proper results. Now i am trying to call from external application to that API.
CURL:
curl -H 'Accept: application/vnd.marketplace.v1' http://api.market_place_api.dev:3000/users/1
About CURL is working properly.
Now my external file is code is:
1234.html
<!DOCTYPE html>
<html>
<head>
<title>API Testing</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" crossorigin="anonymous"></script>
<script type="text/javascript">
$.ajax({
headers: { Accept : "application/vnd.marketplace.v1"},
url: "http://api.market_place_api.dev:3000/users/1",
type: 'GET',
contentType: 'application/json',
data: { auth_token: "Vb6BQdPQNx9uD_wczkeW"},
success: function (data) {
alert(JSON.stringify(data));
$('div.jsonoutput').append(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
</script>
</head>
<body>
<div><center><p><strong>API Request & Response Testing</strong></p></center></div>
<div class="jsonoutput"></div>
</body>
</html>

Add these lines to application_controller
Controller:
protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' }
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
Script:
<script type="text/javascript">
$.ajax({
url: "http://api.market_place_api.dev:3000/users/1",
type: 'GET',
contentType: 'application/json',
data: { auth_token: "Vb6BQdPQNx9uD_wczkeW"},
success: function (data) {
alert(JSON.stringify(data));
$('div.jsonoutput').append(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
</script>

Related

Get Birthday Information using user.birthday.read scope

We have followed the steps mentioned as per the https://developers.google.com/identity/sign-in/web/server-side-flow. But while trying to fetch the date of birth information using 'scope': 'https://www.googleapis.com/auth/user.birthday.read', we are getting payload as below:
payload{"at_hash":"-mvIlEROpJsQSF9rQpRDfA","aud":"<CLIENT_ID>","azp":""<CLIENT_ID>"","email":"sample#gmail.com","email_verified":true,"exp":1628092721,"iat":1628089121,"iss":"https://accounts.google.com","sub":"108685651390298470023","name":"mnbvc plm","picture":"https://lh3.googleusercontent.com/a/AATXAJwejAC1r2SasgNdtqpd6f5q_Ih2-vDiTxELWDhg=s96-c","given_name":"mnbvc","family_name":"plm","locale":"en-GB"}
Please find below the index.html file we are using:
<!DOCTYPE html>
<html>
<head>
<meta name="google-signin-client_id" content="<CLIENT_ID>">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer>
</script>
<script>
function myFunction() {
auth2.grantOfflineAccess().then(signInCallback);
}
</script>
</head>
<body>
<button onclick="myFunction()" id="signinButton">Sign in with Google</button>
<script>
function renderButton() {
gapi.signin2.render('signinButton', {
'scope': 'https://www.googleapis.com/auth/user.birthday.read',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': start
});
}
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.getAuthInstance({
client_id: '<CLIENT_ID>',
scope: 'https://www.googleapis.com/auth/user.birthday.read',
access_type: 'offline'
});
});
}
function signInCallback(authResult) {
if (authResult['code']) {
var authcode = 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: '/gplus.form?authcode='+authcode,
// 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>
What else change is required at JAVA side to get the birthday information?

Writing javascript function from ruby string in hash

I have ROR Helper that build some Javascript code.
In the helper I have Hash of options and variables that define this javascript code.
One of them is string that holds JS function, the problem is it rendered as a string and not as function when using to_json.
How can I make it work?
Example:
In my helper I have this code:
h = {url: '/some/url', async: false}
h[success] = "function(result) {alert(result);}"
"<script type='text/javascript'> jQuery.ajax(#{h.to_json}); </script>"html_safe
This code will generates:
<script type='text/javascript'>
jQuery.ajax({
url: '/some/url',
async: false,
success: "function(result) {alert(result);}"
});
</script>
What I wont to to achieve is that code (without the ".." in success part):
<script type='text/javascript'>
jQuery.ajax({
url: '/some/url',
async: false,
success: function(result) {alert(result);}
});
</script>
You could create a string out of h hash instead of using to_json; for example:
def js_code
h = {url: '"/some/url"', async: false}
h[:success] = "function(result) { alert(result); }"
s = h.map { |k, v| "#{k}: #{v}" }.join(",")
"<script type='text/javascript'> jQuery.ajax({#{s}}); </script>".html_safe
end
Notice that additional double quotes (") were added to '"/some/url"' in order to keep them in the final string.
Output:
<script type='text/javascript'> jQuery.ajax({url: "/some/url",async: false, success: function(result) { alert(result); }}); </script>
I would do that using heredoc syntax and string interpolation:
def some_helper_method
h = { url: '/some/url', async: false }
<<-HTML
<script type='text/javascript'>
jQuery.ajax({
url: '#{ h[:url] }',
async: #{ h[:async] },
success: function(result) {
alert(result);
}
});
</script>
HTML
end
The easiest way would be to remove the surrounding quotes with a regular expression like this.
"<script type='text/javascript'> jQuery.ajax(#{h.to_json}); </script>".gsub(/"success":"(.*)"/, '"success":\1')
which gives
<script type='text/javascript'> jQuery.ajax({"url":"/some/url","async":false,"success":function(result) {alert(result);}}); </script>
Which is not complety what you want.
I would just build a string instead of using the json approach.
html = %Q{
<script type='text/javascript'>
jQuery.ajax({
url: '#{h[:url]}',
async: #{h[:async]},
success: #{h[:success]}
});
</script>
}

Ajax: How to get request?

<p><input type="button" id="ajax" value="click here!"/><br/>
<script type="text/javascript">
$(function () {
$('#ajax').click(
function () {
$.ajax({
type: 'get',
url: 'https://example.com',
success: function (data) {
alert("OKAY");
},
error: function (data) {
alert("NG");
}
});
});
});
I want to GET request using Ajax in Rails but sent options request.
This is an error shown console log
OPTIONS https://example.com 405 (Method Not Allowed)

jquery-ui autocomplete position

I am using jquery-ui autocomplete to retrieve items from a SQL database which is working fine but I would like to move the autocomplete list to another part of the page.
I have been trying to use the Position option from here but cant seem to get the correct syntax when applying to my code?
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCity").autocomplete({
source: function (request, response) {
var param = { cityName: $('#txtCity').val() };
$.ajax({
url: "test.aspx/GetCities",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
event.preventDefault();
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
}
});
});
</script>
I wanted to move the autocomplete box to the right hand side of the textbox.
After a nights sleep my first attempt again this morning worked fine, think I had originally only missed a comma in one of my attempts yesterday.
I just stripped it back to a basic implementation using an array instead of the ajax call and then applied the working syntax to my code.
Wasted FAR too much time on this yesterday, just shows taking a step back and time away from the screen helps work things out!
Thanks for your help
Working code for the record:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery AutoComplete TextBox Demo</title>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
</head>
<body>
<form id="form1" runat="server">
<div><h1>AutoComplete Textbox</h1>
Software
<asp:TextBox TextMode="multiline" Columns="50" Rows="5" ID="txtCity" runat="server"></asp:TextBox>
</div>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCity").autocomplete({
source: function (request, response) {
var param = { cityName: $('#txtCity').val() };
$.ajax({
url: "test.aspx/GetCities",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
position: {
my: "left center",
at: "right center",
},
select: function (event, ui) {
event.preventDefault();
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
}
});
});
</script>
</body>
</html>

How to change image for login button for OAuth windows live Id?

I have develop code for live Id OAuth in my system. I want to chang the image provided by windows live Id.
How can i change it.
More over, When I do login once, it will automatailly alert the login detail when it i load the page again. (F5) before i click on button.
What is the reason?
My code is.........
<div>
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
var APPLICATION_CLIENT_ID = "myclientId",
REDIRECT_URL = "myredirectURl";
//WL.Event.subscribe("auth.login", onLogin);
WL.init({
client_id: APPLICATION_CLIENT_ID,
redirect_uri: REDIRECT_URL,
response_type: "token"
});
var scopesArr = ["wl.signin", "wl.postal_addresses", "wl.phone_numbers", "wl.emails"];
WL.ui(
{
name: "signin",
element: "signInButton",
scope: scopesArr
});
function userContactInfo(sesion) {
var postalAddresses, phoneNumbers, emailAddresses;
WL.api(
{
path: "me",
method: "GET"
},
function (response) {
if (!response.error) {
alert('hello name:' + response.first_name);
alert('hello email:' + response.emails['preferred']);
$.ajax({
type: "POST",
url: "Login.aspx/SaveFacebookAutoSignUp",
data: "{ 'Name':'" + name + "', 'EmailId':'" + email + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("You have successfully sign in.Please Wait, we redirect you in a second.");
alert(data);
}
});
}
});
}
function onLogin() {
var session = WL.getSession();
if (session) {
userContactInfo(session);
}
}
function onLogin1() {
WL.Event.subscribe("auth.login", onLogin);
var session = WL.getSession();
if (session) {
userContactInfo(session);
}
}
</script>
<div id="signInButton">
</div>
Here is the code I use for call the sigin with a button, after, you can add the image you want, hope this help:
<body>
<input id="login" type="image" src="Images/Image.png" onclick="login();"/>
</body>
<script type="text/javascript">
var APPLICATION_CLIENT_ID = "xxxx",
REDIRECT_URL = "xxxx";
WL.Event.subscribe('auth.sessionChange', function (e) {
document.getElementById('login').innerHTML = (e.status === "connected" ? "Sign out" : "Connect");
});
WL.init({
client_id: APPLICATION_CLIENT_ID,
redirect_uri: REDIRECT_URL
});
function login() {
if (WL.getSession() === null)
WL.login({ scope: "wl.signin" });
else
WL.logout();
}
</script>

Resources