Executing a controller method in Grails using JavaScript

When working in a Grails view, I find myself needing to execute a JavaScript method to retrieve certain information. To achieve this, I have set up a submit action as shown below:

<input type="submit" name="submit" class="submit action-button" value="Generate" onclick="generateReport()" style="float: right" />

After the generateReport() function is executed, I need to call or redirect to the show action of a Controller (since I am already at the create action).

I have attempted two approaches:

1) var jsonData = generateJSON();
    <g:remoteFunction controller="report" action="show" params="[data:jsonData]" />

2) var jsonData = generateJSON();
    <g:remoteFunction controller="report" action="show" params="[data:${jsonData}]" />

The issues encountered were:

1) The data passed was null.
2) A compilation error occurred:</p>
<code>org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
Message
Attribute value quote wasn't closed (controller="report" action="show" params="[data:${jsonData}]").

Answer №1

Here is a suggestion for you to try:

To start, declare a variable within your GSP file like so:

<script type="text/javascript>
    var yourVariable = "${createLink(url: [controller: 'yourController', action: 'yourAction'])}";
</script>

Next, in your JavaScript file, you can utilize AJAX.

For example:

function checkUsernameAvailable(user, example){
    $.ajax(
    {
        url: yourVariable,
        contentType:"text/json",
        type: "get",
        data: ({ id: usernamenya}),
        dataType: "json",
        cache: false,
        async: false,
        success: function(data) {
               //Perform actions based on response
        },
        error: function(xhr) {
            //Handle errors here
        }
    });                 
}

Answer №2

The variable json cannot be assigned to data as params in , since var jSon is a JavaScript variable. The data in the params attribute requires a model parameter coming from the controller.

In the 1st option, when it is assigned as params, it shows null because it is not a model parameter from the controller.

The 2nd option would result in a compile error as this is not the correct way to define a model parameter from the controller.

It is recommended to retrieve jSon as a model from the controller and then define it as params.

You can also refer to the following link for defining g:remoteFunction in onclick itself:

I hope this information is helpful! Thank you.

Answer №3

Unfortunately, the remoteFunction tag is not suitable in this scenario as it is processed into html and JavaScript on the server side prior to knowing the value of JSON on the client side.

To resolve this issue, you will need to make an ajax call manually (e.g. using jQuery).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Route functions cannot be hoisted in the Express framework

Can someone shed light on why my Express routes aren't hoisted? I keep encountering this error: throw new TypeError('Router.use() requires middleware functions'); The error is not present in the following file: var express = requir ...

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

Creating a Delicious Earth Progress Pie

I'm looking to incorporate a unique progress bar design on my website, similar to this one: The progress pie Can anyone guide me on how to create a progress pie with an image inside it that changes color as it moves? ...

Setting the attribute dynamically for a select box with multiple choices

In my form, I have multiple choice select boxes styled using bootstrap select. Since the app is developed in Express, I am having trouble retrieving the selected values due to bootstrap select creating a div and a list for user interaction. To tackle this ...

"Utilizing Dynamic Dropdown Options Pulled from Database and Automatically Refreshing List upon

I am facing a dilemma with displaying dropdown menus for Provinces and Cities, both of which have values coming from the database. While I can easily list the values for Provinces by querying all of them, my issue arises when it comes to displaying Cities. ...

Passing an array of integer arrays to a controller method in ASP MVC using Ajax

I am encountering an issue with my AJAX call when trying to post data entered by the user on the webpage to a controller method. Unfortunately, the data never reaches the controller and always results in an error. I suspect that the problem lies in the typ ...

Can we modify a currently active document within MongoDB?

Is there a more efficient way to achieve the same functionality in JavaScript? I have to find a user, validate their password, and then update their document. Can I optimize this process by reusing the already retrieved document (stored in var doc) for up ...

Tips on validating ASP.NET gridview textbox with javascript during the update process:

I've implemented a gridview on my aspx page: <asp:GridView ID="gvPhoneBook" runat="server" AutoGenerateColumns="false" ShowFooter="true" DataKeyNames="PhoneBookID" ShowHeaderWhenEmpty="true" OnRowCommand="gvPh ...

Combining strings and variables in Vue.js with the use of bootstrap-vue syntax

Hey, I'm facing a little syntax hiccup with '="collapse-{{ product.id }}"' in both the b-button and b-collapse. Any ideas on how to properly structure this? Just looking to set up a unique ID that connects the button to the collaps ...

I need to update my database by sending requests to my API, as the changes are not being reflected in the current database state. I am eager to see the

Struggling to grasp the concept of making requests to an API that uses express for CRUD operations. In the code snippet below, .get(/bears) displays a form and in app.post('/bears'), I'm using the 'request' module to send a request ...

Content will be loaded only after the user clicks on the item

On my blog, I have a share button that displays different social media platforms when clicked. However, the page takes longer to load due to fetching data from multiple servers like Facebook and Twitter. Is there a way to use jQuery to make these buttons l ...

Hiding labels in an HTML document can be achieved by using CSS

Recently, I've been working on a code that relies on a specific Javascript from Dynamic Drive. This particular script is a form dependency manager which functions by showing or hiding elements based on user selections from the forms displayed. Oddly ...

Issue with pushing inner list<object> in Knockout version 3.2.0

Currently, I am working with knockout.js on an ASP application. The issue I am facing involves a list of objects returned by the controller action to the view, where the objects in the list point to another list of objects. My struggle lies in adding new o ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: I have data in a model that indicates the available amount of free pallets ...

Creating a React functional component that updates state when a specific window breakpoint is reached

Having an issue with my code when it hits the 960px breakpoint. Instead of triggering once, it's firing multiple times causing unexpected behavior. Can someone help me troubleshoot this problem? const mediaQuery = '(max-width: 960px)'; con ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

The Jasmine test in my Angular project is experiencing a timeout issue, displaying the error message "Async callback was not invoked within 5000ms", despite the fact that no async function is being used in the

Reviewing the source code: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { IonicModule } from '@ionic/angular'; import { HomePage } from './home.page'; import { LevelGridComponent } from &a ...

Creating XML files using Node.js

What are some effective methods for generating XML files? Are there tools similar to the Builder in Rails, or any other recommended approaches? Appreciate any insights! ...

Could you clarify that for me?

Let's take a look at the function isIsogram(str) which checks if a string is an isogram. An isogram is a word or phrase in which no letter occurs more than once. The code snippet for this function can be seen below: We are particularly interested in ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...