0

I have a WCF restful service which exposes login method to the outside world is defined as below, it just validates the given user credentials with DB (login table) & returns result in json format

C# code:

[OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "login/{sUserID}/{password}")]
    List<ParkingLotRestWCFService> login(string sUserID, string password);

definition of the same

 public List<ParkingLotRestWCFService> login(string sUserID, string password)
   {
        ParkingLotRestWCFService login = null;
        List<ParkingLotRestWCFService> arrList = new List<ParkingLotRestWCFService>();
        string json = "";
      try
        {
            string _connectionstring = "Data Source=LM;Initial Catalog=parkinglotdb;Integrated Security=true";
            string _sql1 = "SELECT * FROM [LoginDetails] WHERE EmpID = " + sUserID + " AND Pwd = '" + password + "'";
            SqlConnection _connection = new SqlConnection(_connectionstring);
            SqlCommand _command = new SqlCommand(_sql1, _connection);
            _connection.Open();
            SqlDataReader reader = _command.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Close();
                string _sql2 = "EXEC [dbo].[loginVerify]";
                SqlCommand _command2 = new SqlCommand(_sql2, _connection);
                SqlDataReader reader2 = _command2.ExecuteReader();
                reader2.Read();

                login = new ParkingLotRestWCFService();
                login.status = "Valid";
                login.empID = reader2["EmpID"].ToString();
                login.empName = reader2["Name"].ToString();
                login.secFlag = reader2["SecFlag"].ToString();

                arrList.Add(login);
                reader2.Close();

                //JavaScriptSerializer ser = new JavaScriptSerializer();
                //json = ser.Serialize(arrList.ToArray());
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
                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"); 

            }
            else
            {
                reader.Close();
                login.status = "Invalid";
                login.empID = string.Empty;
                login.empName = string.Empty;
                login.secFlag = string.Empty;

                arrList.Add(login);
            }
            _connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;

        }

        return arrList;
    }

Jquery Ajax Code:

 $('#signIn').on('click',function(){
        var userId=$('#userId').val();
        var pass=$('#password').val();
        var sUrl='http://localhost/ParkingLotRestWCFService.svc/login/'+userId+'/'+pass;
        $.ajax({
                url: sUrl,
            type:"GET",
            contentType: 'application/json; charset=utf-8',
            dataType:"jsonp",
                            jsonp:'jsonp',
                            crossDomain:true,
            success: function (data, textStatus, jqXHR) {
                           //process the json response
               alert("success:"+retData);
            },
            error:function (result, sts, err) {
            alert("inside error block");
                alert(err+":"+sts+":"+result);
            },
            complete: function (jqXHR, textStatus) {
                alert("completed");
            }

        });
    });

So the problem is that whenever i make a ajax call the control goes into error block, even though i can see the actual json data in the response section under Net tab in Firebug console.the error message inside the error block will be alerted as Error: jQuery111108245764932074613_1403187289975 was not called:parsererror:[object Object].

I firebug console i get this error message

      SyntaxError: missing ; before statement
          {"loginResult":[{"empID":"300","empName":"User1","loginTime":null,"logo
           -------------^

Here is the json response what is returned from my WCF service

JSON Response:
{"loginResult":[{"empID":"300","empName":"User1","loginTime":null,"logoutTime":null,"secFlag":"A","slotNo":null,"status":"Valid","vechicleNo":null,"vechicleType":null}]}

Note:

  1. If i hit the url passed to the jquery directly from browser its returning me the json data without any error, but the same is not working with jquery ajax call
  2. I even verified the json response at http://jsonlint.com/ , its valid json

Any Quick help will be much appreciated guys :)

chridam
  • 100,957
  • 23
  • 236
  • 235
dreamweiver
  • 6,002
  • 2
  • 24
  • 39
  • The response from your server doesn't seem to be a JSONP.JSONP is actually javascript and should look like this: callback({*yourjsonhere*}) – opp Jun 19 '14 at 15:23
  • your service doent support jsonp call,try using only json – sakir Jun 19 '14 at 17:27
  • @sakir: actually i have enabled cors at WCF service end but still getting issue, could you please tell me how to enable cors (if not enabled already) and how to return json data within a callback function so that my ajax call can parse it properly – dreamweiver Jun 20 '14 at 05:17
  • here is the how you can enable [here is the how you can enable][1] [1]: http://stackoverflow.com/questions/8219579/how-to-natively-enable-jsonp-for-existing-wcf-service – sakir Jun 20 '14 at 05:43

1 Answers1

0

web.config

<configuration>
  <system.web>
    <compilation debug="true" targetframework="4.0">
    <authentication mode="None">
  </authentication></compilation></system.web>
  <system.webserver>
    <modules runallmanagedmodulesforallrequests="true">
  </modules></system.webserver>
  <system.servicemodel>
    <servicehostingenvironment **aspnetcompatibilityenabled**="true">
    <standardendpoints>
      <webscriptendpoint>
        <standardendpoint **crossdomainscriptaccessenabled**="true" name="">
      </standardendpoint></webscriptendpoint>
    </standardendpoints>
  </servicehostingenvironment></system.servicemodel>
</configuration>
sakir
  • 3,391
  • 8
  • 34
  • 50
  • thanks for that, but it didnt work bro , The behavior at jquery ajax is same as before. any other solutions ? – dreamweiver Jun 20 '14 at 06:50
  • same syntax error in firebug as i have mentioned in my question, also its entering the error block of ajax call with error message as `"Error: jQuery1111010482331053579053_1403247295078 was not called:parsererror:[object Object]"`. this was the same behavior before adding ur solution as well. – dreamweiver Jun 20 '14 at 06:56