Jquery Ajax Call to WEB API - javascript

I'm trying to make a simple jquery ajax call to a WEB API method.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'http://redrock.com:6606/api/values/get',
dataType: "jsonp",
crossDomain: true,
success: function (msg) {
alert("success");
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
WEB API action:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
ajax call does not hitting the WEB API. I get the below error in browser console.
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400 (Bad Request)

Unless you are doing a cross domain call, there is no need to use jsonp (jsonp also requires a custom formatter in Web API).
$.getJSON('http://redrock.com:6606/api/values', function(data){
console.log(data);
});
EDIT:
To install a jsonp media type formatter, have a look at this project: https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
Download the formatter using nuget
Register the formatter
Update your routeconfig

You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.
I would suggest either renaming the action or adding the [HttpPost] attribute to your action method. You may also try the WebApiRouteDebugger package.

Related

The requested resource does not support http method 'GET'. in 3rd party api controller

I used a 3rd party plugin that sends a POST request api controller and getting this error
"The requested resource does not support http method 'GET'."
.NET Controller
[HttpPost]
public WebApiResponseModel HandleContactForm(ContactFormViewModel model);
javascript
$.ajax({
url: "/Api/ContactForm/HandleContactForm/",
type: "POST",
data: object
success: function (result) {
////result here
},
error: function (data) {
//// right data error here
}
});
The controller is using library System.Web.Mvc. I can't edit it to replace to System.Web.Http becuase it is a 3rd party controller and placed in a dll.
My bad, I already resolved this by adding mail settings in the web.config
<mailSettings>
<smtp from="test#test.com">
<network host="smtp.gmail.com" port="587" userName="testuser" password="testpassword" enableSsl="true" />
</smtp>
</mailSettings>

Call WCF rest service with Javascript (JQuery) do not receive any response

The WCF service gets called for sure (the debug kicks in).
No response back to javasript callbacks.
If i configure the call with dataType:JSON the error callback is called.
If i configure dataType:JSONP no error occurs and no response is received (no callback happens neither error or sucess or done).
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json;charset-uf8",
crossDomain: false,
async: true,
url: "http://myurl",
done: function (results) {
// Uhm, maybe I don't even need this?
var parsed = JSON.parse(results);
alert(parsed);
return results;
},
success: function (data, text) {
alert(text);
alert(data);
},
error: function (request, status, error) {
alert(request);
alert(status);
alert(error);
}
});
I'm running this on localhost.
I have no clue at all, i don't even know how to get more in depth error details.
Any help appreciated.
Directly sending an HTTP request to call the WCF service applies the Restful style service. Thereby we should ensure that WCF service is restful style whereas mostly WCF service based on the SOAP web service, and the invocation is completed by using client proxy class.
From the description, I suggest you add a breakpoint on the JS statement then debug it in the browser. Besides, Success event is deprecated in Jquery, I suggest you use the Done event callback after the AJAX method.
$.ajax({
method:"Get",
url: "http://10.157.13.69:11000/Service1.svc/GetData?value=34",
contentType:"application/json"
}).done(function(data){
console.log(data);
})
I would like that you could post the code details on the server-side so that I try to make an example as much as possible.
At last, please refer to my previous demo on this topic, wish it is useful to you.
How to fix "ERR_ABORTED 400 (Bad Request)" error with Jquery call to C# WCF service?
Feel free to let me know if there is anything I can help with.

jQuery was not called:Https Configuration

I have a json file with data. I am trying to access it through ajax call. i am accessing the script in the https website. I am getting the following error.
Error: jQuery110204653455846038177_1518073501526 was not called
at Function.error (https://sitename/news/scripts/jquery-1.10.2.min.js?v=1:21:4112)
at l.jsonp.n.dataTypes.(anonymous function).n.converters.script json (https://stat.sitename.com/news/scripts/jquery-1.10.2.min.js?v=1:23:17176)
at On (https://stat.sitename.com/news/scripts/jquery-1.10.2.min.js?v=1:23:15599)
at k (https://stat.sitename.com/news/scripts/jquery-1.10.2.min.js?v=1:23:13940)
at HTMLScriptElement.n.onload.n.onreadystatechange (https://stat.sitename.com/news/scripts/jquery-1.10.2.min.js?v=1:23:16467).
If I use the same script in an http website, there is no issue.
$.ajax({
url: "data.json",
data: {},
dataType: 'jsonp',
success: function (e) {
alert();
},
error: function (e, l, s) {
console.log(s)
}
});
Use getJSON instead $.ajax with JSONP or change dataType from "jsonp" to "json". JSONP is a technique that allows you to transfer JSON data across multiple domains.
$.getJSON('/data.json',{}, function(data) {
console.log(data);
});
And here part of jQuery 1.2 documentation:
If you have problem with origins, you should modify serwer configuration. Add custom headers to .htaccess or modify server headers in a different way(apache virtual host configuration for example):
Header set Access-Control-Allow-Origin "http://localhost:80/"
After this modification you'll be able to download this file from external serwer.

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);
}
}
);

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);
}
});

Categories