Kamyar Parastesh Kamyar Parastesh - 1 year ago 65
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"
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>
function sendURL() {
var url = '/updatePing';
console.log("URI sent :)")


<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}">
<button id="submit-button" type="submit" class="btn btn-default" onclick="sendURL()">Submit</button>
<div id="resultsBlock">


<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>

I expect that, after pushing button the js function (
) 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();

return "fragments/success";
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
tag, in the main page.

So how can i fix this problem?

Answer Source

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

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