Reputation: 419
I am receiving 400 Bad Request for the AJAX Post method. I am using Spring Data Rest Services at Backend. Below is the code I am having on front end for JS
var url = "/udb/data/SecurityRoleGroup",
groupData = {id:"",name:"",accesslevel:"",roles:[]};
groupData.id = groupId.val();
groupData.name = groupName.val();
groupData.accesslevel = groupDescription.val();
groupData.roles = multiselect_to.val();
$.ajax(url, { type: 'POST',
dataType: 'json',
headers: {
'X-CSRF-Token': _csrfGroup.val(),
'Content-Type' : 'application/json'
},
data: JSON.stringify(groupData),
contentType: 'application/json',
})
.done(function(results) {
showMessage.html("Group details are saved successfully.");
showMessage.removeClass().addClass("alert alert-success").show();
})
.fail( function(xhr, textStatus, errorThrown){
showMessage.html("Error : Rolegroup AJAX request failed! Please try again.");
showMessage.removeClass().addClass("alert alert-danger").show();
});
Although I am serializing the JSON data. Still I am receiving the 400 Bad Request error. Can this error come if some code is breaking on backend or its issue with the request sent to the server?
JAVA Implementation
@RepositoryRestResource(collectionResourceRel = "SecurityRoleGroup", path = "SecurityRoleGroup")
public interface SecurityRoleGroupRepository extends PagingAndSortingRepository<SecurityRoleGroup, Long> {
}
Upvotes: 6
Views: 3009
Reputation: 244
1.Why you need to send the data converting string you can sent the data as it is 2.you need not to put content type as application/json since you defined as json in data type 3.if you use post method here make sure you are handling the same in the server side
Upvotes: 0
Reputation: 2767
if you have spl characters in your data you need to encode the data before you send to server. Try this
$.ajax(url, { type: 'POST',
dataType: 'json',
headers: {
'X-CSRF-Token': _csrfGroup.val(),
'Content-Type' : 'application/json'
},
data: encodeURI(JSON.stringify(groupData)),
contentType: 'application/json',
})
Upvotes: 6