user601367
user601367

Reputation: 2368

jquery cross domain issue!

i have created a service of type post.When i am sending data from jquery ajax it is not working.Method of type GET working fine. I need with post type also .what is the solution.Please help.

var user = document.getElementById("uname").value;
         var pass = document.getElementById("pass").value;
         var utyp = document.getElementById("usertyp").value;
         //  alert("hi"+pass);

         var dat = { "uname": user, "pwd": pass, "utype": utyp };

         Data = JSON.stringify(dat);





     $.ajax({
             url: "http://192.168.1.9:450/Service.svc/Login_Insert",
             type: "POST",
             data:Data,
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             processdata: true,
             success: function res(msg) {
                 alert("hello" + msg);
             },
             error: function error(response) {

                 alert("error");
                 alert(response.responseText);
                 alert(JSON.stringify(response));
             }
         });

Regards, giri Bhushan

Upvotes: 0

Views: 1324

Answers (3)

Taha Rehman Siddiqui
Taha Rehman Siddiqui

Reputation: 2533

in your service method you are calling, insert these 4 lines of code in start of the function below.

    public string GetEmployee(string id, string name, string email)
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Methods", "GET"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Headers", "Content-Type, Accept");
        Employee employee = new Employee();
        employee.TRGEmpID = id;
        employee.First_Name = name;
        employee.Email = email;
        EmployeeManagement empMgmt = new EmployeeManagement();
        var json = new JavaScriptSerializer().Serialize(empMgmt.Search(employee).FirstOrDefault());
        return json;
    }

also, in svc file add this line before your function like in the one below.

        [OperationContract]
    [WebInvoke(Method = "GET",
       ResponseFormat = WebMessageFormat.Json,
       RequestFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare)]
    string GetEmployees(string name);

if you need web.config too, here it is

<?xml version="1.0"?>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
    <services>
        <service  name="EmployeeService.EmployeeSearchService" behaviorConfiguration="DefaultServiceBehavior">
            <endpoint binding="webHttpBinding" contract="EmployeeService.IEmployeeSearchService"      behaviorConfiguration="DefaultEPBehavior" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="DefaultEPBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="DefaultServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
  -->
    <directoryBrowse enabled="true"/>
</system.webServer>

Upvotes: 0

xkeshav
xkeshav

Reputation: 54016

some TIPS:

  • when u r using jQuery then no need to get value with typical javascript style.
  • JSON.stringyfy() is not necessary
  • dont use DATA as variable name, misleading ( i think data is reserved keyword for js)

Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.

here i modified your code

var user = $("#uname").val();
var pass = $("#pass").val();
var utyp = $("#usertyp").val();
var userData = { "uname": user, "pwd": pass, "utype": utyp };
$.ajax({
             url: "http://192.168.1.9:450/Service.svc/Login_Insert?callback=?",
             type: "POST",
             data:userData,          
             crossDomain:true
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             processdata: true,
             success: function res(msg) {
                 alert("hello" + msg);
             },
             error: function error(response) {
                 alert("error");
                 alert(response.responseText);
                 alert(JSON.stringify(response));
             }
         });

REFERENCE

Upvotes: 0

Adam Straughan
Adam Straughan

Reputation: 2848

cross domain requests are solved using JSONP. This is effectively a hack to work around the browser security model. It works by including a remote script block and auto executing a callback function when ready. This can ONLY be done as a GET request

Upvotes: 3

Related Questions