markzzz
markzzz

Reputation: 47995

How can I make a custom "POST" request on client side?

I need to do a POST request such as:

POST /feeds/api/users/default/subscriptions HTTP/1.1
Host: gdata.youtube.com
Content-Type: application/atom+xml
Content-Length: CONTENT_LENGTH
Authorization: Bearer ACCESS_TOKEN
GData-Version: 2
X-GData-Key: key=DEVELOPER_KEY

<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
  xmlns:yt="http://gdata.youtube.com/schemas/2007">
    <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat"
      term="channel"/>
    <yt:username>GoogleDevelopers</yt:username>
</entry>

I know how to do it server (.NET/C#) side for example, using HttpWebRequest object, settings Header/Method/ContentType.

But if I'd like to do it client side? Ajax with jQuery? Where can I set those parameters?

Upvotes: 3

Views: 5018

Answers (1)

jcubic
jcubic

Reputation: 66600

You can use this function:

function post(url, data, headers, success) {
    $.ajax({
        beforeSend: function(xhr){
            $.each(headers, function(key, val) {
                xhr.setRequestHeader(key, val);
            });
            xhr.setRequestHeader('Content-Length', data.length);
        }
        type: "POST",
        url: url,
        processData: false,
        data: data,
        dataType: "xml",
        success: success
    });
}

using code like this:

var request = '<?xml version="1.0" encoding="UTF-8"?>' +
       '<entry xmlns="http://www.w3.org/2005/Atom"' +
       '        xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
       '    <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat" term="channel"/>'+
       '    <yt:username>GoogleDevelopers</yt:username>' +
       '</entry>';

var headers = {
   'Content-Type': 'application/atom+xml',
   'Authorization': 'Bearer ACCESS_TOKEN'
   'GData-Version': 2
   'X-GData-Key': 'key=DEVELOPER_KEY'
};

post('/some/url', request, headers, function(response) {
   alert(response);
});

Upvotes: 4

Related Questions