Json response is not coming while using jggrid in grails - grails

I am using jqgrid with grails first time and facing some problem.i set up jggrid in my gsp as below
<link rel="stylesheet" href="${resource(dir:'css',file:'ui.jqgrid.css')}" />
<link rel="stylesheet" href="${resource(dir:'css/ui-lightness',file:'jquery
ui-1.8.23.custom.css')}" />
<g:javascript library="jquery-1.7.2.min"/>
<g:javascript library="jquery.jqGrid.min"/>
<script type="text/javascript">
$(document).ready(function() {
jQuery("#g-grid").jqGrid({
datatype: "json",
mtype: 'GET',
url: '${createLink(controller: 'roadmap', action: 'listRequestsAsJSON')}',
colNames: ['Entry Type', 'Life Cycle Status'],
colModel: [
{name:'roadMapEntryTypeCode',index:'roadMapEntryTypeCode', editable:'true'},
{name:'lifeCycleStatusCode',index:'lifeCycleStatusCode',editable:'true'}
],
pager: jQuery('#g-pager'),
viewrecords: true,
gridview: true
});
});
</script>
and the code in the controller for getting the response is
def listRequestsAsJSON = {
def r = AssetRoadmap.findAllByAsetIDAndRoadMapEntryTypeCode(Asset.get(10033), CodeConstants.ROADMAP_ENTRY_TYPE_CODE_LIFECYCLE, [sort:"roadMapEventStartDate", order:"asc"])
def jsonCells = r.collect {
[ id: it.id,
cell: [
it.roadMapEntryTypeCode,
it.lifeCycleStatusCode
]
]
}
def jsonData= [rows: jsonCells]
render jsonData as JSON
}
When I looked the response in Firefox (using with Firebugs) I am not seeing in it as response but when I manually render the jsp in browser I am getting
{"rows":[{"id":10172,"cell":["LIFECYCLE","DESTROY"]},{"id":10173,"cell":["LIFECYCLE","ARCHIVE"]},{"id":10174,"cell":["LIFECYCLE","CONTAINMENT"]}]}
which seem to me correct so not sure where is the problem,Any help will be greatly appreciated.Thanks!!!

The request was actually redirecting the request to some other place so the json response was not coming.I got this clue with 302 status,a good learning though

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?

Ajax Call from Basic HTML page For a Footer In Rotativa

Can I make an Ajax Call to my Controller and Action method to get some data, from a HTML page instead of CSHTML page.
I have exactly the same content but instead of cshtml, I want to use a HTML page.
If Yes, please give me a sample code.
EDIT
The Actual Problem was different and I'm sorry for being unclear About it.
The Actual problem is I'm trying to generate a PDF using Rotativa.
And i wanted to add a footer to it and it contains some dynamic part.
string header = System.IO.Path.Combine(HostingEnvironment.ContentRootPath, "Views/Home/header2.html");
string footer = System.IO.Path.Combine(HostingEnvironment.ContentRootPath, "Views/Home/Footer.html");
string customSwitches = string.Format("--header-html \"{0}\" " +
//"--header-spacing \"0\" " +
"--page-offset 0 --header-right \"Page: [page] of [toPage]\" " +
"--footer-html \"{1}\" " +
"--footer-spacing \"10\" " +
//"--footer-font-size \"10\" " +
"--header-font-size \"10\" ", header, footer);
var pdfResult = new ActionAsPdf("CreatePDF1", headerData)
{
FileName = "quotation.pdf",
PageOrientation = Orientation.Portrait,
PageSize = Size.A4,
CustomSwitches = customSwitches
};
The Following is my Footer.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="icon" href="~/Assets/Images/logo.png" />
<link href="~/css/cupertino/jquery-ui.css" rel="stylesheet" />
<link href="~/css/cupertino/theme.css" rel="stylesheet" />
<script src="~/js/jquery-2.1.3.js"></script>
<script src="~/js/jquery-ui-1.11.3.js" type="text/javascript"></script>
</head>
<body>
<div id='divContent'></div>
</body>
</html>
<script>
$.ajax({
url: "/Quotation/ReturnFooterData",
type: 'get',
async: false,
success: function (data) {
document.getElementById("divContent").innerHTML = data;
},
error: function (data) {
document.getElementById("divContent").innerHTML = "error";
}
});
</script>
That part data should be present in the PDF at the footer.
Here the ajax call what I make doesn't hit the action method.
This was my actual problem, and my apologies for not providing the exact information about the problem.
Yes, something like
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
contentType: "application/json",
dataType: 'json',
type: 'POST',
url: '/Shop/FilterRinglet',
data: data,
success: function (result) {
//alert("success");
}
});
});
</script>
inside your html.
DonĀ“t forget to load jquery in your head section:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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 $.ajax Request works in IE but not FF and Chrome

The following JQuery Request works fine in IE but not in FF and Chrome.
I am running the following page from its file location e.g. file:///C:/Test/json.htm and requesting a page running on localhost.
What is the reason for this?
And how can I get it to work for FF and Chrome?
<body>
<input type="button" value="Search" id="search-button" />
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function() {
$('#search-button').click(function() {
var parms = {
id: 27
};
$.ajax({
type: 'POST',
url: 'http://localhost:51621/Test/GetJSONMessage/',
async: false,
data: parms,
dataType: 'json',
success: function(data, testStatus) {
alert(data.message);
}
});
});
});
</script>
</body>
Where GetJSONMessage is supplied by an ASP.Net MVC JSonResult :
[HttpPost]
public JsonResult GetJSONMessage(int id)
{
return Json(new { message = ("hello world " + id.ToString()) });
}
Because you're hosting from the filesystem, and making a request to localhost, Chrome and FF will see this as a cross domain request, and therefore a security issue.
If you type the URL directly into the location bar, you'll probably get your response.
Safari is a little more easy going about those "security issues" when you're hosting from the filesystem.

Resources