Make ajax call from gsp page in grails

13,284

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
            }
        });
    }
Share:
13,284

Related videos on Youtube

Sumon Bappi
Author by

Sumon Bappi

Each person should have two virtue in life. One # Patience &amp;&amp; Two # Gratefulness

Updated on September 14, 2022

Comments

  • Sumon Bappi
    Sumon Bappi over 1 year

    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
    }
    
  • Sumon Bappi
    Sumon Bappi over 10 years
    thanks for the help. First one works for me. But it's not giving alert for the success. Only the controller's action is being called.What should I do now ?
  • Jai
    Jai over 10 years
    you can try adding error function to your ajax, and see if your controller is producing "json" properly.
  • Sumon Bappi
    Sumon Bappi over 10 years
    yes my json is not building properly. Now I have change it to html. It's ok now. But can you give me a link of complete ajax call structure please. thanks.