Mattia Lipreri
Mattia Lipreri

Reputation: 953

jquery set header in post request

I need to simulate this curl command

curl -i -H "Accept: application/json" -H "Content-type:application/json" -X POST -d '{"username":"pippo","password":"secret123"}' http://url.org/api/login

via jquery, I made in this way

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      headers: { 
        "Accept" : "application/json; charset=utf-8",
        "Content-Type": "application/json; charset=utf-8"
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

I still have has content-type text/html. Is it right?

Upvotes: 4

Views: 30285

Answers (4)

Maulik
Maulik

Reputation: 2991

if you still want to use .post() -> call this function before it

$.ajaxSetup({
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});

all jquery request after it will have these headers in it.

Upvotes: 1

electroid
electroid

Reputation: 661

Try beforeSend in your jQuery AJAX call:

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      beforeSend: function(xhr){
                xhr.setRequestHeader("Content-Type","application/json");
                xhr.setRequestHeader("Accept","application/json");
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

Upvotes: 3

DigitalZebra
DigitalZebra

Reputation: 41483

It appears to be working for me... Are you sure you are looking at the correct request? Take a look at the HTTP request in the following JSFiddle; it indeed contains the Content-Type header: http://jsfiddle.net/KqGY4/1/

$( document ).ready(function() {
    $.ajax({
      url:"http://fiddle.jshell.net/user/login",
      type:"POST",
      headers: { 
        "Accept" : "application/json; charset=utf-8",
        "Content-Type": "application/json; charset=utf-8"
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

Upvotes: 2

denolk
denolk

Reputation: 770

have you tried contentType option?

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      headers: { 
        "Accept" : "application/json; charset=utf-8"
      },
      contentType:"application/json; charset=utf-8",
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

Upvotes: 1

Related Questions