skip to Main Content

When i do Ctrl+U, there is below json in my page DOM

<script type="text/x-magento-init">
{
  "#country": {
    "regionUpdater": {
      "optionalRegionAllowed": true,
      "regionListId": "#region_id",
      "regionInputId": "#region",
      "postcodeId": "#zip",
      "form": "#form-validate",
      "regionJson": {
        "config": {
          "show_all_regions": true,
          "regions_required": [
            "AU",
            "BR",
            "CA",
            "CN",
            "CO",
            "HR",
            "EE",
            "IN",
            "LV",
            "LT",
            "MX",
            "PL",
            "RO",
            "ES",
            "CH",
            "US"
          ]
        }
      }
    }
  }
}
</script>

I want to get regionJson value in my custom js file, Can someone please give me any solution or any idea to achieve this.

3

Answers


  1. You can get regionJson like this,

    json = {
      "country": {
        "regionUpdater": {
          "optionalRegionAllowed": true,
          "regionListId": "#region_id",
          "regionInputId": "#region",
          "postcodeId": "#zip",
          "form": "#form-validate",
          "regionJson": {
            "config": {
              "show_all_regions": true,
              "regions_required": [
                "AU",
                "BR",
                "CA",
                "CN",
                "CO",
                "HR",
                "EE",
                "IN",
                "LV",
                "LT",
                "MX",
                "PL",
                "RO",
                "ES",
                "CH",
                "US"
              ]
            }
          }
        }
      }
    }
    
    console.log(json["#country"]["regionUpdater"]["regionJson"])
    
    Login or Signup to reply.
  2. Try something like this, ideally # is not valid in json key name.

    So i used replace method to remove it, then parse it

     var getTxt=$('#script').html().replace('#country','country');
     var jsonData= JSON.parse(getTxt);
      
     console.log(jsonData.country.regionUpdater.regionJson);
    

    Working Demo

    Login or Signup to reply.
  3. Batter Solution would be to find the phtml file which call might be calling block or function which are providing the regionJson data and you can get the same data in your js file by invoking it using text/x-magento-init and pass config same as passed in your question you can also store that in the javascript global window object and get this value later in the js file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search