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

Maintaining Existing Filters and Incorporating Additional Filters in React/Next.js Data Filtering

I'm currently facing a challenge with filtering data in React/Next.js. The issue I'm encountering is that whenever I set a new filter, the previous filters get removed. For instance, if a user performs a search, it works fine but the tag filters ...

Using jQuery UI autocomplete with special characters

Recently, I put together a simple jQuery example utilizing jQuery UI autocomplete feature. $(function() { //autocomplete $(".selector").autocomplete({ source: "getdata.php", minLength: 1 }); }) getdata.php: <?php if (isse ...

Unlocking Google APIs Data through Service Account in JavaScript without User Approval

Is there a way to obtain an Access Token for Google APIs without requiring user consent, utilizing a Service Account in JavaScript? Alternatively, is it possible to retrieve the Access Token using an API Key, Client ID, and Client Secret? ...

Confirm the contents of a form retrieved through ajax

Let me explain the issue I am facing. I have created an HTML page with a simple form and some jQuery code for validation. This is how the page looks: <html> <head> <title></title> <script src="jquery-1.7.min.js" type="text/jav ...

Transform Json Unicode into Utf8 format

Having trouble converting Json Unicode to UTF8. The string "V\u00E4xj\u00F6" should read as "Växjö". I've tried everything I can think of, but no success so far. Any skilled coders have a solution for this problem? It seems like it shou ...

Having trouble interpreting the JSON response from an API in PHP

Currently, I am attempting to parse JSON in PHP from the following URL response: In order to perform the parsing, I have written the following code snippet: <?php $json_string = file_get_contents("https://en.wikivoyage.org/w/api.php?action=que ...

Is it possible to make changes to a box within a current PDF document using HummuJS?

I'm looking to update some existing PDF files with new data. According to the HummusJS documentation, I should be able to modify the box using parsing and modification techniques. However, I haven't been able to find the correct method to do so. ...

Enhancing the user experience by providing auto-complete suggestions while still maintaining the original form functionality

Encountering a curious bug that appears to be affecting only IE and Webkit browsers. I've set up a simple form as follows: <div id="output">Form output is shown here</div> <form id="myForm" action="#" method="post"> <input type= ...

I am experiencing difficulty selecting a precise geolocation using a Postgres query

I'm currently working on an API and encountering a frustrating issue. Whenever I execute the following query: SELECT * FROM u.loc It retrieves all user locations along with additional data, including a parameter called "geocode": ex. "geocode":"(48 ...

showcasing recommended options in the search bar through the use of javaScript

Hey there, I've been working on creating result suggestions for my search bar. The generation process is all set, but I'm facing an issue with displaying the elements on the HTML page. During testing, I keep seeing ${resultItem.name}, and when I ...

Uncovering targeted terms within JSON structures with Python

I have developed an automation script to extract information from a word document and convert it into a JSON object. However, I am facing difficulty in retrieving specific values, particularly the applied voltage values of each test case, and storing them ...

Despite having magic_quotes_gpc turned off, jQuery Ajax still escapes strings

Even with magic_quotes_gpc = off on the server, the data I send via jQuery Ajax is still being escaped. When getting data directly from $_POST without using ajax, everything works fine and the data remains unescaped. However, when sending data through aja ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

A SyntaxError was caught due to an unexpected token '<' in the constants.js file when using react and vite

I'm trying to display a button in the sidebar with a name and an icon. I've been iterating through the list of categories, which are imported from the 'constants.js' file located in the utils folder. However, instead of getting the desi ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Exploring the use of double quotes in constructing a request using Python's dumps function

Seeking advice on how to customize requests for JSON-style syntax. json.dumps will format it like this: {"tenantid": 1, "name": "NewRoleName", "users": "[djones]"} However, the server requires it to look like this: {"tenantid": 1, "name": "NewRoleName" ...

The simple passport.js sign-up feature is not successful as it mistakenly believes that the username is already in

Currently, I am working on setting up a basic signup feature for my Node + Express + Sequelize application using passport.js. The database is empty at the moment, and I am utilizing the passport-local strategy to extract the user's email and password ...

Tips for sending an array of inputs to the query selector in Node.js using Cloudant

Currently, I am attempting to retrieve documents from a cloudant database using node.js. While I have successfully managed to obtain results for a single input value, I am encountering difficulty when it comes to querying with an array of inputs. For a si ...

In Node.js and Express, it is important to note that a variable must be declared before

When I use the express action get('items'), I encounter an issue while trying to call an external JSON-API and display the API response in my local response. The error that I am currently facing states that the items variable is not defined with ...

Is there a way to automatically update the state in ReactJS whenever new information is added or deleted, without the need to manually refresh the page

I have encountered an issue that I have been trying to resolve on my own without success. It seems that the problem lies in not updating the Lists New state after pushing or deleting from the API. How can I rectify this so that manual page refreshing is no ...