For some reason my jQuery ajax request is not working. Every time I click on the button which calls the below javascript, the POST is not sucessful and I get the error:
{"status":"KO","message":"error"} (see my controller action method).
If I use curl, it works fine and I get the response "it works!":
curl --include --request POST --header "Content-type: application/json" --data '{"articleId":28, "isApproved": true}' http://localhost:9000/article/changeStatus
I seem to be doing everything correctly, I am stringify'ing the json part, setting the content type, what could be wrong here?
var d = JSON.stringify({"articleId": articleId, "isApproved": isApproved});
$.ajax({
"type": "POST",
"url": "/article/changeStatus",
"data": d,
"dataType": "json",
"contentType": "application/json;charset=utf-8",
"success": function(p) {
alert('success is ' + p.isSuccess + ' message=' + p.message);
},
"error": function(p) {
},
"complete": function(p){
}
});
My controller action looks like:
def changeStatus = Action(BodyParsers.parse.json) { request =>
val changeStatusRequest = request.body.validate[ChangeStatusRequest]
changeStatusRequest.fold(
errors => {
BadRequest(Json.obj("status" ->"KO", "message" -> "error"))
},
cmRequest => {
Ok("it works!")
}
)
}
case class ChangeStatusRequest(articleId: Int, isApproved: Boolean)
The reads is:
implicit val changeStatusRequest: Reads[ChangeStatusRequest] = (
(JsPath \ "articleId").read[Int] and
(JsPath \ "isApproved").read[Boolean]
)(ChangeStatusRequest.apply _)