Youss
Youss

Reputation: 4212

POST headers and body using Jquery AJAX

I have to send a POST to a broker API including headers and a body:

Action  POST https://demo-api.ig.com/gateway/deal/session

Header  
Content-Type: application/json; charset=UTF-8
Accept: application/json; charset=UTF-8
X-IG-API-KEY: 5FA056D2706634F2B7C6FC66FE17517B

Body    
{ 
"identifier": "A12345", 
"password": "112233" 
} 

The API is here: https://labs.ig.com/rest-trading-api-guide

The problem is that every example on the internet sends the data as "data" like this:

jQuery.ajax(

{

url : 'https://demo-api.ig.com/gateway/deal/session',

type: 'POST',

dataType : "json",

data: {identifier: "A12345", password: "112233"}

});

I don't understand this, where is the header and the body? All examples look basically like this, I can't make heads or tail out of this.

Upvotes: 2

Views: 19674

Answers (2)

Vishnu Atrai
Vishnu Atrai

Reputation: 2368

Using beforeSend call back function and set headers. try below code -

jQuery.ajax({
  url : 'https://demo-api.ig.com/gateway/deal/session',
  type: 'POST',
  dataType : "json",
  data: {identifier: "A12345", password: "112233"}
  beforeSend: function(xhr){xhr.setRequestHeader('X-Header', 'header-value');},    
});

Upvotes: 1

Saar
Saar

Reputation: 2306

The data is for the post parameters in your case, headers have their own object.

jQuery.ajax(

{

url : 'https://demo-api.ig.com/gateway/deal/session',

type: 'POST',

dataType : "json",

headers: {"X-IG-API-KEY":"5FA056D2706634F2B7C6FC66FE17517B"},

data: {identifier: "A12345", password: "112233"}

});

Upvotes: 5

Related Questions