How to request data from an API using AJAX. - javascript

I want to make a post request to an API (http://nairabox.com/food_documentation/) using Ajax but am kind of confused on how to go about it.
This is what I have tried so far:
$.ajax({
type: "POST",
url: "https://mapp.nairabox.com:8443/api/v1/food/",
dataType : "json",
data: { case: "browse"},
headers: {
'case': 'browse'
},
success: function(data){
console.log('success');
}
})
So far, it is returning no result.
What could I be getting wrong?
The API doc is here (http://nairabox.com/food_documentation/)

The documentation you link to does not say to add any custom HTTP request headers.
You, however, are doing so here:
headers: {
'case': 'browse'
},
The case data belongs in the data and only in the data.
By adding the custom header, you are preventing the request from being simple and triggering a preflight OPTIONS request which the server does not accept.
Remove the above and you will get a response (and your success function will fire … you should probably do something with the data argument though)
Note, also, that the documentation says you should pass latitude and longitude as well as case.
Unless you add them, the response you get is unlikely to be useful.

Related

How to do a POST request with headers?

Right now, I'm trying to do a post request:
https://aleapisoap.azure-api.net/httpbin/listSearchFields
And I need a body which is this:
{
"listSearchFields": {
"email": "sample"
}
}
I tried this in postman and works but with this code in JavaScript doesn't work.
$.ajax({
url: 'https://aleapisoap.azure-api.net/httpbin/listSearchFields',
headers: {
'Content-Type':'application/json',
'Cache-Control':'no-cache',
'Ocp-Apim-Trace':'true',
'Ocp-Apim-Subscription-Key':'19f2a7fd474840bfb5fc729cd97b7335'
},
type: 'POST',
dataType: 'jsonp',
data: '{"listSearchFields":{"email":"sample"}}',
success: function(data){
console.log('succes: '+data);
}
});
This is the error:
net::ERR_ABORTED 404 (Resource Not Found)
The headers in your $.ajax() call look correct to me. I think the "listSearchFields" endpoint doesn't exist at https://aleapisoap.azure-api.net/httpbin/ like you're expecting. Check your spelling first - if you're spelling "listSearchFields" correctly, you'll have to dive deeper to figure out why it's not being found.
dataType: 'jsonp',
JSONP requests are incompatible with setting custom request headers or making POST requests. They work by injecting a <script> element with a src attribute (which makes a GET request).
If you need to make a POST request, don't use that dataType. You probably want 'json'.
JSONP is a hack that was used to work around the Same Origin Policy before CORS was available. You might have to take other steps to ensure the endpoint is available to your origin.

AJAX call error - status of 400 (Bad Request)

I'm trying to use the BloomAPI to retrieve Doctor's NPI number by querying with their first and last name. I'm using Jquery Ajax to make a get request for the JSON data.
I am able to get the JSON data when I do CURL in the terminal: curl -X GET 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN'
For the purpose below - I just hardcoded in the params into the URL.
I get a "Failed to load resource: the server responded with a status of 400 (Bad Request" Error. Any idea what I might be doing wrong?
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp'
}).done(function(server_data) {
console.log(server_data)
}).fail(console.log("failed"));
This was a weird one... your code is actually basically correct, however, it appears bloomapi does not support disabling caching in the way jquery does it.
When you make the jquery call you have, the actual url becomes something like this:
http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN&callback=jQuery111207365460020955652_1428455335256&_=1428455335257
The callback is a jsonp construct, and the _ is a way of breaking caching. However, bloomapi appears to not like this:
jQuery111207365460020955652_1428455335256({"name":"ParameterError","message":"_ are unknown parameters","parameters":{"_":"is an unknown parameter"}});
To get around this, you can disable cache busting like so:
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp',
cache: true
}).done(function(server_data) {
console.log(server_data)
}).fail(function() { console.log("failed") });
You will have to be careful of how else you break the cache if that's an issue; the api provider may be able to provide feedback on how to do this.
In the future, you can easily check the errors you are receiving/what you are sending using a web debugger; I used Fiddler to figure this out.

Make $.ajax call to url without knowing dataType

I'm trying to set up a generic call to webservices using jquery $.ajax. I'd like to be able to get raw data back and bind it to a grid.
I have calls working correctly when I know the dataType, but I want to try and make an ajax call without knowing the datatype, specifically to find what the dataType is.
For example, my ajax call knowing the datatype could be:
$.ajax({
type: 'GET',
crossDomain: true,
dataType: "jsonp",
url: 'http://itunes.apple.com/search?term=coldplay',
success: function (res, status, xhr) {
//DoStuff;
},
error: function (jqXHR, textStatus, errorThrown) {
//DoStuff
}
});
But any time I make a request without knowing the datatype I simply get a response status of "Error"?
What I would eventually like to be able to do with this is ping a url (webservice) that returns json, xml, or perhaps odata(unlikely). Since I won't know which, I want to be able to simply make a call to the url once to find out what kind of data I might get back, along with what content-type there is.
I've tried simply getting back the content type in the header in the error, but so far nothing I've tried has worked or returned anything at all.
$.ajax({
type: 'GET',
crossDomain: true,
url: 'http://itunes.apple.com/search?term=coldplay',
success: function (res, status, xhr) {
//DoStuff
},
error: function (jqXHR, textStatus, errorThrown) {
$("#results").html(textStatus + jqXHR.getResponseHeader('Content-Type'));
}
});
Can this even be done with Jquery?
Edit
I am aware that this can (and in most cases should) be done server side, and in all likelihood this is what will end up happening. But for the purposes of seeing how far I can go binding a grid to a datasource clientside without knowing my dataType the above question is born.
Thanks to all for the time.
Your approach is reasonable, but you are asking the user's browser to fetch information from a third party web server.
XMLHttpRequest cannot load http://itunes.apple.com/search?term=coldplay. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Unless the third party grants you permission, the Same Origin Policy will prevent your JavaScript from accessing any information about the response.
You should move your logic server side.

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

JQuery ajax call to cross-domain webservice

I would like consume cross-domain web-service from client with jquery
function TestService() {
$.ajax({
url: "http://service.asmx/GetGeoCompletionList",
data: { "prefixText":"eka", "count":"10", "contextKey":"Trace_0$Rus" },
dataType: "jsonp",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.statusText);
}
});
}
At the error hander I have:
textStatus=parseerror
XMLHttpRequest has status 200 and readyState 4
errorThrown is jQuery16103495572647140...78197139 was not called
I've spent on it for a lot of hours and couldn't make it work. Can u help me?
UPDATED
Thanks, I change to GET, and fix my data string.
Service returns valid JSON object. I can see it at firebug on other site, which consume this service. But that site is getting common json(since it has one domain).
So, if the web-service returns valid JSON(not jsonp), I can't use the same method with jsonp? What can I do for consiming json web-service from other domain?
That string you are passing and claiming is JSON isn't JSON.
Only " characters may be used to quote strings.
Also, you can't make a cross domain JSON-P POST request.
You cannot do cross-domain POST requests using JSONP. JSONP works by adding script tags to the page. script tags always fetch their source using GET HTTP requests. You won't get any data posted.
Summary of problems:
Make sure you're using valid JSON
as #Quentin mentioned.
Make sure you're using GET requests, as
#lonesomeday mentioned
Make sure the response from the server is
JSONP, as seen here

Categories