How to do a POST request with headers? - javascript

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.

Related

How to request data from an API using AJAX.

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.

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.

Unable to perform a Cross domain ajax call. - JQuery

I have checked many post and tried every logic that were mentioned in various blogs and posts. But I am unable to perform a cross domain ajax call to an IIS server. Please anybody advice what else I should look into or configure it to get working. All your help is greatly appreciated.
Here is my ajax call:
var url = "http://mydomain .com/myauthorizeservice";
var jsonParam = JSON.stringify({ username: 'user007', password: 'pass007' });
$.ajax({
type: "POST",
url: url,
crossDomain: true,
data: jsonParam,
success: fnSuccess,
error: fnError,
dataType: "json",
contentType: "application/json"
});
function fnSuccess() {
alert("Success");
}
function fnError() {
alert("Error");
}
My config in the root web.config:-
Error:-
Access Denied.
I really struggled a lot to make this thing work. Here some points that also matters and restrict the cross domain calls-
Note: I am using WCF REST service. and configurations are for IIS 7.5.
1: Make sure your OPTIONSVerbHandler looks like-
2: Make sure you have the correct ordering in HandlerMappings-
Rest settings and the way to perform ajax call is mentioned in the question.
Happy coding!

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

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