Kamyar Parastesh Kamyar Parastesh - 5 months ago 18
Javascript Question

Ajax does not respond correctly

I am trying to make an Ajax request from a thymleaf page. I have seen this.

Here is my html page:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Document</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>
<script>
function sendURL() {
var url = '/updatePing';
console.log("URI sent :)")

$("#resultsBlock").load(url);
}
</script>
</head>
<body>

<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Ping setup</div>
<div class="panel-body">
<form class="form-horizontal" th:object="${ping}" th:method="post" th:action="@{/updatePing}">
bla
bla
bla
<button id="submit-button" type="submit" class="btn btn-default" onclick="sendURL()">Submit</button>
</form>
</div>
</div>
<div id="resultsBlock">
</div>

</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>


I expect that, after pushing button the js function (
sendURL()
) get called and then it sends the params to my controller. This part is working as well

but the answer which comes from controller does not place in the
<div id="resultsBlock">


here is my controller:

@RequestMapping(value="/updatePing", method=RequestMethod.POST)
public String updatePing(@ModelAttribute PingDTO pingDTO) throws Exception{
PingRequestValidation pv=new PingRequestValidation();
if(pv.checkPingRequestValidation(pingDTO.getUrl())){

return "fragments/success";
}
else
return "fragments/failure";
}


The problem is, the controller exactly presents the success and failure pages,
meanwhile i expect that these fragments get presented in the
resultsBlock
tag, in the main page.

So how can i fix this problem?

Answer

To submit whole form using ajax, remove the onclick on button and create a submit handler using jQuery

$(function(){
   $('#formId').on('submit', function(event){
       event.preventDefault();// stop browser submitting from
       var data = $(this).serialize();
       $.post('/updatePing', data , function(response){
             $("#resultsBlock").html(response);
       }).fail(function(){
             alert('Something went wrong')
       });
   });
});
Comments