-1

I am building a Project management app using JavaScript and PHP.

Many of my JavaScript files will need access to a user list from my backend database. To increase performance or server hits I would like to build the user list with user data attached 1 time in PHP and print it to the screen as a JavaScript Object which my other JavaScript files can then access to get users data.

Assuming I have 20 users.

I need to have access to these user fields in ALL my JavaScript app/objects:

  • User name
  • User ID
  • User ACL role
  • User gravatar image URL

I am uncertain if I should generate a JavaScript Object with my PHP of the userlist or if it needs to be generated as JSON?

Also which ever it be, object or JSON, can you please show how it should be formatted to include multiple user records in the list and then how I would access a users data from my other JavaScript files assuming I have the user's ID.

So if I have user ID 1, I can call a function or object from my other JavaScript files and they will have access to all data for that user with ID 1 by getting it from the JavaScript that my PHP would print into the header of page.

Any help please?


Ideally I think something like being able to call:

var user = cureentJsObject.getUser(userId);

user.gravatarUrl  // https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG

user.username  // JasonDavis

user.role   // admin

Being able to do something like that inside of my other JavaScript object/apps based on the data in the header of screen for userlist would be really nice but I am not certain how to do it?


UPDATE

I think this PHP would generate what I want. Just have to figure out the best way to access it in all of my objects in other JS files in the page

<?php
// PHP array
$userList = array(
    array(
        'id' => '1gdfgdfkn123423423',
        'username' => 'JasonDavis',
        'role' => 'admin',
        'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
    ),
    array(
        'id' => '2gdfgdfkn123423423',
        'username' => 'John Doe',
        'role' => 'user',
        'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
    ),
    array(
        'id' => '3gdfgdfkn123423423',
        'username' => 'Rick James',
        'role' => 'user',
        'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
    ),
);
?>

var users = <?php echo json_encode($userList) ?>;

JSON output:

var users = [{
    "id": "1gdfgdfkn123423423",
    "username": "JasonDavis",
    "role": "admin",
    "gravatar":   "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
    "id": "2gdfgdfkn123423423",
    "username": "John Doe",
    "role": "user",
    "gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
    "id": "3gdfgdfkn123423423",
    "username": "Rick James",
    "role": "user",
    "gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}];

UPDATE 2

I can now access the user from the above...

<script>
function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
    }
  }
  throw "Couldn't find object with id: " + id;
}


var users = <?php echo json_encode($userList) ?>;
var id = '2gdfgdfkn123423423';

var user = findById(users, id);

alert(user.gravatar);

</script>
JasonDavis
  • 48,204
  • 100
  • 318
  • 537
  • make ajax requests for data as needed. WIth the proliferation of single page apps that's the most common approach these days. Put together a simple `Users Service` you can access from any part of js app with methods like: `getUser(id, callback)`. Seems to me most of the answers are just telling you what you want to hear – charlietfl Jul 17 '15 at 22:24
  • If you will always need users data, it's better to put it on your template (as above), and don't make an extra ajax request. – Félix Jul 17 '15 at 22:36
  • In JS you can do an object with users id as properties and user data as values, so you can access to users['2gdfgdfkn123423423'].name to get "John Doe", so you don't need a function. – Félix Jul 17 '15 at 22:39
  • @feliz thanks. I actually think I am evolving into a function that will check for the global userlist and use it if available and on failure will then load with ajax as a fallback – JasonDavis Jul 17 '15 at 23:08

4 Answers4

1

I would say using JSON.

You can make a multidimensional array in PHP which encodes to JSON.

After you parse the JSON in JS you can access it like an object. E.g.:

myUserData[1].name
  • So in each of my JS object/apps I could have a function inside them to `myObj.getUser(userId)` and in that function assign `var user = myUserData[userId];` and then call `user.role` in that object? I am still learning JS so I have never really had to bring global spaced data into my own objects so I know very little how it will react – JasonDavis Jul 17 '15 at 21:51
  • I dont understand what you are asking exactly. A flow that makes sense to me is either use Ajax to get JSON from PHP (dynamic) or make php output a JavaScript object as you would type it (on page load). It really depends on what you want to achieve. – Jan Jouke Tjalsma Jul 17 '15 at 21:59
  • I updated my question near the bottom is example code. I just need to know how to best access and get a particular users data assuming I have there User ID and access there data in all my other JS files and obects. – JasonDavis Jul 17 '15 at 22:06
  • There are lots of examples of how to do this. Here's one: http://stackoverflow.com/q/7364150/4699406 – Jan Jouke Tjalsma Jul 17 '15 at 22:10
1
  1. If you will always need all your users data, you can write an array of users in your PHP template as a JS array of objects. You don't need JSON. Something like:
<?php
$users_JS = array_map(function($user) {
  return "{name: '{$user->name}', gravatar: '{$user->gravatar}'}";
}, $users)
?>

<head>
  <title>PHP to JS</title>
  <script>
    window.MyApp.users = [
    <?php echo implode(',', $users_JS); ?>
    ];
  </script>
</head>

Now you can access your user list in window.MyApp.users.

  1. If you need user data on demand (you don't know what data your app will need), you can do a little API in PHP that returns a user on JSON format:
<?php
  $user = getUserFromId($_GET['id']);
  header('Content-type: application/json');
  echo json_encode($user);

And in JS:

$.ajax({
    type: 'GET',
    url: '/getUser.php', // URL of previuose PHP
    data: {id: 3}
}).done(function(user3) {
    // Do awesome things with user3
});

Obviously, this code needs validation, 404 if user id doesn't exists, etc, etc...

HTH!

Félix
  • 1,685
  • 2
  • 11
  • 6
0

You can use json_encode passing your user object to it.

Willian
  • 136
  • 4
  • I'm aware of this part but I am not certain as to best route as my end goal is to access a user object from the global space inside of each of my private objects – JasonDavis Jul 17 '15 at 21:53
-1

The better way is to create a string with concatenating with '.' operator and in javascript use JSON.parse to make it a JSON object

abs
  • 801
  • 6
  • 15