What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript function.

This is my GSP page:

<table>
<tr>
<td><div id="test" onclick="${remoteFunction(controller:'ProjectOperations', action:'ajaxFun', update:'results',onComplete:'getFields(e)',params:'\'filter=\' + escape(this.id)' )}">click me!</div></td>
</tr>
</table>
<div id="results"></div>

Controller class:

import grails.converters.JSON

class ProjectOperationsController {

    def ajaxFun(){
                def project="Hill"
                def company="VK"
        def operation=Operation.findAllByProject_name(project)
        def staff=StaffDetails.findAllByCompany_name(company)

        render operation,staff as JSON
    }
}

In this part, I aim to render two lists (operation and staff respectively) and also learn how to retrieve them from the JavaScript function.

Javascript function:

<g:javascript>
  function getFields(e){ 
// here I want to retrieve those two objects.
 } 
 </g:javascript>

Answer №1

Make a modification in the controller.

    Change the code from render operation,staff as JSON//am not sure 

to

    render [operation:operation,staff:staff] as JSON

Next, update the javascript function:

 function getFields(e){
    var data = eval("("+e.responseText+")");
    console.log(data.staff);
    console.log(data.operation);
 }

When you check your console, you will first see the contents of staff followed by the contents of operations. These will likely be arrays that can be manipulated in JavaScript.

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

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Ways to identify if there is a problem with the Firestore connection

Can anyone help me understand how I can use angularfire2 to check the accessibility of the cloud firestore database and retrieve collection values? If accessing the cloud database fails, I want to be able to retrieve local data instead. This is an exampl ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Troubleshooting a setTimeout filter problem in Vue

Implementing a notification system in Vue has been my latest project. I've created a Notifications component to store error messages that I want to display. data(){ return { alerts: { error: [] } ...

Updating a textbox with JQuery AJAX when the text in another textbox changes

Whenever I type something into an input field with the id "textbox1", I want to update another input field with the id "textbox2" accordingly. This is the code I started with: $("#textbox1").keyup(function(){ $.ajax({ type: "POST", ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

How can I move a complete range of values up using the Google Sheets API in Node.JS?

I'm working with a Google Spreadsheet that is being accessed and modified by a Node.JS app. There's a specific situation where I need to shift an entire range up (moving A3:D up by one cell), but due to my limited experience with the Google Shee ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

Get JSON or partial HTML responses from ASP.NET MVC controller actions

Is there a recommended method for creating controller actions that can return either JSON or partial HTML based on a specified parameter? I'm looking for the optimal way to asynchronously retrieve the results in an MVC page. ...

Tips for displaying a refresh indicator while making an ajax call for refreshing data:

I have successfully implemented jQuery code that refreshes a specific div every 10 seconds without reloading the entire page. However, during this refresh process, the user does not visually perceive any changes happening in the browser. While there are n ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

post request using jquery synchronous method

When you visit the jQuery website, they provide an example of making a synchronous call using the method below: jQuery.ajax({ type: "POST", url: 'http://example.com', success: function(result) { }, async: f ...

Issue with Observable binding, not receiving all child property values in View

When viewing my knockout bound view, I noticed that not all values are being displayed. Here is the script file I am using: var ViewModel = function () { var self = this; self.games = ko.observableArray(); self.error = ko.observable(); se ...

Leveraging the power of Express.js, transmit local data alongside a

Why can't I display the active user in my view using plain HTML when console log shows it? Here is the code snippet: app.post('/', function (req, res) { var user = { user : req.body.username }; res.render('doctor_hagfish/pets&ap ...

Tips for transforming a JSON Array of Objects into an Observable Array within an Angular framework

I'm working with Angular and calling a REST API that returns data in JSON Array of Objects like the example shown in this image: https://i.stack.imgur.com/Rz19k.png However, I'm having trouble converting it to my model class array. Can you provi ...

A guide on accessing header response information in Vue.js

Currently, I am operating on my localhost and have submitted a form to a remote URL. The process unfolds in the following sequence: Submission of a form from localhost Being redirected to a remote URL Sending a response back from the Remote URL to localh ...

Ensure that the div remains within the viewport

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tit ...

Using Javascript to organize an array of objects based on a specific condition

Having an array of objects structured as follows: obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3}, {'name': 'Sam', ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...