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
}
});
}
Related videos on Youtube
Author by
Sumon Bappi
Each person should have two virtue in life. One # Patience && Two # Gratefulness
Updated on September 14, 2022Comments
-
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 over 10 yearsthanks 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 over 10 yearsyou can try adding error function to your ajax, and see if your controller is producing
"json"
properly. -
Sumon Bappi over 10 yearsyes 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.