MeltingDog
MeltingDog

Reputation: 15414

Return JSON results as JS array with AJAX?

Apologies in advance - I am new to this and so other answers have not been able to help me.

I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.

Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.

I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?

My AJAX:

$.ajax({
            type: 'POST',
            url: 'calculator.php',
            data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
            success: function(data) {
                <!--NOT SURE WHAT TO PUT HERE-->
            }
})

PHP (after the calculator does its thing - not sure if it needs to be changed):

$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);

The expected JSON results should look 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": [
            {
              "code": "AUS_SERVICE_OPTION_STANDARD",
              "name": "Standard Service",
              "price": "0.00",
              "price_type": "static",
              "option_type": "optional",
              "ui_display_order": 1
            },
            {
              "code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
              "name": "Signature on Delivery",
              "price": 2.95,
              "price_type": "static",
              "option_type": "optional",
              "tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
              "ui_display_order": 2,
              "suboptions": {
                "option": {
                  "code": "AUS_SERVICE_OPTION_EXTRA_COVER",
                  "name": "Extra Cover",
                  "option_type": "optional",
                  "price_type": "dynamic",
                  "tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
                  "ui_display_order": 1
                }
              }
            }
          ]
        }
      },

Upvotes: 1

Views: 87

Answers (2)

rrk
rrk

Reputation: 15846

You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.

Edit 1

If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].

success: function (data) {
    jsonObj = $.parseJSON(data);
    //this gives you the inner onject of the return data
    servicesObj = jsonObj.services; 
}

Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.

$.ajax({
    type: 'POST',
    url: 'calculator.php',
    data: {
        toPostcode: toPostcodeValue,
        parcelLengthInCMs: parcelLengthInCMsValue,
        parcelHeighthInCMs: parcelHeighthInCMsValue,
        parcelWidthInCMs: parcelWidthInCMsValue,
        parcelWeightInKGs: parcelWeightInKGsValue
    },
    success: function (data) {
        jsonObj = $.parseJSON(data);
        //this gives you the inner onject of the return data
        servicesObj = jsonObj.services; //or jsonObj["services"]
    }
})

Upvotes: 1

Hannan
Hannan

Reputation: 514

Your success function will never be called if you are using echo json_encode(); in your php script. You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data

Upvotes: 0

Related Questions