Cannot get jQuery Ajax to parse JSON web service result

I checked the JSON response on my C # web method, so I don't think the problem is.

I am trying to parse the result using simple jQuery $ .ajax, but for some reason I cannot get the method to run and parse the result correctly, by the way, it seems it cannot get the function to run the result. Are there any restrictions on the size of the JSON object that can be returned.

I also removed this code from the Site.Master page because it always updated when I clicked a simple button. Do tags work correctly with jQuery elements, such as entering a button that I grab from the DOM?

function ajax() { //var myData = { qtype: "ProductName", query: "xbox" }; var myData = { "request": { qtype: "ProductName", query: "xbox"} }; $.ajax({ type: "POST", url: "/webservice/WebService.asmx/updateProductsList", data: {InputData:$.toJSON(myData)}, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { // var msg = {__type: "Testportal.outputData", id: "li1234", message: "it work!", myInt:101} alert("message=" + msg.d.ProductName + ", id=" + msg.d.Brand); }, error: function (res, status) { if (status === "error") { // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace var errorMessage = $.parseJSON(res.responseText); alert(errorMessage.Message); } } }); 

}

And the page:

  <asp:Button ID="Button1" runat="server" OnClientClick="ajax();" Text="Button" /> 

And the Serverside web method:

  public class WebService : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public OutputData updateProductsList(InputData request) { OutputData result = new OutputData(); var db = new App_Data.eCostDataContext(); var q = from c in db.eCosts select c; if (!string.IsNullOrEmpty(request.qtype) && !string.IsNullOrEmpty(request.query)) { q = q.Like(request.qtype, request.query); } //q = q.Skip((page - 1) * rp).Take(rp); result.products = q.ToList(); searchObject search = new searchObject(); foreach (App_Data.eCost product in result.products) { /* create new item list */ searchResult elements = new searchResult() { id = product.ProductID, elements = GetPropertyList(product) }; search.items.Add(elements); } return result; } 

And helper classes:

  public class OutputData { public string id { get; set; } public List<App_Data.eCost> products { get; set; } } public class InputData { public string qtype { get; set; } public string query { get; set; } } 
+3
json jquery ajax
source share
3 answers

One of the problems you may have is that you are not doing anything to prevent the form from being submitted and the complete postback / reload when the $ .ajax () callback is triggered.

I suggest connecting this unobtrusively, instead of using the OnClientClick property, for example:

 $(document).ready(function() { // May need to use $('<%= Button1.ClientID %>') if your Button is // inside a naming container, such as a master page. $('#Button1').click(function(evt) { // This stops the form submission. evt.preventDefault(); $.ajax({ // Your $.ajax() code here. }); }); }); 

I also agree with Oleg that you should use json2.js for your JSON pull and parse. In new browsers, this will revert to their own implementations of these browsers, which is much faster and makes parsing safer.

Update:

To answer your question about data, this does not look completely correct.

What you want to ultimately send to the server is (without formatting):

 {"request":{"gtype":"ProductName","query":"xbox"}} 

For this you need something like this:

 var req = { request : { qtype: "ProductName", query: "xbox" }}; $.ajax({ data: JSON.stringify(req), // Remaining $.ajax() parameters }); 

Keep in mind that request , qtype and query must match your server case structure.

You can also be more detailed in the definition of the request object (which I personally prefer to keep clean and readable):

 var req = { }; req.request = { }; req.request.qtype = "ProductName"; req.request.query = "xbox"; 

I wrote a little more about this here if you are interested: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

+1
source share

What does your server side code method look like? Set a breakpoint. Is that even a hit?

It should look something like this:

 [WebMethod, ScriptMethod] public string updateProductsList(string qtype, string query) { // stuff } 

Also, your javascript options do not look right.

+1
source share

It seems to me that your problem is that you are trying to use manual JSON serialization. There is a more direct way. You should simply declare [ScriptMethod (ResponseFormat = ResponseFormat.Json)] or [ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] and return return direct instead of the object from the web method. On the client side (in JavaScript), I strongly recommend that you use JSON.stringify (from json2.js, which can be downloaded from http://www.json.org/js.html ) to build the data parameter jQuery.ajax .

Look. Can I return JSON from the .asmx web service if ContentType is not JSON? and How can I build a JSON object to send to AJAX WebService? probably also in jquery ajax the httpget webmethod (c #) call does not work , you have interest for more experiments.

+1
source share

All Articles