Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with JSON.Parse - console shows error in DOCTYPE

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

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

But I get an error saying there is 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 this could be because of quotation marks around the JSON object. I have tried to add different quotes around the JSON object but with no luck, eg: var obj = JSON.parse("'" + data + "'");

I am not sure how to tackle this one. Can anyone point me in the right direction?

Thanks

The JSON data looks like:

{
  "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);
            }
like image 855
MeltingDog Avatar asked Feb 16 '26 10:02

MeltingDog


1 Answers

You have alreadyb added datatype as json , no need to parse it again. So remove line var obj = JSON.parse(data); from your success 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/

like image 100
Pranav C Balan Avatar answered Feb 18 '26 22:02

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!