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> {
}
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).
400 Bad Request A 400 status code means that the server could not process an API request due to invalid syntax. A few possibilities why this might happen are: A typo or mistake while building out the request manually, such as mistyping the API endpoint, a header name or value, or a query parameter.
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',
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With