Reputation: 1
I'm using a post Ajax to call a controller, however i do not get a response and get error.
I see that the controller also gets null on the user name where ajax get properly Below is my code
Ajax is hitting the controller and the input value (username) is print as null in the systemout, hence not getting the expected value
My Spring Controller
@Controller
public class SearchController {
UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@PostMapping("/api/search")
public String getSearchResultViaAjax(String username) {
System.out.println(username);
String result=userService.findByNativeByName(username);
return result;
}
}
My Ajax which submits post
function fire_ajax_submit() {
var name = $("#username").val();
$("#btn-search").prop("disabled", true);
$.ajax({
type: "POST",
contentType: "text/plain",
url: "/api/search",
data: name,
dataType: 'text',
cache: false,
timeout: 600000,
success: function (data) {
var json = "<h4>Ajax Response</h4><pre>"
data + "</pre>";
$('#feedback').html(json);
console.log("SUCCESS : ", data);
$("#btn-search").prop("disabled", false);
}
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>"
+ e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
$("#btn-search").prop("disabled", false);
}
});
}
My html
<form class="form-horizontal" id="search-form">
<div class="form-group form-group-lg">
<label class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<fieldset>
<p>
<select id = "username" class="form-control">
<option value = "Kilu">Kilu</option>
<option value = "Maha">Maha</option>
</select>
</p>
</fieldset>
</div>
</div>
</form>
Any help will be much appreciated
Upvotes: 0
Views: 2832
Reputation: 119
1) Your Spring Controller should be @RestController or @Controller with method annotated as @ResponseBody.
2) Post data like this ==> data: { "username": name },
3) After receiving the data, use stringify() to display it, and use JSON.parse() to extract the value.
4) Check your Content type header parameter(contentType: 'application/json; charset=utf-8;')
Upvotes: 1
Reputation: 67
Try to change the contentType,
contentType: 'application/json; charset=utf-8;'
And also put ','(comma) after the success block.
Upvotes: 0
Reputation: 957
You need to put a "," (comma) after your success block ,otherwise you will keep on getting the same error on your page on console :-
success: function (data) {
//your code
}, // right here to indicate the end of this block here as you're putting your error block after this.
Upvotes: 0