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.
Related
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.
I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int
How can I add a JSON file in jsfiddle? I have a JSON file but I am not able to attach it in jsfiddle. I can make a JSON object and use it, but is there any way to add an external JSON file to a fiddle?
Myjson.com provides api, which runs in Jsfiddle.net.
Custom my myjson:
// Loading JSON with CROS
var url = 'https://api.myjson.com/bins/3ko1q';
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
},
error: function (e) {
alert('error');
console.log(e);
}
});
Myjson GET Example:
// 1. Create valid uri via POST
// 2. GET using newly created uri
var obj = {
"key": "value",
"key2": "value2"
};
var data = JSON.stringify(obj);
$("#clickMe").click(function () {
$.ajax({
url: "https://api.myjson.com/bins",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// load created json
$.get(data.uri, function (data, textStatus, jqXHR) {
var json = JSON.stringify(data);
$("#data").val(json);
});
}
});
});
You can harness the power of Cross-Origin Resource Sharing (CORS) to achieve your task.
Basically how CORS works is that if the Access-Control-Allow-Orign header is set in the HTTP response, then the content loaded by AJAX can be used in our script regardless of the fact it is on the same domain or some other.
Now for your purpose, you can upload your local JSON file to Dropbox's Public folder and get a Public URL, that you can load by a simple AJAX call.
The AJAX call will succeed in this case because Dropbox sets the following value in the response Access-Control-Allow-Orign:* which means any domain can use the loaded content.
Jquery code will be something like this(you can even use pure JavaScript if you prefer ).
var url = 'https://dl.dropboxusercontent.com/u/94145612/example.json';
var myJsonData= {};
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
myJsonData= data;
},
error: function (e) {
alert('error');
console.log(e);
}
});
Example JSFiddle
Based on your comment, you want to use a pure JSON file as an external resource in a jsFiddle. You can't do this, because pure JSON is not JavaScript. Say you try to include http://example.com/foo.json as an external resource, and that file contains the following:
{"foo":"bar"}
This will result in Uncaught SyntaxError: Unexpected token :, because the JSON object is not valid JavaScript by itself.
But if you assign the JSON object to a variable, like so:
var foo = {"foo":"bar"};
then no problem.
Solution: use a modified version of your file to initialize a variable for use in the jsFiddle.
I'm currently trying to integrate the Stocktwits symbols multicall api into my website. Using ajax jsonp, I can indeed get it working and throw flags such as limit, but whenever I try to use the filter flag I receive a GET 500 error. What is strange is I can use said filter on the single symbol call api and it works fine. Could anyone point me in the right direction?
Like I said before, I can already get the symbols multicall to work, so it's not authentication, it's just the filter flag. Below are my working examples followed by my code that is not working. I am currently running this on localhost
Single call that works:
StocktwitsJsons = $.ajax({
url: "https://api.stocktwits.com/api/2/streams/symbol/AAPL.json?callback=?",
dataType: 'json',
data:{
limit:8,
filter: 'top'
},
success: function(data) {
if (data) {
callback(data, tickerList, assetIds);
}}
});
Multi-call that works:
stocktwitsJsons = $.ajax({
url: "https://api.stocktwits.com/api/2/streams/symbols.json?callback=?",
dataType: 'json',
data:{ access_token: token,
symbols: symbols,
limit:8
},
success: function(data) {
if (data) {
console.log(data);
callback(data, tickerList, assetIds);
}}
});
Multi call that does NOT work:
StocktwitsJsons = $.ajax({
url: "https://api.stocktwits.com/api/2/streams/symbols.json?callback=?",
dataType: 'json',
data:{ access_token: token,
symbols: symbols,
limit:8,
filter:'top'
},
success: function(data) {
if (data) {
console.log(data);
callback(data, tickerList, assetIds);
}}
});
We will correct the documentation this is an error. Currently we do not allow filtering on the multisymbol endpoint. It is on the roadmap to add. Sorry this is why it is not working for you.
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);
}
});
});