Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks.

  1. datasource
dataSource = new kendo.data.DataSource({
            transport: {
                read:
                    {
                        url: crudServiceBaseUrl + "WindowsService",
                        dataType: "json",
                    },
                destroy:
                    {
                        url: crudServiceBaseUrl + "WindowsService/Delete/?deletedby=" + clientid,
                        type: "DELETE"
                    },
                create:
                    {
                        url: crudServiceBaseUrl + "WindowsService/Post",
                        type: "POST"
                        //complete: function (e) {
                        //    $("#grid").data("kendoGrid").dataSource.read();
                        //}
                    },
                update:
                    {
                        url: crudServiceBaseUrl + "WindowsService/Put/",
                        type: "PUT",
                        parameterMap: function (options, operation) {
                            if (operation !== "read" && options.models) {
                                return {
                                    models: kendo.stringify(options.models)
                                };
                            }
                        }
                    },
            },
            schema:
                {
                    model:
                        {
                            id: "WindowsServiceId",
                            fields: {
                                WindowsServiceId: { editable: true, nullable: false, type: "int" },
                                ServiceName: { editable: true, nullable: true, type: "string" },
                                ServiceStatus: { editable: true, nullable: false, type: "string" },
                            }

                        }
                }
        });
  1. kendo grid
$("#grid").kendoGrid({
        dataSource: dataSource,
        editable: "popup",
        toolbar: ["create"],
        columns: [
        {
            field:"ServiceName",
            title: "Service",
            width: '200px',
        },
        {
            field: "ServiceStatus",
            title: "Status",
            width: '140px',
        },
        {
            field: "CreatedDate",
            title: "Date",
            width: '140px',
        },
        {
            command: [
                     {
                      name: "start",
                      text: "Start",
                      click: function (e) {
                          $.ajax({
                              method: "POST",
                              url: crudServiceBaseUrl + "WindowsService/Start?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
                          }).done(function (msg) {
                              alert("Service Started successfully");
                          }).fail(function () {
                              alert("service failed");
                          });
                      }
                     },
                     {
                         name: "stop",
                         text: "Stop",
                         click: function (e) {
                             $.ajax({
                                 method: "POST",
                                 url: crudServiceBaseUrl + "WindowsService/Stop?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
                             }).done(function (msg) {
                                 alert("Service Stop successfully");
                             }).fail(function () {
                                 alert("service failed");
                             });
                         }
                     },
                     {
                         name: "restart",
                         text: "Restart",
                         click: function (e) {
                             $.ajax({
                                 method: "POST",
                                 url: crudServiceBaseUrl + "WindowsService/ReStart?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
                             }).done(function (msg) {
                                 alert("Service ReStarted successfully");
                             }).fail(function () {
                                 alert("service failed");
                             });
                         }
                     },
                     {
                         name: "history",
                         text: "History",
                         click: function (e) {
                             alert("History");
                         }
                     }
            ]

        }
        ],

        //height: "500px",
        pageable: {
            refresh: true,
            pageSizes: true,
            buttonCount: 5
        },
    }).data("kendoGrid")

   ;
  1. html
<div id="grid"> </div>

I am facing challenges when passing the dynamic windowsserviceid which is a unique ID. Currently, I am using a static ID and it works fine. Please provide guidance on how to use a dynamic windowsserviceid in the AJAX function call. Your assistance and time are greatly appreciated. Thank you in advance.

Answer №1

After some searching, I discovered the solution by utilizing the Unique Id of each row and incorporating it into my Button Clicks functions. Everything fell into place perfectly for me.

var row = $(e.target).closest("tr");    //getting access to a specific row in the grid
var data = this.dataItem(row);     //retrieving the row items from the grid
var id = data.WindowsServiceId;    //the Unique Id associated with the row

Ultimately, I relied on this unique identifier (id) within my Button click functions.

Answer №2

Here is a solution that should work perfectly for your needs:

<div id="table"></div>
<script>
$("#table").kendoGrid({
  columns: [
    { hidden: true, field: "id" },
    { field: "name" }
  ],
  dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
</script>

If you want more information, you can visit this link:

http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#configuration-columns.headerAttributes

After implementing this solution, make sure to access the hidden field value within your function.

Additionally, it's recommended to separate your functions from the grid definition and call them as separate functions within the grid.

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

Creating DIV's with Equal Heights Using AngularJS ng-repeat

I'm currently facing an issue with aligning two side-by-side divs to the same height when the content is generated using an ng-repeat function. Using flexbox is causing responsiveness issues, and I'm unsure of the appropriate time to call a jQuer ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Switching from jquery's $.animate to $.velocity is not effective

I have a smooth animation implemented in jQuery for scrolling to a specific element. However, the animation is quite laggy. When I click on it, it smoothly scrolls down to the desired element. $('#aboutMenu').click(function(){ $('html, body ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Exception in posting strings or JSON with react.js

Whenever a user clicks on the Signup button, the process I follow to create an account is as follows: Firstly, a new User entry is created in the database. createUser = () =>{ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http:// ...

Working with JSON data in PHP and JavaScript

I'm attempting to send a JavaScript object to a PHP script using jquery.ajax(), like so: var bigArray = new Object(); //Code //Start loop bigArray[x] = {name: exname, id: exID, order:e, set: setBox, inc: incBox, example: exampleBox, day: i}; It&apos ...

Adjust the background hue and opacity when incorporating a "modal div"

Currently, I have a page where a hidden div appears at some point to display a form for inputting data. This could be considered a modal div. My goal is to darken the rest of the page and only allow interaction with this specific div. I want the backgroun ...

Tips for navigating through a JSON response to find specific information:

I'm currently looking for a way to search within a JSON result that has been returned. The result that was returned looks like this: {"Result":["Css","java","jquery","asp.net","mvc","javascript","asp","c#"]} My goal is to extract all the words that ...

Integrating a Find Pano functionality into a Kolor Panotour

I used a program called Kolor to create a panorama. Now, I am attempting to integrate the "find pano" feature, which involves searching through the panoramic images for display purposes. I have come across an HTML file that contains the search functionalit ...

Passing data retrieved from Laravel to AJAX using the ID

I'm currently struggling to figure out the best approach for handling a multiple comment form. Here is an example of what my form looks like: @foreach($lists as $list) //some views <form class="commentForm"> <input type="te ...

Utilizing Bootstrap modal to insert data into phpMyAdmin database - a comprehensive guide

I'm attempting to insert data into my localhost database using a Bootstrap modal in conjunction with Laravel 5.2. Here is the PHP function I am using: public function addReport(Request $request) { $postreport = new PostReport(); $postreport- ...

How to effectively filter nested arrays within Mongoose Populate function

I received the following object from a Mongoose query: let systems = [ { "maxUserLevel": 1, "subsystems": [ { "sections": [], "name": "apple" ...

The validation functionality in AngularJS for a form within an ng-repeat loop is not functioning as intended

In my table, I used the <tr> tag repeatedly with ng-repeat="cancellationPercentData in cancellationPercent" Each tr tag contains a form with name and id set using $index See the code snippet below: <tbody> <tr ng-repeat="cancellatio ...

Performing an action once all AJAX requests have finished

I'm dealing with a situation where I have a click event triggering 3 ajax calls: $("#button").click(function(e) { e.preventDefault(); $.ajax(call1); $.ajax(call2); $.ajax(call3); some_function() //needs to be executed only afte ...

Using the React Hook useCallback with no dependencies

Is it beneficial to utilize useCallback without dependencies for straightforward event handlers? Take, for instance: const MyComponent = React.memo(() => { const handleClick = useCallback(() => { console.log('clicked'); }, []); ...

Store JWT as a cookie in Vue JavaScript and ensure it is successfully saved before proceeding

Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home. However, there seems to be an issue with the authentication check on the /home route. When c ...

Issue with integrating e-junkie shopping cart with Bootstrap 5

After transitioning from Bootstrap 4 to Bootstrap 5 and encountering navigation issues on smaller screens, I delved into the code to uncover the source of the problem. It turns out that the collapse button in the navbar wasn't functional due to confli ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

Extracting precise information from a JSON file using Angular's $http.get

I am struggling with extracting a specific user from a JSON file containing a user list and displaying it on an Angular index page. Despite extensive research, I have been unable to find a satisfactory solution. The user list must remain in a JSON file ins ...

jQuery interprets every PHP response as having a status of 0

I've been working on a way for javascript to verify the existence of a user in a MySQL database. My method involves using jQuery to send the user details to a PHP script that will then check the database. The data is successfully sent to the PHP scr ...