1

I would like to pass parameters to my webservice from jquerys ajax. How can I do that?

I've already looked through a few of the related questions but couldn't find a solution that worked for me. I've tried this: jQuery AJAX parameter not being passed to MVC but I'm not using mvc so I'm sure that is why the solution isn't working. My jquery looks like this:

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "CarService.svc/GetCar",
                data: {CarID:117},
                dataType: "json",
                success: function (data) {
                    $("#lblCurrentTime").text("");
                    $("#lblCurrentTime").text(data.d.CarID);
                }
            });

Something is wrong with my 'data' part, correct? If leave the data: part as data: "{}" I can get my method to run (and I don't pass any parameter) but the moment I try the above out firebug tells me:

Firebug's log limit has been reached. 0 entries not shown.  Preferences  
POST http://localhost:64461/TimeService.svc/GetCar
POST http://localhost:64461/TimeService.svc/GetCar

500 Internal Server Error
  1.12s

My Webservice looks like this:

[OperationContract]
    public CarTable GetCar(int id)
    {
        using (var sqlc = new SqlConnection(@"sdfgsdfg"))
        {
            sqlc.Open();
            var cmd = sqlc.CreateCommand();
            cmd.CommandText = "HUGE QUERY HERE ^^";
            //id = 117;
            cmd.Parameters.Add("CarID", System.Data.SqlDbType.Int).Value = id;
            using (var reader = cmd.ExecuteReader())
            {
                CarTable Cars = new CarTable();

                while (reader.Read())
                {
                    Cars.CarID = reader["CarID"].ToString();
                    Cars.CarName = reader["CarName"].ToString();
                }


                return Cars;

            }
        }
    }
[DataContract]
public class CarTable
{
    [DataMember]
    public string CarID { get; set; }
    [DataMember]
    public string CarName { get; set; }
}

EDIT: If I change the data part to:

data: CarID=117,

I get Sys.ParameterCountException: Parameter count mismatch. [Break On This Error] {name: "format", type: String}

Community
  • 1
  • 1
RoboKozo
  • 4,981
  • 5
  • 51
  • 79
  • Are you able to call your webservice using a tool like SoapUI? – Jan Aagaard Dec 08 '10 at 22:54
  • Have you tried "complete" instead of success, and seen what the error messages were? – Matrym Dec 08 '10 at 23:06
  • I'm not familiar with that tool, but I'll check it out now. – RoboKozo Dec 08 '10 at 23:07
  • I just spent the last few minutes with SoapUI and it left me feeling very confused -_- It is probably beyond my current scope of understanding. – RoboKozo Dec 08 '10 at 23:20
  • {"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.","StackTrace":null} – RoboKozo Dec 08 '10 at 23:41
  • Edit up above. please check it out! – RoboKozo Dec 08 '10 at 23:45

4 Answers4

2

First you should verify that you include attribute

[WebInvoke (ResponseFormat = WebMessageFormat.Json)]

to the GetCar method or do the same in web.config.

Second you should use data:"117" or data:JSON.stringify(117) instead of data: {feat:117}.

UPDATED: If you would has a more complex data input, for example as an object CarTable the data parameter should be data:JSON.stringify({CarID: 117, CarName: "BMW"}), so it should be built in the same way. The JSON.stringify is defined in http://www.json.org/js.html.

One more remark. After the successful return of data you will see that the data returned back should be accessed not with data.d.CarID, but with data.CarID instead. ASMX web-service place the data in the property d, but not WCF service.

UPDATED 2: I don't know which small error you do, so I created a small WCF service which do what you need. You can download the source code here http://www.ok-soft-gmbh.com/jQuery/WcfData.zip. To be sure that you will be able compile it I used Visual Studio 2008. In Visual Studio 2010 the web.config file can be much more simple.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hey Oleg thanks! I replaced [OperationContract] with [WebInvoke(ResponseFormat = WebMessageFormat.Json)]. But I still get the same 500 error when I try to pass in data with all the different options. – RoboKozo Dec 09 '10 at 00:24
  • typically one use both `[OperationContract]` and `[WebInvoke(ResponseFormat = WebMessageFormat.Json)]` attributes, but you posted only a part of the definition... I hope the rest is made correct. – Oleg Dec 09 '10 at 00:28
  • Ok. I kept operationContract in as well but still none of the solutions seem to be working correctly. I consistently get the 500 error or Sys.ParameterCountException: Parameter count mismatch. [Break On This Error] {name: "format", type: String} – RoboKozo Dec 09 '10 at 00:31
  • Thank you for uploading that test. I'll take a look at it now! – RoboKozo Dec 09 '10 at 00:46
  • @Robodude: Look in the updated part and download the code example from http://www.ok-soft-gmbh.com/jQuery/WcfData.zip – Oleg Dec 09 '10 at 00:47
  • @Robodude: By the way, probably you want return `List` instead of `CarTable` object. The code inside of `using (var reader = cmd.ExecuteReader())` can be about following `var list=new List(); while (reader.Read()) {list.Add(new CarTable {CarID = reader["CarID"], CarName = reader["CarName"]})} return list;`. I hope you will can read the code here in spite of bad formatting. – Oleg Dec 09 '10 at 01:05
  • Thank you again. I took a moment to look through it and I appreciate your effort in putting it in. There are a few differences which might be causing the problem. In my case, I am only using one .svc file. While in yours, there also appears to be an interface. Your OperationContract and WebInvoke are within the public interface that is labeled as a [ServiceContract]. -_- I really don't know what I'm doing as I just followed an example from a tutorial as closely as I could. – RoboKozo Dec 09 '10 at 01:07
  • @Robodude: I suppose you should search the problem in the `web.config` espetially in the `` part. Which version of .NET and which version of the Visual Studio you use? Which tutorial you try to follow? In general you must not use interface for a WCF web service, but you should and it makes all much easy. It is only a part of good style and the best practice. If you will just create a new empty web application and add WCF web service to it Visual Studio will automatically generate the code with a class and an interface. So in my example I just followed the standards. – Oleg Dec 09 '10 at 10:18
  • 4.0 and Visual Studio 2010. I made another post about getting the webservice to work in the first place (without parameters) earlier. http://stackoverflow.com/questions/4383098/creating-json-return-strings-from-a-webservice-for-use-with-jquery-ajax – RoboKozo Dec 09 '10 at 17:22
  • @Robodude: Ohhhh. You chooses not the best tutorial. One from tho references from your earlier questions are about ASMX web services and not about WCF. ASMX web services place results inside `d` and should receive other formated parameters: {id:117} in your case. See http://stackoverflow.com/questions/2737525/how-do-i-build-a-json-object-to-send-to-an-ajax-webservice/2738086#2738086. In WCF "tutorial" are used wrong `` behavior instead of ``. Compare `` from my example with youth. If you will have problems in about 2 hours I could help you. – Oleg Dec 09 '10 at 18:06
  • Ok. I abandoned my service and all the related files and I recreated your webservices into my project using Add New > WCF Service. When I run your code in my project I get the following error according to firebug: 415 Unsupported Media Type. – RoboKozo Dec 09 '10 at 18:41
  • In the XML section of firebug I also get some more information: XML Parsing Error: no element found Location: moz-nullprincipal:{a3587512-2962-4e72-afdb-30c36fd173c7} Line Number 1, Column 1: ^ – RoboKozo Dec 09 '10 at 18:42
  • In the post section of firebug I get: JSON There are no child objects Source {} – RoboKozo Dec 09 '10 at 18:43
  • I was able to get your solution working in my app - it wasn't working moments ago because I had a copy-paste fail. I will now re-write my methods using your setup. What I'll do from here on out is just build on your existing framework and go from there. Many many thanks Oleg! You rock! – RoboKozo Dec 09 '10 at 19:03
  • @Robodude: I just back. If you need I can explain step by step How you can create in Visual Studio 2010 a small Web-Site (HTML-file which use `jQuery.ajax`) and you receive the solution which I posted you before. If you need that, please open new question and post me the url here. Then I post my answer. – Oleg Dec 09 '10 at 19:13
2
data: {CarID:117}, 

should be:

data: "{'id':'117'}", 

The data parameter must be a string. The name and value pairs need to be quoted to be valid JSON. The name of the name/value pair should match the input parameter of the web service.

DaveB
  • 9,470
  • 4
  • 39
  • 66
1

try changing

data: {CarID:117},

to just data: {id:117},

EdChum
  • 376,765
  • 198
  • 813
  • 562
winston
  • 11
  • 1
0

I think the parameter name needs to match what the call is on the service.

try changing

data: {CarID:117},

to just data: {ID:117},

willz
  • 2,020
  • 3
  • 21
  • 24