Get Javascript variable inside json

I have a json file that has about twenty objects like this:

{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "http://www.example.com/wp-content/themes/mytheme/images/profile/user1.jpg",
"contact": {
     "email" : "user1@example.com"
      }
}

I have a javascript code to display images/description from these objects to a page. I want this site to be uploaded in more than one place. So it doesn’t make sense for me to use absolute url in this json file. I overcame the issue in js by passing a variable templateUrl from header.php file and calling it inside the javascript file.

Read More
<script type="text/javascript"> 
    var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

And in javascript:$.getJSON(templateUrl+"/scripts/file.json", function(file){....}

I want a way to pass this templateUrl variable to json file too. So I can have image path set to just images/profile/user1.jpg, and I can prepend the url to this depending on where the site is uploaded.

Related posts

Leave a Reply

1 comment

  1. #json.php
    {
    "firstName": "User1",
    "lastName" : "UserLname",
    "title": "Human",
    "description": "Something Facinating",
    "photoURL": "<?= $_GET['var']; ?>/images/profile/user1.jpg",
    "contact": {
         "email" : "user1@example.com"
          }
    }
    

     

    #main page
    <script type="text/javascript">
    var templateUrl = encodeURI("http://example.com");
    
    $(function(){
        $.getJSON(
            'json.php?var=' + templateUrl,
    
            function(data){
                $.each(data, function(key, val){
                    console.log(key + ": " + val);
                });
            }
        );
    });
    
    </script>
    

     

    Output:

    firstName: User1
    lastName: UserLname
    title: Human
    description: Something Facinating
    photoURL: http://example.com/images/profile/user1.jpg
    contact: [object Object]