JSON.Parse issue - console shows error in DOCTYPE

I am trying to write some JSON data to a div using JQuery:

var obj = JSON.parse(data);
$('#container').html(obj.services.service[0].code);

      

But I am getting a syntax error in my DOCTYPE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

      

I read in other posts that it might be because of the quotes around the JSON object. I tried adding different quotes around the JSON object, but no luck, for example:var obj = JSON.parse("'" + data + "'");

I'm not sure how to handle this. Can anyone point me in the right direction?

thank

The JSON data looks like this:

{
  "services": {
    "service" : [
      {
        "code": "AUS_PARCEL_REGULAR",
        "name": "Parcel Post (your own packaging)",
        "speed": 2,
        "price": 6.95,
        "max_extra_cover": 5000,
        "extra_cover_rule": "100,1.5,1.5",
        "icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
        "description": "Based on the size and weight you've entered",
        "details": "Check our ",
        "delivery_time": "Delivered in up to 3 business days",
        "ui_display_order": 1,
        "options": {
          "option": [
            {

      

AJAX call:

$.ajax({
            type: 'POST',
            dataType: 'JSON',
            url: 'AusPostDomestic.php',
            data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
            success: function(data) {
                //console.log(data);
                var obj = JSON.parse(data);
                $('#auspostresult').html(obj.services.service[0].code);
            }

      

+3


source to share


1 answer


You already have datatype as json, no need to parse it again. So remove the line var obj = JSON.parse(data);

from your callback function.

$.ajax({
  type: 'POST',
  dataType: 'JSON',
  url: 'AusPostDomestic.php',
  data: {
    toPostcode: toPostcodeValue,
    parcelLengthInCMs: parcelLengthInCMsValue,
    parcelHeighthInCMs: parcelHeighthInCMsValue,
    parcelWidthInCMs: parcelWidthInCMsValue,
    parcelWeightInKGs: parcelWeightInKGsValue
  },
  success: function(obj) {
    //console.log(data);
    $('#auspostresult').html(obj.services.service[0].code);
  }
});

      



Api Doc: http://api.jquery.com/jquery.ajax/

+2


source







All Articles