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

What is the best way to insert a record into the rth column of the nth row in a table

In the table I'm working with, there are 6 columns and only 5 of them have data filled in. The last column is currently empty for all rows. I am now trying to populate the last column of each row with some data. Can someone guide me on how to use a f ...

Having trouble retrieving req.session variables in Express/NodeJS?

I have come across various versions of this particular question, however, none of them seem to address my issue directly. My current objective is to establish a Node.js server using Express. Below is my existing server configuration: var express = require ...

What are the benefits of keeping JavaScript and HTML separate in web development?

Recently, I came across the concept of Unobtrusive JavaScript while researching best practices in the realm of JavaScript. One particular point that grabbed my attention was the idea of separating functionality (the "behavior layer") from a web page's ...

ESLint flags a misuse of promises in my code that I believe is acceptable

This symbol table implementation includes a method that needs some adjustments: public getAllSymbols(type?: typeof Symbol, localOnly = false): Promise<Set<Symbol>> { const promise = super.getAllSymbols(type ?? Symbol, localOnly); ...

Experiencing Chrome freezing issues due to a setInterval function in combination with React

Can anyone assist me with a countdown issue using React? I am trying to set the minutes and seconds by clicking on + and - buttons, then passing the seconds to a new variable called tottime. However, when the user clicks on Go!, the countdown should start ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Inscribe latitude from marker onto input field

Currently, I am working on a feature where markers are added to Google Maps API v3 by clicking on the map. Each marker then displays its coordinates in an info window. However, I am facing an issue with picking up the latitude and longitude values and inse ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

React's conditional statement is malfunctioning

I am attempting to display a specific form for review if the user meets the following criteria: 1. Logged in 2. Not an administrator 3. Not a moderator My code currently looks like this: <h2>Write a Review</h2> {errorResortReview &a ...

two occurrences of the identical controller in AngularJS

Encountering a dilemma (admittedly, not the best approach). There is a single view featuring a split screen; an input field occupies the left side while its corresponding value appears on the right. Both sides are managed by the same controller, using the ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

What is the optimal method for generating numerous records across various tables using a single API request in a sequelize-node.js-postgres environment?

I need to efficiently store data across multiple separate tables in Postgres within a single API call. While I can make individual calls for each table, I am seeking advice on the best way to handle this. Any tips or suggestions would be greatly appreciate ...

angularJS controller does not seem to be functioning properly due to a certain

var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var currentdate = yyyy + ',' + mm + ',' + dd; var appointmentDate = moment($scope.AppointmentsList[i].J).f ...

Updating Angular 8 Component and invoking ngOninit

Within my main component, I have 2 nested components. Each of these components contain forms with input fields and span elements. Users can edit the form by clicking on an edit button, or cancel the editing process using a cancel button. However, I need to ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

The scrolling on the image listing webpage is not as fluid as desired

I'm currently working on building a website for displaying images in Angular, similar to Google Photos. The site includes a custom scrollbar that displays the month and year. I want the image list to scroll when the user moves the scrollbar thumb. Her ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Show method created by function, substituting the former element on the display

showButtons(1) will show radio buttons for frame number 1, showButtons(400) will display radio buttons for frame number 400. The current code shows all radio buttons for every frame up to 400 HOWEVER, I am aiming for a single set of radio buttons to start ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Leveraging TypeScript to sort and extract specific elements from two arrays

Given two arrays, I am looking to identify the elements in array2 that match elements in array1 based on a specific property. The arrays are structured as follows: var array1 = [ {"myId": 1, "text": "a"}, {"myId& ...