Writing javascript function from ruby string in hash - ruby-on-rails

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

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?

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

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>

Ajax call on separate js file

I can use ajax call on *.cshtml file as below.It's working properly.
$.ajax({
url: '#Url.Action("GetAllBooks", "Book")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
But How can I call same method on seperate *.js file ?When I used above code it's not working?
CSHTML (I prefer the tag input):
#* without the attribute 'name' *#
<input type="hidden" value="#Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks" />
#* or *#
<div style="display:none;" data-url="#Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks"></div>
JS:
var url = $('#UrlBookGetAllBooks').val();
//or for tag div
var url = $('#UrlBookGetAllBooks').data('url');
$.ajax({
url: url,
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
HTML - Contains data- attributes
<div id="ExampleDiv"
data-url = "#Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>
HTML - Option 2
<div id="ExampleDiv"
url-Val = "#Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>
JQuery - Contains data- attributes
var Url_Value = $('#ExampleDiv').data('url');
JQuery - Option 2
var Url_Value = $('#ExampleDiv').attr('url-Val');
Ajax Call
$.ajax({
url: Url_Value,
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
For such solution, I recommends you to create a JavascriptController with a "JavascriptActionResult" or a new "JavascriptActionResult" on the BookController along with the view that outputs the desired javascript. That way you can write Javascript dynamically with razor and also have garantee that the Route Pattern behavior of your MVC will be followed. With all that set, the page would be:
<script type="text/javascript" src="#Url.Action("GetAllBooksJS","Book")"></script>
PS: There is not a native JavascriptActionResult in MVC, but you could extend the ActionResult to perform that or simple force a Content-Type in the classic ActionResult function.
Bellow is a working case that Ive made in MVC3.
Controller:
public class BookController : Controller
{
//
// GET: /Book/
public ActionResult Index()
{
return View();
}
public JsonResult GetAllBooks() {
return Json(new[] { new { name = "Book1" }, new { name = "Book2" } });
}
public ActionResult GetAllBooksJS()
{
Response.ContentType = "text/javascript";
return View();
}
}
Index View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="#Url.Content("~/scripts/jquery-1.7.1.min.js")"> </script>
<script type="text/javascript" src="#Url.Action("GetAllBooksJS","Book")"></script>
</head>
<body>
<div>
<button>Get books ajax</button>
</div>
</body>
</html>
GetAllBooksJS View:
#{
Layout = null;
}
$(document).ready(function(){
$('button').on('click',function() {
GetBooksAjax();
});
});
function GetBooksAjax() {
$.ajax({
url: '#Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetAllBooksJS View v2, In this second version the Javascript, as soon as it is loaded by the Index view, will engage the Ajax Call, I guess thats your case:
#{
Layout = null;
}
function GetBooksAjax() {
$.ajax({
url: '#Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetBooksAjax();

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