grails gsp javascript integration, how to escape variables? - javascript

I have a gsp page (template) where I need to include some javascript. In the example below, how would I get the remoteFunction to understand, the moneyTransId will be set by the javascript function? MoneyTransId comes out fine in the alert, but I can't get it to work in the remoteFunction, and apparently need to escape it somehow.
<script type="text/javascript">
function confirmVoid(moneyTransId) {
var r = confirm("Please confirm the void");
if (r == true) {
alert("ID is: " +moneyTransId);
${remoteFunction(action:"voidTransaction", id:moneyTransId)};
...

Use the following syntax:
${remoteFunction(action:'voidTransaction', params:'\'id=\'+moneyTransId')};
This way, you won't mix server-side code with client-side code.
Hope this helps.

Server side variables and statements can not read client side (javascript) variables.
Server side code runs first, then html and javascript get generated and sent to the client (browser). Then the browser renders HTML and runs javascript. Hope this helps your thought process.
Dmitry.

Related

Can I set httpSession using js file which is included in my jsp?

I am using spring mvc. i want to set attributes to my httpSession. I want to do something like
// this is inluded in my js file
function setName(name){
<%session.setAttribute("name", name)%>
}
I dont think it will work.You should try to know the Principle of the jsp:
1.the <%session.setAttribute("name", name)%> is java code,it will excute in the server before the jsp is return to the browser.
2.the function setname() is js code, it will only work in browser.
3.you can see response in browser finally like that:
// this is inluded in my js file
function setName(name){
}
yeah,there will be nothing in setname;
If I have understood correctly what you want. You can't set attribute in your httpSession with javascript cause it's client side. If you want to set attributes in your httpSession, you have to get the name server-side (with a get or a post) and change your httpSession in your java.
If you want to change it dynamically, you have to use Ajax to do your request.

jQuery syntax in Laravel View

My code in my View (Laravel framework):
...
var d_from = $('#date_from').val();
$('#total-invoices').html('{{ App\Output_Detail::getTotalInvoices(' + d_from + ') }}');
...
$('#total-invoices') is a HTML Label component.
I have a syntax error in my above code above: ..(' + d_from + ')..
If I put a static variable, the return from my Model function is working fine:
{{ App\Output_Detail::getTotalInvoices("2015-11-03") }}
You're mixing JavaScript and PHP here. PHP is a server side language, which means it is processed on your server. JavaScript is a client-side language, which is run on the client's browser. So your PHP will be parsed BEFORE your JavaScript. You're trying to use a JavaScript variable d_from inside PHP, but that variable won't be declared until PHP is done and the HTML is sent to the client's browser.
As far as a solution goes -- whatever value you're populating the #date_from input with you could also drop into this getTotalInvoices method. If that value isn't available until it hits the client-side, you'll need to make an AJAX call back to the server to run this method.
You cannot have the backend code depend on the front end code in that way.
When your page loads, all the PHP Laravel code gets executed on the Server machine.
Then, all Javascript code gets executed on the resulting page on the clients machine. That will be your computer or the users computers.
So, getTotalInvoces is receiving the string literally as ' + d_from + '.
If you need to get the values after a page has been loaded, you will need to make an ajax call to the server.
I solved my issue:
...
// ajax
$.get('{{ URL::to('employee/ajax_Total_Invoices') }}?date_from=' + $('#date_from').val(), function(data){
// success data
$('#total-invoices').html(''+data+'');
});
...

Accessing a local js variable in razor block

I am trying to write razor code inside javascript where I am trying to use a local variable inside the razor code. Here is the sample code:
<script type="text/javascript">
for (i = 0; i < data.result.length; i++) {
$("#member-table tbody").append("<tr>");
var id = data.result[i].MemberId;
var actions = $("<td>" + #Html.ActionLink("Detay", "Edit", new { id }) + "</td>)");
}
</script>
the problem is that id is not recognized by the razor code (i.e. it does not exist in the current context). How can I achieve that ? Is there any way ?
It's not possible to access a javascript variable in a razor block.
That's because razor is executed in the server, and javascript is executed in the browser.
However, by looking at your code it seems like you are using javascript to populate a table and that's bad, there are two patterns for solving this problem, one that solves everything in the server, and another one that solves everything in the browser.
Solving everything in the server:
If you decide that you want to solve everything in the server, your javascript should request the contents from the server and load them into a placeholder without changing them, something like:
$("#myButton").click(function(){
$("#myDinamicDiv").load("/Path/ToView");
});
and then you use razor's foreach loop to generate the table's html:
#foreach (var x in ViewBag.MyData)
{
<tr>
<td>Generate contents here, including links </td>
</tr>
}
Solving everything in the client:
As pointed out in another answer, if you are using the default routing, you can just create direct strings in the javascript code and add them to your page, keep in mind however, that when using this solution, as your page gets complex, your javascript will became less and less maintainable, having a for loop that iterates over data is a sign that maybe you can benefit from javascript UI frameworks like Angular.js and Knockout.js, in fact, what you are doing is the core of Knockout.js's third lesson in its tutorial (Single page applications)
If you're just using default routing, then simply just don't bother with the Razor #Html.ActionLink. Stick with an explicit tag:
var actions = $('<td>Detay</td>');
...obviously with whatever your current controller name is substituted for [your-controller-here].
(And I'm assuming your 'id' isn't necessarily URL-encoded, hence the 'escape'.)
You are mixing server side and client side here. You cannot create #Html.ActioLink using client side variables. Html.ActionLink is rendered on the server, it does not have any clue at all about your client side variables.
If you want to use a client side variable, like "id", render a plain html link (a) tag.
This worked for me once
if ('#ViewBag.DownloadLink' != '') {
window.location.href = '#ViewBag.DownloadLink';
}

how to pass javascript variable to embedded Server Side code ASP.NET WebForm

let say i have a function like below in BAL.cs file
public static void xyz(string name)
{
Response.Write("Hello "+name);
}
Let say i have a javascript variable x.
now i want to call the function from BAL.aspx file
<script>
var x= "Tahmid";
<%=BAL.xyz()%> // want to pass x as a parameter
</script>
this is in webform.
It seems like there is some sort of confussion here that I would like to help solve. Server code and client code are separated. When client code executes (such as javascript) the server has no way to know what happened so your server side code (code behind) is not aware of any changes. In order to have the javascript variable information on the code behind you'll need to send that variable value back to the server and one of the mechanisms is the one provided by user2952502. I think in your case a postBack (using a submit or link button) would be more appropiate, right? I think you're trying to redraw the page based on something that the user did (since you're using javascript).
I think we should have some more information to understand the whole scope of your question and probably suggest you a better way to deal with it.
so you want to use windowfunctioname ?
since javascript is clientside and asp is serverside you could create a list of calls with parameters.
<script type="text/javascript">
var calls = [{exec: 'functionname', param : {name: 'Tahmid'}}];
document.addEventListener('DOMContentLoaded', function () {
c = calls.length;
for (var i = 0; i < c; i++) {
call = calls[i];
window[call.exec](call.param);
}
});
</script>
I hope that was an answer that helps.
The question is not clear enough .
what are u trying to do ?
just to print a dynamic text u can do with javascript function..
if u have to use a server function please specify the platform u use : MVC / WebForms..
in MVC you can use jQuery Post:
<script>
var x = "value";
$.post('#Url.Action("Action","Controller")',{name : x});
</script>

Transferring javascript from a view to a seperate JS file

I am working on a legacy application and I want to move some JS code onto a separate JS file.
I will have to refractor some of the code to do this. I can put #Url.Content statements into data attributes in the HTML.
But how would I replace this line of code?
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
A separate JS file will not know what #Html.Raw means.
Server side code like that cannot run in a seperate javascript file. My solution for such problems is having a short javascript part in the head that runs on the onload event. There you can set variables that you can use in a seperate javascript file:
in the head:
array = #Html.Raw(Json.Encode(ViewBag.JobList));
in the seperate javascript file:
var array;
Then, in the seperate javascript file you can do with your array whatever is necessary.
The ViewBag.JobList data is only known at HTML page generation time. To include it in an external JavaScript file, you have to have another ASP.NET resource that recalculated ViewBag.JobList and then served as part of a dynamic JavaScript file. This is pretty inefficient.
Instead, do what you're doing with the URLs: pass the data through the DOM. If you're writing into normal DOM instead of a script block, you don't need the raw-output any more (*), normal HTML escaping is fine:
<script
id="do_stuff_script" src="do_stuff.js"
data-array="#Json.Encode(ViewBag.JobList)"
></script>
...
var array = $('#do_stuff_script').data('array');
// jQuery hack - equivalent to JSON.parse($('#do_stuff_script').attr('data-array'));
(Actually, the raw-output might have been a security bug, depending on what JSON encoder you're using and whether it chooses to escape </script to \u003C/script. Writing to HTML, with well-understood HTML-encoding requirements, is a good idea as it avoids problems like this too.)
I think you need to create action with JavaScriptResult
public ActionResult Test()
{
string script = "var textboxvalue=$('#name').val();";
return JavaScript(script);
}
But, before proceeding please go through following links
Beware of ASP.NET MVC JavaScriptResult
Working example for JavaScriptResult in asp.net mvc
I would also follow MelanciaUK's suggestion :
In your javascript file, put your code inside a function :
function MyViewRefactored( array ){
... your code ...
}
In your view, leave a minimal javascript bloc :
<script>
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
MyViewRefactored( array );
</script>

Categories

Resources