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 community but can't seem to get any data back (through the alert dialog). If it matters
from the documentation calling the API looks like this:
curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/
My current AJAX code looks like this:
$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
data: {
x-textrazor-key: "YOUR_API_KEY",
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);
}});
here is the link to jsfiddle if it helps: jsfiddle.net
Thanks for your support!
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);
}});
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"}
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.
Related
I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});
I am a problem with simple javascript web page hosted on AWS S3 that makes a HTTP POST to AWS API Gateway using ajax.
I am able to make a call using curl with success:
curl -X POST -H "Content-Type: application/json" https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta --data #data.json
data.json file:
{ "imie": "jasiu",
"ocena": "6",
"opinia": "niezle"
}
My javascript code looks like this.
<html>
<body>
<title>Ankieta</title>
<h1>Wypelnik ankiete</h1>
<button type="button" onclick="uruchom()">JSON</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function uruchom() {
var resultDiv = $("#resultDivContainer");
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: JSON.stringify(myData),
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
};
</script>
</body>
</html>
This is the error I get from web debug:
GET https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta?callback=jQuery17203000220305941388_1546897907447&{%22imie%22:%22Michal%22}&_=1546897908872 net::ERR_ABORTED 400
It looks like there is problem with callback and in the URL is altered with my data from body. In my case I don't want to check whenever the callback is fine - want to simply POST data.
Thanks for any suggestions.
POST can't be used to send a JSONP request. JSONP doesn't actually use AJAX, it works by creating a <script> tag whose src is the URL. There's no way to send POST data this way, so the data is added as URL parameters.
If this API expects the JSON in POST data, you can't use dataType: 'jsonp'. You have to use dataType: 'json'. If the API doesn't allow CORS, you'll need to use a proxy on your server to make the actual request, you can't do it directly from the browser.
Dont stringify the data object. JQuery does this for you. Just pass object.
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: myData,
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
Thanks for suggestions and answers especially in CORS direction. I was sure my API GW has CORS enabled, but didn't check AWS Lambda that is behind it and found that I was not returning "Access-Control-Allow-Origin" header back to client.
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
After applying this, I can send HTTP POST.
I am making a basic PATCH call like this one:
.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: {
"foo": "foosball",
"bar": "bars on bars"
},
...
});
Jquery automatically encodes the data, which leaves "bars on bars" like "bars+on+bars". Is there a way to change the encoding so that spaces are replaces with %20 rather than pluses?
I've noticed this thread that didn't seem to lead anywhere.
I've also taken note of encodeURI and encodeURIComponent but haven't gotten either to work. Both seem to result in the string being double encoded, leaving me with bars%2520on%2520bars
summary:
What I start with:
... "bars on bars" ...
What the received data looks like after jquery encodes the request:
"bars+on+bars"
What I need the received data to look like:
"bars%20on%20bars"
How about use a variable and pass that to data.
var d={
"foo": "foosball",
"bar": "bars on bars"
}
d.bar=encodeURI(d.bar);
.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: d,
...
});
Still wish there was a better way, but I ended up using this plugin from this website.
jQuery.extend({
postJSON: function(url, data, callback) {
return jQuery.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
This forces my api to parse the body as a string into a dict/json. Hopefully in a few years someone can come along with a better solution.
I am facing the following problem, I am trying to build a small application to search within the Odata dataset from the KVK (dutch chamber of commerce) to retrieve data based on file numbers, ZIP codes or tradenames.
My ajax code looks like this:
$.ajax({
url: urls,
error: function(){console.log('FAILED!')},
headers:
{
"Content-Type":"application/json",
"ovio-api-key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
dataType: 'jsonp',
complete: function(data) {
console.log(data);
}
});
the URL would like like this:
https://overheid.io/api/kvk?&filters[postcode]=3553BA&callback=jQuery110208921047365292907_1432134770039&_=1432134770040
The error I am getting:
The part I do not understand, when I try the exact same URL in a web rest client such as chrome's advanced rest client the result is exactly what I want:
Fixed this by changing the code to:
$.ajax({
type: 'GET',
url: urls,
error: function(){console.log('Gefaald!')},
headers:
{
"Content-Type":"application/json",
"ovio-api-key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
dataType: 'json',
complete: function(data) {
console.log(data);
}
});
just had to add the 'GET' type.
I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});