I am new to AJAX and currently learning to use it with Spring MVC. I am facing issues on the same.
Before proceeding to the actual real time requirement that I am working on, I am testing out the whole AJAX+Spring MVC+jquery combination with something really basic to get my understanding right.
I am having a search box+'submit' button on a page. I am sending a hard coded text to the Spring controller on submit using $.get. Then I am sending another text from that controller back to the callback function and trying to display the returned text in the callback function using an 'alert' box. This doesn't seem to work.
I see that the call back function is being called(since the 'alert' inside the callback function is being fired) so I am kind of assuming that control is being transferred to the controller and back to the callback method but I am not able to figure out why the text that is returned from the controller is not showing up on the alert box in the call back method. Not sure what I am missing here to capture the return value in the call back method.
Your response and help on this is really appreciated.
Thanks.
HTML for text box and submit button:
<div class = "searchcontactform">
<form id = "searchcontactform" name="searchcontactform" method="GET">
<input type = 'text' size='25' name = "searchlastname" id = "searchlastname" value='Enter Last Name to Search'/>
<input type = "submit" value="Find">
</form>
</div>
JavaScript that triggers on submit of the above form:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/scripts/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},callback);
function callback(textreceived){
alert('In Callback. Text Received is: '+textreceived);
};
});
});
Controller:
@RequestMapping(value = "/search", method = RequestMethod.GET)
public @ResponseBody String searchcontact(@RequestParam(value="textsent") String textsent){
return textsent;
}
Jackson Dependency in POM.xml:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
Annotation driven in servlet-context.xml and root-context.xml:
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
first of all, put return false at the end of submit event handler
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search",
{
textsent : 'Hello Controller'
},
function(textreceived){
alert('In Callback. Text Received is: '+textreceived);
});
return false;
});
if this does not work try using Google Chrome you could debug your javascript application, put a breakpoint inside the callback and at the $.get line
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