I am learning ajax. Please find below code,
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="/MyApp/js/jquery.js"></script>
<script type="text/javascript">
function doAjax() {
alert('yes');
$.ajax({
url: 'register.html',
data: ({name : "me"}),
success: function(data) {
$('#time').html(data);
}
});
}
</script>
</head>
<body>
<form action="">
<button id="demo" onclick="doAjax()" title="Button">Get the time!</button>
<div id="time">
</div>
</form>
</body>
</html>
This code makes successful ajax call to my spring controller and return data only if i remove form tags otherwise it wont show ajax message (and no error as well).
I checked logs. If i remove form tag, last request received is to ‘register.html’ which is very correct. If i put form tag, on click of button, request goes to ‘hello.html’ which is the page which holds above code. I am not able to understand how is this happening.
One thing I was suspecting is form is getting sumitted. but how can this happen if i am not firing sumit event on click of button.
I need to have form tag on this page so please advice.
controller functions below,
@RequestMapping("/hello")
public ModelAndView helloWorld() {
return new ModelAndView("hello", "message", "Spring MVC Demo");
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public @ResponseBody String registerUser(@RequestParam String name) {
String result = "Time for registration" + name + " is " + new Date().toString();
return result;
}
Firstly, If you use the button tag inside the html form browser may interpret as the submit request. Which is why you do a button press with the form its no more an ajax request. Which could be noted when you render the homepage the url would be something like localhost:8000/home but after the button click url would be localhost:8000/home? which denotes there was a normal get request
If you still want the button to create a ajax request inside the form do something like this:
Secondly, try changing the url in your Ajax function to “/register.html/”. Mind the slashes. Since it could be possible in some cases where jquery would suggest append the given url to the page’s url.
For example, if your page url is localhost:8000/home. The request generated could be localhost:8000/home/register. So, its always a good idea to use slashes when you define your urls.
Laslty, try using some other extension instead of html since, html is conventionally used to generate static content and convent for dynamic content is htm. Its just a convention for a good practice rest is your choice.