Tips for integrating Grails ${createLink} into your javascript code

Below is a JavaScript function that I have:

function GetSelectedItem()
{
    var e = document.getElementById("country");
    var strSel =  e.options[e.selectedIndex].value;
    alert(strSel);
    var url = "${createLink(controller:'country', action: 'wholeTestUnits', id: strSel)}"
    alert(url);
 }

When I click the submit button, I want to navigate to the URL action:

<button class="submit_small" onClick="GetSelectedItem();">
    <span><g:message code="default.button.submit.label" /></span>
</button>

Unfortunately, the ${createLink} function is not functioning as expected.

Answer №1

A more efficient method for accomplishing this task without the need for JavaScript code to be embedded in your GSP file is as follows:

<button class="submit_small" onClick="GetSelectedItem();" data-url="${createLink(controller:'country', action: 'wholeTestUnits')}">
    <span><g:message code="default.button.submit.label" /></span>
</button>

function GetSelectedItem() {
    var button = event.target;
    var e = document.getElementById("country");
    var strSel =  e.options[e.selectedIndex].value;
    var url = button.getAttribute("data-url") + "/" + strSel;
}

Answer №2

It seems like there might be an issue between the server side and client side operations. The createLink function is executed on the server, while the JavaScript code runs on the client...

You can attempt the following solution:

var url = '${createLink(controller:'country', action: 'wholeTestUnits')}' + strSel ;

Answer №3

It appears that you may not be properly retrieving the value of strSel in your link. To address this issue, consider implementing the following code snippet:

function GetSelectedItem()
{
        var e = document.getElementById("country");
        var strSel =  e.options[e.selectedIndex].value;
        alert(strSel);
        var url = "${grailsApplication.config.grails.serverURL}/country/wholeTestUnits/" + strSel
        alert(url);
}

Answer №4

Instead of relying on the createLink function, consider constructing your own URL for greater control. Be mindful of capitalization in the controller name.

var url="${ createLink(controller:'testcontroller', action:'getData') }";

This can be simplified to:

var url = "/testcontroller/getData;

If you need to pass arguments from JavaScript to the controller, follow this approach.

var url = "/testcontroller/getData?arg0=" + arg0 + "&arg1=" + arg1;

In the controller, use the params keyword to access the arguments. To display these parameters, use the following code:

println params.arg0
println params.arg1

Answer №5

    --inside a gsp file--
   <a href="#" onclick="makeAjaxCall('${createLink(controller:'shift',action: 'addShift')}");">Add or Edit Shifts</a>


    --within a js file--
    function makeAjaxCall(endpoint){
    //endpoint->/shift/addShift
       var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        document.getElementById("updateContent").innerHTML = this.responseText;
                    }
                };
                xhr.open("GET", endpoint, true);
                xhr.send();
      }

Answer №6

Give this a shot: let target_url = "${generateLink(controller:'nation', task: 'allTestCases', parameters:[identifier: selectedString], complete: true)}"

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

Retrieve identification details from a button within an ion-item located in an ion-list

<ion-list> <ion-item-group *ngFor="let group of groupedContacts"> <ion-item-divider color="light">{{group.letter}}</ion-item-divider> <ion-item *ngFor="let contact of group.contacts" class="contactlist" style="cl ...

The Highchart formatter function is being called twice on each occasion

My high chart has a formatter function that seems to be running twice. formatter: function() { console.log("starting formatter execution"); return this.value; } Check out the Fiddle for more details! ...

Creating a chat interface with chat bubbles in React JS can be done by implementing components such as Message

Having some JSON data stored in dummyData, I am seeking guidance on how to position chat bubbles on the left and right based on the direction. My framework of choice is Material UI along with the context API. The attached image serves as a visual reference ...

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

Can you explain the functionality of $scope.$apply()?

Lately, I've been incorporating $scope.$apply() into my Angular applications to refresh the bindings for my models when new data is received via websockets. It seems to be effective, but I'm curious about its actual functionality and why it' ...

Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of th ...

Executing MySQL queries through JavaScript functions

I need to create a PHP function that I can use in my JavaScript code. The issue I'm facing is that the variables from the beginning of the file are not recognized in the JavaScript block. <!DOCTYPE html> <?php include 'pdo_connect.php&a ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

Verify if the term is present in an external JSON file

I am currently using tag-it to allow users to create tags for their posts. At the moment, users can type any word, but I have a list of prohibited words stored in JSON format. I am looking for a way to integrate this list into the tagit plugin so that if ...

Utilizing JavaScript to enable HTML checkbox to be checked automatically

I am currently working on a constructor that generates checkboxes within a loop. My issue lies in attempting to set these checkboxes as checked, however, it doesn't seem to be functioning correctly. Below is the code snippet: funct ...

Attempting to Send an Ajax Request and Utilize the Result within a React Component

I am having issues with my tweet box component. I have a submit function that triggers the getAllTweets function when called. The problem is that I am unable to capture the value of the field and pass it on to the getAllTweets function in order to create ...

What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion. Below is a fragment of the code: var h ...

Why do we even need Angular controllers when directives can perform the same tasks as controllers?

As a new Angular developer, I have to say that I am really impressed with the architecture of this framework. However, one thing that puzzles me is the existence of controllers. Let me elaborate: Services in Angular seem to have a clear purpose: 1) Store ...

Display a webpage once its design is completely loaded in Nuxt

I have implemented a layout for my admin pages that displays user information in a consistent format, eliminating the need to fetch this data every time the page reloads. However, I am facing an issue where the page does not wait for the layout to fully l ...

Error: The constructor for JsSHA is not valid for the TOTP generator

Attempting to create a TOTP generator similar to Google's timed-based authenticator using the React framework. I am utilizing the bellstrand module for TOTP generation, but I am encountering issues when trying to import it into my React code. Here is ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

Retrieving the updated list after a child has been deleted from the Firebase Database

According to the documentation, the DataSnapshot received in the child_removed callback contains the old data for the removed child. I have a scenario where I am adding data using push and then trying to access the next value after the top child is remove ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...