Robert Stober Robert Stober - 1 year ago 44
Javascript Question

Invalid json in ajax request

The goal is to successfully POST a new job to the marathon REST API. I'm using jQuery v1.12.4

The following code is getting values from a form and printing valid json to the console.log. I've verified it using JSONLint. But it doesn't seem to be getting to the server. here's the JSON that's being printed to the log, and that I see in firebug:

{"id":"basic-0","cpus":"0.1","mem":"32","instances":"1","cmd":"while [ true ] ; do echo 'Hello Marathon' ; sleep 5 ; done"}

I'm getting 400 Bad Request, and then I see this crazy response (in firebug):

{"message":"Invalid JSON","details":[{"path":"/instances","errors":["error.expected.jsnumber"]},{"path"

I have no idea what that response means. Is it coming from jQuery or the server? Does anyone know of a working example of calling the marathon REST API from javascript?

Here's the code. Yes, I know it's really bad practice to pass the username and password in the request, but I haven't figured out how to use the basic authentication yet, not have I yet figured out how to enable SSL on the marathon webserver. Baby steps...

var $form = $('#appsubmit1');

$form.submit(function() {
var form2json = JSON.stringify($('form').serializeObject());
type: 'POST',
url: '',
data: form2json,
dataType: 'json',
contentType: "application/json; charset=utf-8",
timeout: 10000
}).done(function(resp, status, xhr) {
console.log("ajax function done: ", status);
}).fail(function(xhr, status, errmsg) {
console.log("error: ", status);
console.log("error: ", errmsg);
return false;

Answer Source

The error clearly states that the service requires a number instead of a string for cpus, mem and instances fields. Try to post with this json:

    "id": "basic-0",
    "cpus": 0.1,
    "mem": 32,
    "instances": 1,
    "cmd": "while [ true ] ; do echo 'Hello Marathon' ; sleep 5 ; done"