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
}
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
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With