rtfminc
rtfminc

Reputation: 6363

Grails: Passing a javascript variable to a template

I am new to ajax so maybe this is obvious. I've tried many different not-working approaches. I have javascript that when you click on a button:

  1. an ajax call that grabs some data from a controller - returns an object
  2. display that data in a template that I will show on the page

Here is the javascript/ajax:

<script type="text/javascript">
  $("#show").click(function () {
    $.ajax({  url: '/Myproject/result/index',
              type: "POST",
              data: { id: id},

          success: function(result) {
             alert("Success:" + result);  // Can see getting object back.
          }});
    $(".resulttable").show();
  });

Here is the key line in grails view template:

<g:each in="${allResults}" status="i" var="result">
  1. How do I get the data from the javascript to the gsp code (ie allResults)?
  2. Do I have to "refresh" this template to display new data?

thanks.

Upvotes: 0

Views: 1388

Answers (2)

Tiago Farias
Tiago Farias

Reputation: 3407

You just can't make your javascript/jquery code populate things in the gsp, since the gsp is processed server-side and javascript is processed client-side, after the gsp rendered all html documents and populated them with your model. You need to be aware that your page was already processed, so things like ${variables} won't be reloaded anymore. So when you do this:

$(".resulttable").show();

It's not gonna show the result you're waiting for. You have to use javascript code to reload your result table.

So if you're using ajax here, you should use the function success to alter your html table via javascript/jquery since you already have the response you wanted. Maybe this read can help you. Oh, and I think it would be better if in your ajax call, you would define a dataType (json works great in your case), like this:

$("#show").click(function () {
    $.ajax({  url: '/Myproject/result/index',
              type: "POST",
              data: { id: id},
              dataType: 'json',
              success: function(result) {
                  alert("Success:" + result);  // Can see getting object back.
              }});
    $(".resulttable").show();
  });

Just to make clear what kind of response you're getting from the controller.

Upvotes: 1

matcauthon
matcauthon

Reputation: 2261

You do not need to write your ajax calls the hard way. There are some Grails intern tags you can use inside your html:

Following the links you will find some nice examples...

Upvotes: 1

Related Questions