0

I am sending following data to API, but not receiving values of child objects. How to properly URL encode child objects in javascript?

Data:

    var details = {
      OrderDate: "10-Sep-2020",
      OrderID: "1011539",
      Dated: "27-feb-2021",
      CreatedBy: 0012,
      tblAuthorityLetterDtls: [
        {
          ProductCode: "0010005",
          Qty: "1"
        },
        {
          ProductCode: "0010005",
          Qty: "5"
        },
        {
          ProductCode: "0010005",
          Qty: "3"
        }
      ]
    }

Loop code I am using to URL encode data:

    var formBody = [];
    for (var property in details) {
      if (property != "tblAuthorityLetterDtls"){
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
      }else{
        var innerval = details[property];
          for (var i = 0; i < details[property].length; i++) {
          var formBodyinner = [];
          for (var innerproperty in innerval[i]) {
            if (innerval[i].hasOwnProperty(innerproperty)) {
              var encodedKey = encodeURIComponent(innerproperty);
              var encodedValue = encodeURIComponent(innerval[i][innerproperty]);
              formBodyinner.push(encodedKey + "=" + encodedValue);
            }
            formBodyinner.push(encodedKey + "=" + encodedValue);
          }
          formBody.push("tblAuthorityLetterDtls" + "=" + formBodyinner);
        }
      }
    }
    formBody = formBody.join("&");
  • Did my answer help you resolve your problem? if so, please mark it as accepted by ticking the V icon to its left. if not, let me know and I'll try to further help. – OfirD Mar 10 '21 at 12:47

1 Answers1

0

Running your encoding code over your object, we get:

OrderDate=10-Sep-2020&OrderID=1011539&Dated=27-feb-2021&CreatedBy=10&tblAuthorityLetterDtls=ProductCode=0010005,ProductCode=0010005,Qty=1,Qty=1&tblAuthorityLetterDtls=ProductCode=0010005,ProductCode=0010005,Qty=5,Qty=5&tblAuthorityLetterDtls=ProductCode=0010005,ProductCode=0010005,Qty=3,Qty=3

Note that:

  1. This string is a valid query string per RFC 3986, so that per the spec it doesn't have to be encoded. However, your API provider may have applied some assumptions upon some delimters, assigning them a special meaning and hence making them "reserved".
    For example, maybe your API provider doesn't allow using = multiple times within a single query string parameter. This is just an example, of course.
  2. This string contains duplicate child values (each ProductCode and Qty appears twice).

I suggest you just pass the entire string to encodeURIComponent and see if it works. If it does, you can then gradually apply encodeURIComponent for each part of the query string and see what's the problematic part.

Otherwise, you'd have to advise your API provider.

OfirD
  • 9,442
  • 5
  • 47
  • 90