1

I have developed a service which is running successfully. Following is my service code:

namespace WcfService1
{   
[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method="GET", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate="/display/{a}/{b}")]        
    string Display(string a, string b);        
} 
}

My Service:

namespace WcfService1
{
 public class Service1 : IService1
{
    public string Display(string a, string b)
    {
        int ab = Convert.ToInt32(a);
        int bc = Convert.ToInt32(b);
        int cb = ab + bc;
        return cb.ToString();
    }
}
}

How do I call this with the help of AJAX URL? I have tried out the following code but it is not working.

<script type="text/javascript">
    $(document).ready(function () {
        $('#BtnRegister').click(function () {
            debugger;

            var No1 = document.getElementById('TxtFirstNumber').value;
            var No2 = document.getElementById('TxtSecondNumber').value;

            $.ajax({
                cache: false,
                type: "GET",
                async: false,
                url: "http://localhost:22727/Service1.svc/Display",
                data: 'a=' +No1+'&b='+No2,
                contentType: "application/json; charset=ytf-8",
                dataType: "json",
                processData: true,
                success: function (result) {
                    alert("data");
                },
                error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
            });
        });
    });
</script>

Updated:

I changed my code to the following one:

$(document).ready(function () {
        $('#BtnRegister').click(function () {
            debugger;

            var No1 = document.getElementById('TxtFirstNumber').value;
            var No2 = document.getElementById('TxtSecondNumber').value;

            $.ajax({
                cache: false,
                type: "GET",
                url: "http://localhost:22727/Service1.svc/Display",
                data: { a: No1, b: No2 },
                contentType: "application/json; charset=ytf-8",
                //processData: true, //<-- this isn't needed because it defaults to true anyway
                success: function (result) {
                    alert("data");
                },
                error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
            });
        });
    });

But when I am clicking on the button:

enter image description here

halfer
  • 19,471
  • 17
  • 87
  • 173
Nimit Joshi
  • 1,006
  • 3
  • 18
  • 44

4 Answers4

2

According to the service definition, it's expecting JSON as the request format, but you're passing a form encoded key/value pair. So change the data part to:

data: {a : No1, b : No2},

This will pass an object, and because you have the content type set to JSON, jQuery will automatically transform the object to JSON for the request.

Also, your service is returning a string, not JSON, so you need to remove dataType: "json", because if you leave this in, jQuery will try to parse the response as JSON and it will trigger the error handler instead of success.

I suggest removing the async: false because ajax is best used asynchronously and there is no benefit to a synchronous request in this case.

Full request after the above changes:

$.ajax({
    cache: false,
    type: "GET",
    url: "http://localhost:22727/Service1.svc/Display",
    data: {a : No1, b : No2},
    contentType: "application/json; charset=ytf-8",
    //processData: true, //<-- this isn't needed because it defaults to true anyway
    success: function (result) {
        alert("data");
    },
    error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
});

UPDATE after question editted:

Your service lives on a different port to your the origin of your JavaScript, therefore the request failing due to Same Origin Policy.

To resolve, you will need to output the CORS header from the service:

Access-Control-Allow-Origin: *

This will allow any origin to call the service, you might want to restrict it to certain origins.

MrCode
  • 61,589
  • 10
  • 82
  • 110
  • Where do i insert this in my service? What about the first error (404 error) – Nimit Joshi Jun 12 '14 at 09:59
  • Have a look at http://enable-cors.org/server_wcf.html to enable CORS in the web.config. As for the 404 error, that might not be a problem when you get CORS working. – MrCode Jun 12 '14 at 10:12
2

Try this:

$.ajax({
   type:'GET',
   url:'your url',
   data:{ var1: value1, var2: value2},
   success:function(response)
{

}

});

and on the business layer, retrieve these using the variable names ie. var1 and var2.

AppleBud
  • 1,479
  • 7
  • 29
  • 47
0

Try this one,

var params = {a: No1, b:No2}

 <script type="text/javascript">
$(document).ready(function () {
    $('#BtnRegister').click(function () {
        debugger;

        var No1 = document.getElementById('TxtFirstNumber').value;
        var No2 = document.getElementById('TxtSecondNumber').value;

           var params = {a: No1, b:No2}

        $.ajax({
            cache: false,
            type: "GET",
            async: false,
            url: "http://localhost:22727/Service1.svc/Display",
            data: params,
            contentType: "application/json; charset=ytf-8",
            dataType: "json",
            processData: true,
            success: function (result) {
                alert("data");
            },
            error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
        });
    });
});

KarthikManoharan
  • 775
  • 4
  • 12
0

I think data should be an object like this and remove the async = false:

$.ajax({
                cache: false,
                type: "GET",
                url: "http://localhost:22727/Service1.svc/Display",
                data: {
                     a: No1,
                     b: No2
                },
                contentType: "application/json; charset=ytf-8",
                dataType: "json",
                processData: true,
                success: function (result) {
                    alert("data");
                },
                error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
            });



Ray1618
  • 98
  • 1
  • 6