Math and Science
Math and Science

Reputation: 55

How To Write To Javascript Object With PHP

Currently, my front end website uses a .js file that is hosted on dropbox as a "database". It is essentially a Javascript dictionary that is called, and then used. This is the format.

myDictionary = {
"Tag1":["Tag1","info1","info2"],
"Tag2":["Tag2","info1","info2"],
...
...

}
myDictionary2 = {
"Tag1":["Tag1","info1","info2"],
"Tag2":["Tag2","info1","info2"],
...
...

}

I'm starting to transition into PHP, and I wanted to know if it was possible to add new entries to this dictionary without messing things up. Basically, what I am asking is if there is a way of adding entires to a javascript dictionary, preferably without just adding the text, as it may get complicated. Thank You!

Upvotes: 3

Views: 124

Answers (2)

davethebrave
davethebrave

Reputation: 823

First off: I strongly suggest you use JSON to store your data. Then use AJAX to load the file and parse its contents with JSON.parse() to get the resulting JavaScript object.

Your example could look something like this:

[{
    "Tag1":["Tag1","info1","info2"],
    "Tag2:"["Tag2","info1","info2"]
},
{
    "Tag1":["Tag1","info1","info2"],
    "Tag2:"["Tag2","info1","info2"]
}]

You would then parse the JSON like so:

var dictionaries = JSON.parse(jsonstring);

As for your question regarding the manipulation of the file, this needs to be done with an API. You will need to handle this server side (in PHP), as you do not want to give the client (or really the rest of the world) access to your Dropbox account. This is probably not as straight forward as you'd like. However, this way you can verify that what you are storing in the file is valid and won't cause a mess when someone else is trying to access the (possibly corrupted) file.

See: Using the Core API in PHP.

However, I believe what you really want is a simple JSON DB. A quick search turned up TaffyDB. There are probably other ones. I have no experience with TaffyDB but it doesn't look too difficult to use and it's widely used.

However, if this is something multiple people will be using at potentially the same time, I strongly suggest you invest the time needed to make a good and most importantly SAFE solution using a reliable database (MongoDB, CouchDB, or any other document based database).

Upvotes: 1

Mike
Mike

Reputation: 24393

Yes, it's possible using json_decode() and json_encode():

<?php

$myDictionary = json_decode('{
    "Tag1":["Tag1","info1","info2"],
    "Tag2":["Tag2","info1","info2"]
}');

$myDictionary->Tag3 = ["Tag3","info1","info2"];

echo json_encode($myDictionary, JSON_PRETTY_PRINT);

Output:

{
    "Tag1": [
        "Tag1",
        "info1",
        "info2"
    ],
    "Tag2": [
        "Tag2",
        "info1",
        "info2"
    ],
    "Tag3": [
        "Tag3",
        "info1",
        "info2"
    ]
}

Upvotes: 4

Related Questions