Passing parameters to the View - From Grails to Javascript - javascript

From my Controller i am passing a parameter to the view.
When i print the parameter from the Body it gets printed correctly. However, if i try to print the parameter from a Javascript function it doesn't work.
How can i correct this ?
Controller
def showpeople(Long id){
def pInstance = People.get(id)
render (view: "showpeople",model: [pInstance: pInstance])
}
View
<script>
$(document).ready(function(){
var str = ${pInstance.stringval}; // <--- DOESN'T WORK
alert (str); // <--- DOESN'T SHOW ALERT
)}
</script>
<body>
${pInstance.stringval} <--- PRINTS SUCCESSFULLy
</body>

The reason why your alert doesn't show is you are outputting that value as a constant instead of a valid String within javascript. You really need to wrap it in quotes and you should also encode the string value for use with javascript.
For example:
var str = '${pInstance.stringval?.encodeAsJavaScript()}';
alert(str);

Related

C# JSON String returned in ambiguous format

i have an issue with my logged Json String as it replaces the double quotes with "
Controller Code :
var message = new SuccessMessagesVM()
{
Title = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? "It's beautiful" : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
Message = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? CustomModel.Resources.SuccessMessagesResources.AddFormSuccess : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
ColorCode = (int)EnumHelper.MessagesCodes.Success
};
var json = JsonConvert.SerializeObject(message);
ViewBag.SuccessMessage = successMessageType == 0 ? null : json;
Javascript just logs the ViewBag.SuccessMessage as following:
console.log('#ViewBag.SuccessMessage');
and the object is displayed as {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
replacing all single quotes with ' and all double quotes with "
I expect the output to be {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
This is because you are using ViewBag variable.
In order to use ViewBag, you can write it as followed:
First, in view:
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var successMessageJson = jss.Serialize(ViewBag.SuccessMessage);
}
Then use it:
<script>
//use Json.parse to convert string to Json
var successMessageInfo = JSON.parse('#Html.Raw(successMessageJson)');
</script>
There's a few different issues and a few different approaches, and the OP doesn't give us any view code, so it's a bit of guesswork.
My feeling is that you should just return the SuccessMessagesVM from your method, and access the properties individually in your view (probably using #Html.DisplayFor and HTML). This will ensure that any redundant quotation marks are never created in the first place, and will give you total control over how the values are displayed.
You should not expect console.log(#ViewBag.Anything) to display properly. If you need the data as a JavaScript object, don't stick it in the ViewBag, as it will get rendered as HTML.
If you must write to a JavaScript object you can, but it begs the question why are you not using an ajax request if all you want is data?

Passing Javascript generated variable as parameter to Craft function

I have a javascript generated string called latlongParam and I want to pass it into a twig statement (Craft CMS). For example, if I write in my script:
<script>
...
var test = "{{craft.smartMap.lookupCoords('Dundas Street East Toronto ON M5B 2G9 Canada').lat}}"
...
</script>
then test becomes "-79.3804367". However, I want to pass in latlongParam param as so :
var test = "{{craft.smartMap.lookupCoords(latlongParam).lat}}"
I have tried doing: "{{craft.smartMap.lookupCoords('" + latlongParam + "').lat}}";
But I keep getting the following error before the page even loads:
Impossible to access an attribute ("lat") on a boolean variable ("")."
since
Due to the fact that "{{craft.smartMap.lookupCoords('" + latlongParam + "')}}"; becomes an empty string for some reason and i end up with "".lat
Does anyone know how i can pass this javascript generated string inside of lookupCoords()?

Using Handlebars object in JavaScript

I want to pass an entire object right into javascript, but it doesn't seem to work.
I tried the {{{data}}} approach and the {{data}} approach like recommended in another post.
I'm doing something like this in the handlebars file:
<script>
var myData = {{data}}; // or even {{{data}}}
</script>
Both of these give me the exception: Uncaught SyntaxError: Unexpected Identifier.
However if I do a
var myDataUrl = "{{data.url}}";
It works fine, but for the first case it prints out "[Object Object"]. Any thoughts on how I can make case 1 work?
To insert Javascript data directly into template, you need to make it into a legal javascript string and pass that string into the template. It needs to be legal Javscript before it gets to the template. Using something like JSON.stringify() is one such way to make legal Javascript, but it isn't the only way.
Here's a piece from a handlebars template of mine that inserts some javascript data structures into the HTML file:
<script>
// temperature data - array of arrays of the form [dateTime, atticTemp, outsideTemp]
var temperatureData = {{{temperatures}}};
// onOffData is an array of [dateTime, str] - where str is "on" or "off"
var onOffData = {{{onOffData}}};
</script>
And, the data passed to the template looks like this (the two method calls return JSON strings):
app.get('/chart', function(req, res) {
var tempData = {
temperatures: data.getTemperatureDataSmallJSON(),
onOffData: data.getFanOnOffDataSmallJSON(),
units: req.cookies.temperatureUnits
};
res.render('chart', tempData);
});
This results in a piece of an HTML file that looks like this:
<script>
// temperature data - array of arrays of the form [dateTime, atticTemp, outsideTemp]
var temperatureData = [[1412752013861,22.19,16.35],[1412753505591,22,16.15],[1412754286561,21.85,15.94]];
// onOffData is an array of [dateTime, str] - where str is "on" or "off"
var onOffData = [[1411786960889,"off"],[1411790853867,"off"]];
</script>
Note, I'm turning the data into JSON and passing that JSON string into the template.

Underscore Template does not get rendered. Why?

I have a template for Underscore.js that does not get rendered. My problem is explained in this JSFiddle.
// this string will get loaded by an ajax call and put in a variable when the application starts
var allTemplates = '<section id="header">header template</section> <section id="content"><% var test = 10 %><%= test %></section>"';
// put it in the DOM to parse it with jQuery
$('#test').html(allTemplates);
var getSpecificTemplate = function(templateID) {
return $('#test').find('#' + templateID).html();
};
var templateData = getSpecificTemplate('content');
// expected log output: 10
// actual log output: <% var test = 10 %><%= test %>
console.log( _.template(templateData, {}) );
// why?
This setup equals pretty much my code. What could be the problem? Why is the template even encoded?
If I understand you correctly, you're not evaluating your template, you're appending a literal string.
Change this: $('#test').html(allTemplates);
to this:
var templateString = _.template(allTemplates, {});
$('#test').html(templateString);
Then you will see the expected outcome in your console.log(), also in your console.log() you can simply put the following:
var templateData = getSpecificTemplate('content');
console.log(templateData);
Fiddle: http://jsfiddle.net/KyleMuir/my3NW/6/
Hope this helps!
Your approach is perfectly fine. What you have missed on is the call to .html().
Your templateData variable is messed up because .html() in this line -
return $('#test').find('#' + templateID).html();
escapes the content. Change .html() to .text() and this should work.
http://jsfiddle.net/q5Q7e/
Edit: CORRECT APPROACH -
The above doesn't work because .text() only gets the 'text', skipping the elements.
What you need to do is, add your template in a script tag and not section tag. This way,
when you make a .html() call on the element, you will get unescaped html (jQuery doesn't bother escaping when .html() is called on a script tag).
Here, make this change
OLD
var allTemplates = '<section id="header">header template</section> <section id="content"><% var test = 10 %><%= test %></section>"';
NEW
var allTemplates = '<section id="header">header template</section> <script type="text/template" id="content"><a href="#“><% var test = 10 %><%= test %></a></script>"';
I couldn't get this to work with jsfiddle.net, so here is a plnkr.co

Passing Data received in one html page to another

Say I have variables that I acquire in one html page, such as a UserName or a url or something. And in another html page I have input boxes for these variables and I want to autocomplete them by sending the data from the first html page to the input boxes in the second one. Can anyone indicate to me how I can achieve this?
Use JavaScript to create the equivalent collection for use by other JS code:
Code:
<script type="text/javascript">
var querystring = [ ];
var qs = location.search;
if ( qs.length > 1 )
{
qs = qs.substring(1); // skip past the ?
var pairs = qs.split( /\&/g ); // get all the name=value pairst
for ( var p = 0; p < pairs.length )
{
var pair = pairs[p];
querystring[ pair[0] ] = unescape( pair[1].replace(/\+/g," ");
}
}
</script>
Then, anyplace in your page where in ASP code you might use
Code:
var foo = Request.QueryString("foo");
you instead simply do
Code:
var foo = querystring["foo"];
CAUTION: "foo" will be case sensitive, unlike in ASP. If you wish, you could replace
Code:
querystring[ pair[0] ] = unescape( pair[1].replace(/\+/g," ");
with
querystring[ pair[0].toLowerCase() ] = unescape( pair[1].replace(/\+/g," ");
and then always use lower case names ("foo" in place of "Foo" or "FOO") when finding values.
Untested, though I have used this same code before. If there's a goof, it's just a typo.
You can use JQuery for that. Assuming you are not using any server side code.
Pass the value as a param to the next page.
Like myurl?param=xyz
Then you can get the value in the next page like this,
See this answer and sourcecode
var xyz = jQuery.url.param("param_in_url");
For this you can use php session .store that variable in session and get them in any page.or if you are calling that page from the page where u have values say username call like
next page
You should use $_SESSION variable in php. OR you can use sessionStorage of javascript.

Categories