Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Basically, it's a matter of code organization, trying to delegate as most responsibility as possible to the server and keeping JavaScript use to a minimum, mostly as "glue" code between the view and the server.

Simple example:

Say you have a "select" field (states) which based on user selection it populates another select field (cities).

I currently define the route in a data-* attribute inside the select tag like this:

<select id="state" name="state" data-route="{{ route('get_cities')"></select>

<div id="cities-container"></div>
...

<script>
$('#state').on('change', function() {
   $('#cities-container').load($(this).attr('data-route'), {id_state: $(this).val()});
});
</script>

Then on the method called server-side I just return a view with the select already populated, formatted and with all needed processing done server-side instead of concatenating strings and values with jQuery append, etc.

Is a good practice to do it like this? I'm not really fond of using 20 libs to do something so simple, just plain old school PHP and jQuery. Is there a better way to tackle this? I found this avoids mixing a lot of html code with javascript and prevent using extra javascript functions for formatting (for example numbers, text, etc), since everything is already done by PHP and JavaScript is just the glue, simply request something and show it, do nothing else; complex logic server-side.

Also, defining the route in a data-* attribute lets me use the templating engine (Blade, Twig, etc) and PHP variables, without needing to define a superglobal base_url for JavaScript in order to do a route request based on its alias, instead of its URL.

For example:

$('#cities-container').load(base_url + '/get-cities')

Because, what happens if your route URL changes? Finding every route on the code and replacing it.

Or using some other "request" class to communicate with PHP and use route aliases, etc. Symfony's FOSJsRouting Bundle for example.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.