Ajax: How to get request? - ruby-on-rails

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

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?

#Html.CheckBoxFor onchange actionlink

How can I make the code below an on change actionlink? So when I check the checkbox it will trigger an actionlink!
#Html.CheckBoxFor(c => OutOfBank.Available)
You can send an Ajax request when Checkbox changed, which triggers the action each time you check or uncheck the checkbox.
#Html.CheckBoxFor(c => OutOfBank.Available)
<script>
$(function () {
$('#Available').change(function () {
$.ajax({
url: '/example/#OutOfBank.Available',
cache: false,
method: 'GET',
success: function (data) { alert('success'); },
error: function () { alert('error'); }
});
});
});
</script>

jQuery UI Autocomplete get input element on source function

Is there any way to get input element on Autocomplete source function? $(this) not referring to input of autocomplete instance.
jsFiddle sample here.
<input type="text" data-code="foo" placeholder="type something ..." class="suggest" />
<input type="text" data-code="foo2" placeholder="type something ..." class="suggest" />
JavaScript
$(".suggest").autocomplete({
delay: 100,
source: function (request, response) {
// get foo here,: $(this).data("code"); not working
// Suggest URL
var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
suggestURL = suggestURL.replace('%QUERY', request.term);
// JSONP Request
$.ajax({
method: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data){
response(data[1]);
});
}
});
this.element gets the current element on source function.
$(".suggest").autocomplete({
delay: 100,
source: function (request, response) {
this.element.data("code");
// Suggest URL
var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
suggestURL = suggestURL.replace('%QUERY', request.term);
// JSONP Request
$.ajax({
method: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data){
response(data[1]);
});
}
});
Working sample here

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>

jquery change function on dropdown value

I have a dropdown in my view to which i want to apply jquery(ajax onChange value). So that JSon data passed for the selected value by controller action rendered over the same view by replacing some id of that view
Dropdown
<div><select id="package_master" name="package_master"><option value="">
--select package--</option>
<option value="1">JPMC Package1</option>
<option value="2">JPMC Package 2</option>
<option value="3">JPMC Package1</option>
<option value="5">Select Package</option>
<option value="6">Select Package</option>
</select></div>
What i am presently doing is
<script type="text/javascript">
$(function () { //$(document).ready(function () {
$("#package_master").change(function () {
var value = $('#package_master').val();
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Test/getPackageDetails/")",
data: "packageID="+value,
success: function(data){//here i want to Replace come id with json data passed by action
</script>
url is url: "#Url.Content("~/Test/getPackageDetails/")",
Complete Above script
Updated:I used following script to accomplish my task which is working fine too, but data is displayed in array format like ["abc","xyz"]Now here i need help to format json data in row format i.e 1 row for each array element like abcxyz
`
<script type="text/javascript">
$(function () { //$(document).ready(function () {
$("#package_master").change(function () {
var value = $('#package_master').val();
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Test/getPackageDetails/")",
data: "packageID="+value,
success: function(data){
$("#packageDetails").html(JSON.stringify(data));
},
error: function(data){
alert("Request couldn't be processed. Please try again later. the reason "+data);
}
});
});
});
`
<script>
$(function () {
$("#package_master").change(function () {
var data = { packageID: $(this).val() }
$.post("url", data, function (backdata, status) {
// callback, do something
}, "json");
});
});
</script>
<script type="text/javascript">
$(function () { //$(document).ready(function () {
$("#package_master").change(function () {
var value = $('#package_master').val();
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Test/getPackageDetails/")",
data: "packageID="+value,
success: function(data){
data = $.map(data, function (item, a)
{
return " "+item+ "<br>";
});
$("#packageDetails").html(data.join(""));
},
error: function(data){
alert("Request couldn't be processed. Please try again later. the reason "+data);
}
});
});
});
jQuery ajax function has an option: dataType: "json"
Since you are using JSON.stringify(data) you need this parameter as dataType: "text"
So there's no need for JSON.stringify(data).
$(function () { $(document).ready(function () {
$("#package_master").change(function () {
var packageID = $('#package_master').val();
$.post("#Url.Content("~/Test/getPackageDetails/")", {packageID : packageID}, function (data) {
$("#packageDetails").html("");
$.each(data,function(i,field){
$("#packageDetails").append(i+1+" "+field+"<br/>");
});
}, "json");
});
});
Alternatively you can use
$("#packageDetails").$(selector).load(url,data,function(response,status,xhr))
for other solutions, see here. And I'd recommend to avoid using $.ajax if you have some alt.

Resources