4

I'm trying to pass a parameter coming from my controller to a javascript script so I can edit the data. But the javascript isn’t accepting my parameter.

Here is the code:

@for(status <- lista){
<tr>
<td>@status.getDescricao()</td>
<td><a href="javascript:;" onclick="enviar('formAltStatus/@status.getCodStatus()')"><img src="@routes.Assets.at("img/edit.png")" alt="" title="Editar"/></a>
                    <a href="@routes.StatusController.removerStatus(status.getCodStatus())"><img src="@routes.Assets.at("img/erase.png")" alt="" title="Remover"/></a>
</td>
</tr>
            }

The @status.getCodStatus() is my ID.

The route:

GET     /formAltStatus/:id              controllers.StatusController.formAltStatus(id:Long)

The javascript:

function enviar(a){
    $.ajax({
        url: "/"+a,
        type: "GET",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        dataType: "html",
        async:true,
        success: function(html){        
            $("#nova").html("");
            $("#nova").html(html);
            $("#logo").show();
        }
    });
}

Is there another way to do this?

2 Answers 2

3

HTML5 data attributes are designed for this situation where you have to pass server-side data to client-side functions. I think the best-practice solution is to add a data attribute to your anchor tag, and then retrieve the attribute value in Javascript.

<a ... data-status="@status.getCodStatus" data-param2="@param2">

This code then illustrates what the Javascript might look like. I don’t have much Javascript expertise so I’ve written a solution that uses JQuery. You will have to modify my suggestion if you're not using JQuery and are just using pure Javascript.

HTML:

<!-- Simple illustration of how to pass server-side data to a JS function -->
<a href="no-javascript.html" class="edit-link" data-status="@status.getCodStatus" data-param2="@param2">
    Hyperlink body goes here
</a>

Javascript:

$('.edit-link').click(function(e) {
   e.preventDefault();
   statusCode = $(this).data('status', 'param2');
   alert(statusCode);
 });

Live example on jsFiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

Similiar situation. Wanted to set the template parameter as an angular scope variable. I passed the Json version of my model object and set it using ng-init.

Server Side

return ok(views.html.database.admin.chargeGroups.render(Json.toJson(commodity)));

Front End

@(commodity: com.fasterxml.jackson.databind.JsonNode)
@main("Charge Groups") {
<div ng-controller="ChargeGroupsController" ng-init="commodity = @commodity">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.