POST headers and body using Jquery AJAX
16,975
Solution 1
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');},
});
Solution 2
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"}
});
Author by
Youss
Updated on June 04, 2022Comments
-
Youss almost 2 years
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.
-
Saar over 8 yearsSince jQuery 1.5 (which is already quite old) you can use
headers: {"header Name":"Header Value"}
which is the better approach in my opinion.