Solved

jQuery Ajax Post Json

Posted on 2010-09-15
11
854 Views
Last Modified: 2012-05-10
Hi Experts. My function below is suppose to return json data that I am using to populate a div.  When I look at Fiddler.  My webservice call is passing the json data back correctly. What am I missing?


function OnLookup() {
                $.ajax({
                    type: "POST",
                    url: "http://<%=HttpContext.Current.Request.Url.Host%>/services/LocationService.asmx/ChangeLocation",
                    data: "{zipcode : '" +$('#edtzipcode').val()+"'}",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function(data){
                        alert(data);
                        $('#curlocation').innerHTML(data[1].City + "," + data[1].State);
                        $('#edtzipcode').val("");
                    },
                });
            }
0
Comment
Question by:ikeyser
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 58

Expert Comment

by:amit_g
ID: 33688036
Could you show us the returned response from the server that you can see in Fiddler? Does your JSON data look like

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?

Note the ({ in the beginning  and }) in the end.
0
 

Author Comment

by:ikeyser
ID: 33688039
The JSON data returns...
{"d":{"DataObject":{"LocationId":8,"EntityId":9,"EntityTypeId":2,"LocationName":"loc1","Address1":"1495 S. Wolf Rd.","Address2":null,"City":"Prospect Heights","ZipCode":"60070","ModifiedBy":2,"ModifiedDateTime":"\/Date(1279386329023)\/","CreatedBy":2,"CreatedDateTime":"\/Date(1279386329023)\/","LocationIdentifierId":null,"State":"IL","EntityState":1,"EntityKey":{"EntitySetName":"Location","EntityContainerName":"ResourceDBEntities","EntityKeyValues":[{"Key":"LocationId","Value":8}],"IsTemporary":false}},"Address1":"1495 S. Wolf Rd.","Address2":null,"City":"Prospect Heights","LocationName":"loc1","State":"IL","ZipCode":"60070","EntityId":9,"EntityTypeId":2,"HasChanged":false,"IsValid":true,"ValidationMessages":[]}}
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33688051
What about :   data: { zipcode : $('#edtzipcode').val() },

(you post a json object and not a string)
function OnLookup() {
                $.ajax({
                    type: "POST",
                    url: "http://<%=HttpContext.Current.Request.Url.Host%>/services/LocationService.asmx/ChangeLocation",
                    data: { zipcode : $('#edtzipcode').val() },
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function(data){
                        alert(data);
                        $('#curlocation').innerHTML(data[1].City + "," + data[1].State);
                        $('#edtzipcode').val("");
                    },
                });
            }

Open in new window

0
Report: Liquid Web beats Amazon, Rackspace & More

A study by performance analyst firm Cloud Spectator finds that Liquid Web beats rivals Amazon, Rackspace and DigitalOcean when it comes to website and cloud application performance.

 

Author Comment

by:ikeyser
ID: 33688062
Sorry new to this...my web service is expecting a string value which is what I am passing.
0
 

Author Comment

by:ikeyser
ID: 33688081
Leakim971 - When I changed to data : { zipcode : $('#edtzipcode').val() },
I get an error when I make my ajax call...
{"Message":"Invalid JSON primitive: zipcode.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
0
 
LVL 17

Expert Comment

by:Shinesh Premrajan
ID: 33689149

success: function(data){
                        data = $.parseJSON(string);
                        $('#curlocation').innerHTML(data[1].City + "," + data[1].State);
                        $('#edtzipcode').val("");
                    },

yopu need to parse the JSON to actually use the JSON data.

hoep this helps
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33691698
>I get an error when I make my ajax call...

Are using DataContract & Co ? What is the language used for the webservice ? VB.Net or C#.Net
0
 

Author Comment

by:ikeyser
ID: 33697867
shinug - the .ajax call automatically parses the json data.  After debugging, I found the solution.

data[1].City does not exist.  What i ended up doing is

success: function(data){
                        result = data.d;
                        $('#curlocation').innerHTML(result.City + "," + result.State);
                        $('#edtzipcode').val("");
                    },


0
 

Accepted Solution

by:
ikeyser earned 0 total points
ID: 33697887
I have another issue but not ajax related but if someone can provide the answer i will provide all the points... my code below works except when it completes the ajax call it populate my label but then my panel slide again and my label value is gone.

$(document).ready(function () {

            var zip = $("#edtzipcode");
            $("#changelocation").click(function () {
                $(".panel").slideToggle("slow");
            });

            $("#cmdgo").click(function (event) {
                var bool = validateZip(zip);
                if (bool) {
                    OnLookup();
                }
                else {
                    alert("Zip Code is Invalid");
                    return false;
                }
            });

            function validateZip(obj) {
                var regexp = /^([0-9a-zA-Z])+$/;
                if (!(regexp.test(obj.val()))) {
                    return false;
                } else {
                    return true;
                }
            }

            function OnLookup() {
                $.ajax({
                    type: "POST",
                    url: "http://<%=HttpContext.Current.Request.Url.Host%>/services/LocationService.asmx/ChangeLocation",
                    data: "{zipcode : '" +$('#edtzipcode').val()+"'}",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function OnLookupComplete(result) {
                        data = result.d;
                        $("#curlocation").text(data.City + "," + data.State);
                        $("#edtzipcode").val("");
                    },
                });
            }

        });
0
 
LVL 17

Expert Comment

by:Shinesh Premrajan
ID: 33698529
There is no return value if the zipcode is valid.

Hope this helps
function OnLookup() {
                $.ajax({
                    type: "POST",
                    url: "http://<%=HttpContext.Current.Request.Url.Host%>/services/LocationService.asmx/ChangeLocation",
                    data: "{zipcode : '" +$('#edtzipcode').val()+"'}",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function OnLookupComplete(result) {
                        data = result.d;
                        $("#curlocation").text(data.City + "," + data.State);
                        $("#edtzipcode").val("");
                    },
                });
return true;
            }

Open in new window

0
 

Author Comment

by:ikeyser
ID: 33706236
Shinug - #curlocation is the field I am populating, not the zipcode field.
0

Featured Post

Report: Liquid Web beats Amazon, Rackspace & More

A study by performance analyst firm Cloud Spectator finds that Liquid Web beats rivals Amazon, Rackspace and DigitalOcean when it comes to website and cloud application performance.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question