I need to send an XML type data to backend using jquery, ajax as a DELETE request. This returns empty array from backend request body. How can I send id properly?
here is my code,
JavaScript
x
18
18
1
function deleteProduct(id) {
2
3
var xmlDocument = $(
4
`<productsData>
5
<Prod_ID>${id}</Prod_ID>
6
</productsData>`);
7
8
$.ajax({
9
type:"DELETE",
10
url:"http://localhost:8000/delete",
11
data:JSON.stringify({
12
data : xmlDocument
13
}),
14
contentType: 'application/json',
15
dataType: 'text'
16
});
17
}
18
I need to send this data,
JavaScript
1
4
1
<productsData>
2
<Prod_ID>2</Prod_ID>
3
</productsData>
4
this 2 comes from the function parameter.
this is my backend in express
JavaScript
1
7
1
app.delete('/delete',(req,res,next)=>{
2
console.log(req.body);
3
res.status(200).json({
4
message: "success"
5
})
6
})
7
this returns empty object.How can I solve this?
Advertisement
Answer
If you want to send XML, don’t say you’re sending application/json
:
JavaScript
1
9
1
function deleteProduct(id) {
2
return $.ajax({
3
type: "DELETE",
4
url: "http://localhost:8000/delete",
5
data: `<productsData><Prod_ID>${id}</Prod_ID></productsData>`,
6
contentType: 'application/xml'
7
});
8
}
9
By returning the Ajax request, you can do something like this:
JavaScript
1
7
1
deleteProduct(42).done(function () {
2
// delete completed, remove e.g. table row...
3
}).fail(function (jqXhr, status, error) {
4
// delete failed, keep table row & show alert
5
alert("Could not delete product: " + error);
6
});
7