Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make ajax call from gsp page in grails

I am new to ajax. I am trying to send a request from my gsp page to controller action. But I am failing. It is not calling controller action and the page is reloading. Can anyone please look at this and help. Here is my view page bellow >>>

    <%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
  <title>Ajax First Example</title>
    <g:javascript plugin="jquery" library="jquery" src="jquery/jquery-1.7.2.js"/>
    <script>
        function callAjax(){
            $.ajax({
                url: "returnMe",
                type:"post",
                dataType: 'json',
//            data:{ids:JSON.stringify(idList), option:option, id:id}
                success: function() {
                    alert(1)
                }
            });
        }
    </script>
</head>
<body>
<form name='myForm'>
    <input type="submit" value="Call Ajax Function" onclick="callAjax()">
</form>
</body>
</html>

here is my controller action >>>

def returnMe = {
    String msg = 'sdfsdf'
    render msg as JSON
}
like image 484
Sumon Bappi Avatar asked Mar 21 '23 12:03

Sumon Bappi


1 Answers

You can try this :

onclick="callAjax() return false;">

or this one:

function callAjax(e){ //<-------pass the event
        e.preventDefault(); // <-----add this to prevent the default behavior
        $.ajax({
           .....
        });
}

Your complete ajax call as requested:

function callAjax(){
        $.ajax({
            url: "returnMe",
            type:"post",
            dataType: 'json',
//          data:{ids:JSON.stringify(idList), option:option, id:id}
            success: function(data) {
                console.log(data); //<-----this logs the data in browser's console
            },
            error: function(xhr){
                alert(xhr.responseText); //<----when no data alert the err msg
            }
        });
    }
like image 153
Jai Avatar answered Apr 05 '23 13:04

Jai