ajaxgrailsgsp

How can i get a value from the controller to my gsp page using AJAX


I am new to AJAX and grails so any help is appreciated. on my GSP page, on button click I am trying to retrieve a variable from the controller:

$.ajax({
                url:'${createLink(controller: 'store', action: 'getNum')}',
                type: 'GET',
                dataType: 'json',
                data: {num: num}, // the num is defined before and access properly
                error: function() {
                    alert("error");
                },
                success: function(data) {
                    alert(data);
                }
            });

this is my controller function:

    def getNum(){
        String num = params.num
        Long locnum = num as Long
        int result = storeService.getNum(locnum)
        String json = JsonOutput.toJson([count: result])
        return json
    }

I am going into the error and getting an "error" alert. I was wondering how I could utilize AJAX to get the number I need for my GSP page?

Thank you.


Solution

  • I would modify your JavaScript code like so:

    $.ajax({
        url:'store/getNum',
        method: 'POST'
        data: {'num': num}, // the num is defined before and access properly
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
    

    And then modify your Grails controller code like so:

    def getNum() {
        Long locnum = = params.long('num')
        int result = storeService.getNum(locnum)
        return render([count: result] as JSON) // you will need to import grails.converters.JSON
    }
    

    A tip for the future is to set a breakpoint in your Grails controller method and run the application in Debug mode to ensure that the controller method is being called. If it is not being called, click on the Network tab on your internet browser's Developer Tools and then press the button on your GSP page to inspect the HTTP request being made by the AJAX call.