0

Currently I am working on the project where i have to fetch information from web API into web application using JQuery.

<script src="jquery-1.11.2.js"></script>
<script src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
        jQuery.support.cors = true;
        $("#btn").click(function () {
            $.ajax({
                url: "http://localhost:52227/api/Values",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    alert("hello");
                }
            });
        });
    });
</script>

<body>
<form id="form1" runat="server">
<div>
    <input type="button" id="btn" value="submit" />
</div>
</form>

When I run this application it is not showing me any output.

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Saba Aslam
  • 43
  • 3
  • 11

1 Answers1

0

The code you have provided is syntactically correct. The get request is most likely failing and you haven't provided an error function for the request. You can add an error callback like this

$.ajax
(
{
    url: "http://localhost:52227/api/Values",
    type: "GET",
    dataType: "json",
    success: function (data) {
        alert("hello");
    },
    error: function (data) {
        alert("test");
    }
}
)

Here is a JSFiddle showing it in action.

http://jsfiddle.net/1mqotn6v/2/

Sam Abushanab
  • 492
  • 3
  • 13
  • but here i am getting error ( i am getting test in my alert box) : what is the error in this code ??? – Saba Aslam Apr 24 '15 at 17:45
  • You can console.log the return object to glean some information about the error or you can open the developer tools in your browser and look at the network tab for some information about the error. I have updated the jsfiddle with the console.log instead of the alert: http://jsfiddle.net/1mqotn6v/7/ – Sam Abushanab Apr 24 '15 at 17:53
  • is the issue not that he is telling jquery to expect JSON, when in fact xml is being returned? – Paul Fitzgerald Apr 24 '15 at 17:55
  • That's most likely the underlying issue but the above answer will let him know how to troubleshoot these errors in the future – Sam Abushanab Apr 24 '15 at 18:00
  • I am getting the error as-- XMLHttpRequest cannot load http://localhost:52227/api/Values. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access -- and when i run my code success :function(data){ alert(data.UserName) ;} ( where user name is my property ) it is giving me message as "undefined" – Saba Aslam Apr 24 '15 at 18:03
  • absolutely, but he should be aware that xml and json are two different things http://stackoverflow.com/questions/2620270/what-is-the-difference-between-json-and-xml – Paul Fitzgerald Apr 24 '15 at 18:03