Skip to content Skip to sidebar Skip to footer

From Curl To Jquery’s $.ajax() Function

I'm trying to convert the curl code from an API called TextRazor to jquery's AJAX because of a platform limitations. I have tried many solutions from similar questions by the commu

Solution 1:

I think you have to pass "x-textrazor-key: YOUR_API_KEY" as additional header

$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('x-textrazor-key', 'YOUR_API_KEY');},
data: { 
   extractors: "entities,entailments",
   text:"Spain's stricken Bankia expects to sell..." 
},
success:function(data) {
    alert(JSON.stringify(data));
},error: function(xhr) {
    alert("<some error>");
    console.error(xhr.responseText);
}});

Solution 2:

data: { 
   x-textrazor-key: "YOUR_API_KEY",

The data: bracket in jQuery means that you want to send that data as POST, while you need to send the API key as a header.

Add this field to your code (after URL or so):

headers: {"x-textrazor-key": "YOUR_API_KEY"}

Solution 3:

This looks close to me, but you put the header into the POST body. I think it should be the below. (Note that you also need quotes around 'x-textrazor-key', since the dashes in it will otherwise be interpreted as subtraction.)

$.ajax({
    url: "https://api.textrazor.com/",
    type: "POST",
    dataType: 'json',
    headers: {
       'x-textrazor-key': "YOUR_API_KEY"
    },
    data: { 
        extractors: "entities,entailments",
        text: "Spain's stricken Bankia expects to sell..." 
    },
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (xhr) {
        alert("<some error>");
        console.error(xhr.responseText);
    }
});

There could of course be other issues here. (E.g. perhaps the API doesn't support cross-origin requests.) You'll want to take a look at the network tab in your browser's developer tools to see what actually happens.

Post a Comment for "From Curl To Jquery’s $.ajax() Function"