Voriki
Voriki

Reputation: 1647

How to decide whether to use a JavaScript or PHP object when using both languages?

For example, you are building a dictionary app where the entries are objects, and all the values are stored in a server-side database. The entries are visible client-side, so they should eventually be JavaScript objects. However, since the data is server-side, there are two ways to construct the object:

  1. Construct the entries objects via PHP, then pass the result to a .js script, which makes JavaScript objects from it.

  2. Construct the entries via JavaScript, calling AJAX methods on the object to request the specific information about the entry (e.g. definition, synonyms, antonyms, etc.) from the server.

The first way ends up constructing each entry twice, once via PHP and once via JavaScript. The second way ends up calling several AJAX methods for every construction, and opening and closing the database connection each time.

Is one preferable to the other, or is there a better way to do this?

Upvotes: 1

Views: 127

Answers (3)

Dan Blows
Dan Blows

Reputation: 21184

Totally depends on the project. There are just too many variables to say 'you should do it this way'.

Instead, test it. Do it one way, push it to a high number of requests, and profile it. Then switch and try the other way. Keep it easy to switch the output from the PHP by following the MVC pattern.

The only general rule is 'minimise the number of HTTP requests', as HTTP is by far the biggest bottleneck when a page is loading.

Upvotes: 1

Marcus
Marcus

Reputation: 5153

Another option would be, if you're not tied to PHP, to have a JS-based back-end like Node.js. This way you can transmit everything in one format. In some cases you can even store the JS object directly on the database. An example of this kind back-end would be Node.js + Mondo DB, if document database is suitable to your needs.

If you're tied to PHP/JS, i'd go for minimizing AJAX calls. Making asynchronous transfer (duplicating objects) should achieve improved user experience, and the choices made should aim for this. Too many HTTP-requests usually end up making the site slow to react, which is one of the things we usually try to get rid of by using AJAX.

One way that's sometimes useful is also to render JS object by PHP, that could be used if the data is going to be needed but that should not be directly (or at all) shown to the user.

Upvotes: 1

Frankie
Frankie

Reputation: 25165

I use a rule of thumb, the less AJAX (on a page opener) the better.

If you can push all information on the page load to the user, do it. Then use AJAX on subsequent calls. Otherwise the user-experience will suffer from AJAX (rather than benefit) as the page will take longer to load.

Upvotes: 3

Related Questions