views:

37

answers:

3

Hi

It's me again (previous question) I am still having problems with json and xml being returned from an ajax call.

I have written a webservice in MonoDevelop version 2.2 to return my json.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string  getLocationJ(){}

Which returns:-

JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(bigPM);
return json;

If I test my webservice I get:-

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/"&gt;[{"placeName":"XXXX","address":"Some    Address","lat":12121,"lng":12121}]</string>

Which is exactly what I am pulling in when I make my ajax calls. My json is still wrapped in XML and therefore cannot be read.

This is my ajax call:-

$.ajax({
  type: "GET",
  url: theURL,
  async: true,
  data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
  cache: false,
  dataType: "jsonp",
  contentType: "application/xml; charset=utf-8",
  success: function (data) {
    alert('in here');



  },
  error:function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
                alert(xhr.statusText);
            }  
  });

If I do just json I get 500 Internal server error, if I do a POST I get 403 forbidden error.

This morning I tried doing:-

$.getJSON(theURL, {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat}, function(data) {
 );
});

Only I get the exact same problems.

If I could just remove the xml from my json then I could move forward but right now I am dead in the water and I think I am drowning in ajax!

Please help Cheryl

A: 

change

contentType: "application/xml; charset=utf-8",

to

contentType: "application/json; charset=utf-8", 

Complete example:

/* in this case I am using */
       <script src="Js/json2.js" type="text/javascript"></script>

  // available at: http://www.json.org/js.html

function jsonObject()
{
};
var phoneListObject = new jsonObject();

function SaveJsonObject()
{
    phoneListObject.Control = new jsonObject();
    phoneListObject.Control.CustomerId = $("#CustomerId").val();
    phoneListObject.Control.CustomerName = $("#CustomerName").val();
    phoneListObject.ListBody.PhonesBlock = new jsonObject();
    phoneListObject.ListBody.PhonesBlock.Phone = new Array();
    $('#PhonesBlock .Phone').each(function(myindex)
    {
        phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneNumber = $(".PhoneNumber input", this).val();
        phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneName = $(".PhoneName input", this).val();
     });
 };

 $(function()
{
    function SaveCurrentList()
    {
        SaveJsonObject();
        var currentSet = phoneListObject;
        var formData = { FormData: currentSet };
        phoneListJSON = JSON.stringify(formData);
        var FormData = "{ FormData:" + JSON.stringify(phoneListJSON) + "}";
        SavePhoneListData(FormData);
    };
    function SavePhoneListData(phonesData)
    {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: phonesData,
            dataFilter: function(data)
            {
                var msg;
                if ((typeof (JSON) !== 'undefined') &&
        (typeof (JSON.parse) === 'function'))
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "../../WebServices/ManagePhones.asmx/SaveJson",
            success: function(msg)
            {
                SaveSuccess(msg);/* the JSON is in the msg, create this function to do what you want with it. */
            },
            complete: function(xhr, textresponse)
            {
                var err = eval("(" + xhr.responseText + ")");
            },
            error: function(msg)
            {
            },
            failure: function(msg)
            {
            }
        });
    };
    $('#btnSave').click(function()
    {
        SaveCurrentList();
    });
});

/* json data snip */
{"FormData":{"Control":{"CustomerId":"12345y6","CustomerName":"Joe Customer"},"PhonesBlock":{"Phone":[{"PhoneNumber":"234-233-2322","PhoneName":"son harry"},{"PhoneNumber":"234-233-2323","PhoneName":"son frank"},{"PhoneNumber":"234-233-2320","PhoneName":"momk"}]}}}

/*XML of the form data:*/
<FormData>
    <Control>
        <CustomerId>12345y6</CustomerId>
        <CustomerName>Joe Customer</CustomerName>
    </Control>
    <PhonesBlock>
        <Phone>
            <PhoneNumber>234-233-2322</PhoneNumber>
            <PhoneName>son harry</PhoneName>
        </Phone>
        <Phone>
            <PhoneNumber>234-233-2323</PhoneNumber>
            <PhoneName>son frank</PhoneName>
        </Phone>
        <Phone>
            <PhoneNumber>234-233-2321</PhoneNumber>
            <PhoneName>momk</PhoneName>
        </Phone>
    </PhonesBlock>
</FormData>

/* form layout snip */

<div class="control">
    <div class="customer">
        <input typeof="text" id="CutomerId" />
        <input typeof="text" id="CutomerName" />
    </div>
    <div class="phoneslist" id="PhonesBlock">
        <div class="Phone">
            <input typeof="text" class="PhoneNumber" />
            <input typeof="text" class="PhoneName" />
        </div>
        <div class="Phone">
            <input typeof="text" class="PhoneNumber" />
            <input typeof="text" class="PhoneName" />
        </div>
        <div class="Phone">
            <input typeof="text" class="PhoneNumber" />
            <input typeof="text" class="PhoneName" />
        </div>
    </div>
</div>
<input id="buttonSave" class="myButton" type="button" value="Save" />

signature of the web service method:

   [WebMethod(EnableSession = true)]
    public string SaveJson(string FormData)
    {
    }
Mark Schultheiss
ooops too bad I left that in by mistake - I have done that and it makes no difference I still have my json wrapped in xml.
Cheryl
You could try using the serializer class from: http://james.newtonking.com/pages/json-net.aspx
Mark Schultheiss
whether I do json or xml I keep getting this response in firebug:-missing ; before statement<string xmlns="http://tempuri.org/">[{...nue","lat":-79.45,"lng":43.6801},{"pla
Cheryl
Yes, that would be due to the XML markup around your JSON text. You need to fix your server. This is not a problem with your jQuery code.
Pointy
yes I agree the problem definitely lies on the server - but any suggestions as to how to fix it?
Cheryl
I'd help if I could but I know nothing about "MonoDevelop".
Pointy
I have seen other asp.net servers also returning json wrapped in xml so I don't beleive my problem lies with the server. I think I should be doing a Post not a Get. But with a Post I get 403 Forbidden. Does anyone know how to get around that problem?
Cheryl
I agree it should be Post not Get and as such it should be json not jsonp for the dataType. The 403 error indicates (to me at least) that you might have a cross domain issue in play in the url. Is that from the same site (Domain)?
Mark Schultheiss
Also, your `data:` appears to be incorrect and should be serialized. I use the one from http://www.json.org/ (json2.js) to serialize my client side stuff for this. I will add and example of that above.
Mark Schultheiss
One other note, not being familiar with MonoDevelop config, I can only toss out a link http://vampirebasic.blogspot.com/2009/04/aspnet-ajax-in-mono.html but I have no first hand experience with that.
Mark Schultheiss
A: 

A quick and dirty fix is to extract your json from the xml in the success function.

$.ajax({
  type: "GET",
  url: theURL,
  async: true,
  data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
  cache: false,
  dataType: "jsonp",
  contentType: "application/xml; charset=utf-8",
  success: function (data) {

data = extractJsonFromXml(data); 
  //you have to write extractJsonFromXml function in js, you could use substring, or a regex replace. 

 }
Sumit
A: 

Make sure your service class has [ScriptService] attribute. This attribute is not added by default.

Pavel Morshenyuk