Reputation: 1678
I have a ajax post
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: 'POST',
url: '${contextPath}/sms/schedule',
data: '{"id":'+ ($('#idAttribute').val()?$('#idAttribute').val():null)
+ ',"repId":' + $('#repId').val() + ',"scheduleDate":"'
+ $('#scheduleDate').val()+ '","scheduleTime":"'
+ $('#scheduleTime').val() + '","message":"'
+ $('textarea#message').val() + '"}',
success: function (data) {
$('#schedule-sms-modal').modal('hide');
window.location.replace("${contextPath}/sms/list");
},
error : function(jqXHR, textStatus, errorThrown){
}
});
the text area #message
contain new lines. So the Java back end fail to parse the request and give a 400 bad request.
I tried JSON.stringify($('textarea#message').val())
and also replace new line with following function as well.
var removeEscapeCharacters = function(myJSONString){
myJSONString.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
}
Didn't help. I'm kind of lost to identify the room cause of this issue.
Upvotes: 1
Views: 2257
Reputation: 97707
Don't build JSON by hand use JSON.stringify
data:JSON.stringify({id: $('#idAttribute').val()?$('#idAttribute').val():null,
repId:$('#repId').val(),
scheduleDate: $('#scheduleDate').val(),
scheduleTime: $('#scheduleTime').val(),
message: $('textarea#message').val()
}),
Upvotes: 1
Reputation: 7890
What I think you really want to do is stringify()
your object first and then pass that as the data
parameter.
var data = {
id: ($('#idAttribute').val() ? $('#idAttribute').val() : null),
repId: $('#repId').val(),
scheduleDate: $('#scheduleDate').val(),
scheduleTime: $('#scheduleTime').val(),
message: $('textarea#message').val()
};
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: 'POST',
url: '${contextPath}/sms/schedule',
data: JSON.stringify(data),
success: function (data) {
$('#schedule-sms-modal').modal('hide');
window.location.replace("${contextPath}/sms/list");
},
error : function(jqXHR, textStatus, errorThrown){}
});
Upvotes: 2