Table of contents

Make the raw body in jQuery Ajax

Javascript Mar 05, 2020 Viewed 1.5K Comments 0

Using jQuery's $.ajax function to post data to server, The default Content-Type is application/x-www-form-urlencoded; charset=UTF-8. Sometimes we need to submit raw text, such as json, xml, html, etc. You can modify the headers property.

In order to set the raw body of the request, we should put the string format of the entire data into the data property. Set the headers and specify the corresponding http Content-Type so that the server can recognize it. 

Example for JSON

We can use JSON.stringify function.

var data = {
    username: "test",
    arr: [2, 3],
};
$.ajax({
    url: "/index.php",
    data: JSON.stringify(data),
    type: "post",
    headers: {
        "content-type": "text/plain;charset=UTF-8" // Add this line
        // "content-type": "application/json;charset=UTF-8" // Or add this line
    },
    beforeSend: function (){
        console.log("Waiting...");
    },
    error: function() {
        console.log("Error");
    },
    success: function (data){
        console.log(data);
    }
});

For xml

var data = '<xml><username>test</username></xml>';
$.ajax({
    url: "/index.php",
    data: data,
    type: "post",
    headers: {
        "content-type": "application/xml"   // Add this line
    },
    beforeSend: function (){
        console.log("Waiting...");
    },
    error: function() {
        console.log("Error");
    },
    success: function (data){
        console.log(data);
    }
});
Updated Jun 30, 2020