Skip to content Skip to sidebar Skip to footer

Web Service Call From Javascript

I am calling a webservice in javascript file using json but web service is called only when both of the .asmx file and javascript file are on my local server or both of the files

Solution 1:

The problem is that you are trying to make request to another domain.

You can try to use crossDomain option of jQuery.ajax call.

https://api.jquery.com/jQuery.ajax/

Solution 2:

you can call the web service which is on same domain beacuse of some Security reasons.u will have to use JSON with padding (JSONP).

Your service has to return jsonp, which is basically javascript code. You need to supply a callback function to the service from your ajax request, and what is returned is the function call.

Example: 1

Ajax Request:

functionhello() {

        $.ajax({
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: "http://example.example.com/WebService.asmx/HelloWorld",
            data: {}, // example of parameter being passeddataType: "jsonp",
            success: jsonpCallback,

        });
    }

    functionjsonpCallback(json) {
        document.getElementById("result").textContent = JSON.stringify(json);
    }

Server-side Code:

publicvoidHelloWorld(int projectID,string callback)
{

    Strings="Hello World !!";
    StringBuildersb=newStringBuilder();
    JavaScriptSerializerjs=newJavaScriptSerializer();
    sb.Append(callback + "(");
    sb.Append(js.Serialize(s));
    sb.Append(");");
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write(sb.ToString());
    Context.Response.End();
}

Example:2 How can I produce JSONP from an ASP.NET web service for cross-domain calls?

Post a Comment for "Web Service Call From Javascript"