0

I have a form with only 2 inputs. I wanna send a JSON to my POST method. Although, all possibilities give back this error:

415 (Unsupported Media Type)

I tried used this 3 ajax:

        console.log($("#idform").serializeArray());
        console.log($("#idform").serialize());
        var nome = "\"" + $("#idnome").val() + "\"";
        var idade = "\"" + $("#ididade").val() + "\"";
        var all = "{\n"+"\"name\": "+nome+",\n"+
           "\"idade\": "+idade+"\n"+"}";
        console.log(all.toString());
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : all           
        })
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : $("#idform").serializeArray()           
        })
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : $("#idform").serialize()          
        })

Here is what I got after printing them on console:

nome=yrt&idade=09    //$("#idform").serialize()

{
"name": "yrt",       //all
"idade": "09"
}

And $("#idform").serializeArray() returned [("name","yrt"),("idade","09")]

rado
  • 5,720
  • 5
  • 29
  • 51
  • 1
    Your server is getting data it doesn't expect, and returns a `415`. Without the serverside code, it's impossible to tell why – adeneo Nov 23 '16 at 17:37
  • Possible duplicate of [jquery ajax rest call - Unsupported Media Type](http://stackoverflow.com/questions/10028335/jquery-ajax-rest-call-unsupported-media-type) – Daniel W. Nov 23 '16 at 17:38

1 Answers1

3

You need to add the following

contentType: 'application/json'

contentType is what format you are sending to the server

dataType is what format you are expecting back form the server

$.ajax({
  url : 'http://localhost:8080/DBRest/rest/escreve',
  type : "POST", // type of action POST || GET
  contentType : 'application/json', // data type
  data : all           
})
curv
  • 3,796
  • 4
  • 33
  • 48
  • Good guess, but how do you know what the server is expecting, the OP hasn't told us what serverside language is being used *(all though I'd guess Java)* – adeneo Nov 23 '16 at 17:46
  • Good point but does answer his question which was how to send a correct AJAX JSON – curv Nov 23 '16 at 17:56
  • @Zinc thanks a lot for your patience, that was exactly my problem. – rado Nov 24 '16 at 11:25