Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Ajax Call to WEB API

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)

like image 445
chamara Avatar asked Oct 02 '22 13:10

chamara


2 Answers

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
like image 141
Francis Avatar answered Oct 16 '22 14:10

Francis


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.

like image 2
elolos Avatar answered Oct 16 '22 15:10

elolos