4
\$\begingroup\$

A while ago I started working on a project, which does things mostly with jQuery and PHP. I had some problems with my structure and started using CodeIgniter which uses an MVC pattern. So the PHP part is all good now.

I am just a little worried about my jQuery code. It looks bloated and I feel like there is room for improvement. The problem is that the code is very simple and I don't know how to actually improve it.

My code looks like this:

$(function() {
 var baseURL = "index.php/";
 /* *
 * Fill the list with all available objects
 */
 $(document).ready(function() {
 $.ajax({
 type: "POST",
 url: baseURL+"Objects/getList",
 dataType: "json",
 data: "",
 cache: false,
 success: function(data) {
 $('#object-list').html();
 var objects= "";
 for (var i = 0; i < data.length; i++) {
 objects+= "<option value='" + data.id +"'>" + data[i].name + "</option>";
 }
 $('#object-list').html(options);
 }
 });
 });
 /* *
 * Authenticate and login using a username and password
 */
 $('#login').click(function(event) {
 var username = $("#login-username").val();
 var password = $("#login-password").val();
 $.ajax({
 type: "POST",
 url: baseURL+"User/authenticateUser",
 dataType: "json",
 data: "username="+ username +"&password=" + password,
 success: function(data) {
 var success = data.result;
 if (!success) {
 $("#login-window-inner-message").html("The credentials provided were not found. Please try again.");
 } else {
 $('#login-window').remove();
 LoadGame();
 }
 }
 });
 });
 /* *
 * Run all functions part of the startup procedure
 */
 function LoadGame() {
 UpdateNavigation();
 DisplayUserInfo();
 }
 /* *
 * Update the action screen
 */
 function UpdateActions() {
 $.ajax({
 type: "POST",
 url: baseURL+"Location/getOptions",
 dataType: "json",
 data: "",
 success: function(data){
 $("#action1").html(typeof data.option1 != 'undefined' ? data.option1.title : "<br/>");
 $("#action2").html(typeof data.option2 != 'undefined' ? data.option2.title : "<br/>");
 $("#action3").html(typeof data.option3 != 'undefined' ? data.option3.title : "<br/>");
 }
 });
 }
 /* *
 * Display the description of the current zone
 */
 function DisplayZoneDescription() {
 $.ajax({
 type: "POST",
 url: baseURL+"Location/getZoneDesciption",
 dataType: "json",
 data: "",
 success: function(data){
 $("div#message-log").html("<p class='normal'>" + data.description + "</p>");
 }
 });
 }
});

That's not the entire code (so some called functions might not be there), which would be too long to post here. But the gist of it is that I have about a hundred "hooks" to HTML elements which all fire an Ajax function which returns data after which the screen is updated.

Some things that come to mind:

  1. In an MVC environment, should the Ajax data part be in the URL?
  2. I will be splitting up the functions into different files an the production environment.
  3. The main problem I'm having with this is that it just looks like it's hanging loosely together, and doesn't fit my structured MVC environment/code.
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 17, 2013 at 8:36
\$\endgroup\$
3
  • 1
    \$\begingroup\$ What about security? Will the server refuse to send data if the player executes LoadGame() from the browser debug window without having been authentified? \$\endgroup\$ Commented May 17, 2013 at 12:59
  • \$\begingroup\$ Yea, it's all caught in the PHP code Ajax makes the call to, it's all pretty secure on that level. I'm making sure I don't put any security measures into the JQuery code. At most, error messages returned by PHP are shown to the users (although not at the moment). But generally speaking if a function returns an error it means the user is trying to mess with the script. I dont'see the point in creating message such as "Please stop trying to cheat/hack the system", so that's why you don't see any error messages. \$\endgroup\$ Commented May 17, 2013 at 13:28
  • \$\begingroup\$ DisplayZoneDescription and UpdateActions seem to be getting information from your server not changing/updating data. To keep in line with practices would these not best be served as GET requests?? \$\endgroup\$ Commented May 20, 2013 at 8:49

1 Answer 1

3
\$\begingroup\$

You say you got a hundred of these? And possibly longer?

I suggest you invest on learning these tools:

  • A client-side MV* framework like Backbone. That way, your code will be modular and structured.

  • As for your UI, I suggest you go with Mustache for a logicless templating solution.

  • An automation tool like Grunt, which runs for you the most repetitive tasks like merging files, moving files unit tests etc.

I also suggest you watch this video from Nicholas Zakas regarding scalability and architecture. Though not all points will be applicable, at least you get the idea how to loosely couple your code.

As for the questions:

In an MVC environment, should the Ajax data part be in the url?

If you were to use MVC, that would be handled in the Models and Routers. Depending on the framework, some handle it for you. Just give them the proper routing and parameters, and you are good to go. No "low-level" code.

I will be splitting up the functions into different files an the production environment.

It's only in development that you actually split them so they make sense. In production, you actually merge and minify them. Check out jQuery. Their source is split into parts during development, but end up with a squished file during deployment.

The usual procedure (via Grunt tasks) is:

  • jsbeautifier - Beautify code, so that the linter will be happy
  • JShint - Checks for syntax errors, readability issues, possible break areas.
  • Qunit - Unit testing for all your functions. to check if it works as expected.
  • concat - Join all files into one. Lessens HTTP requests.
  • minify - shrinks your concatenated scripts, to lessen download size.

And you end up with one power-packed nKB file (where n is the size of course).

The main problem I'm having with this is that it just looks like it's hanging loosely together, and doesn't fit my structured MVC environment/code.

I really suggest you invest your time in your toolset. I gave suggestions above based on experience and taste. There are other tools out there, like other MV* frameworks, other template engines. You might even want to learn SASS or LESS for CSS.

Although I encourage you to learn the tools, which will lead you to ultimately abandon your old code, here are a few tips though:

  • The index.php/ part of the url can be removed via url-rewriting on the server. As far as I know, there's a solution posted somewhere in the CodeIgniter forums, which can be searched. That way, your code will always start right after the first / of the domain.

  • The data parameter of $.ajax() can accept objects:

    data: {
     username : username,
     password : password
    }
    
  • These could be avoided using templating:

    $("#login-window-inner-message").html("The credentials provided were not found. Please try again.");
    
answered May 19, 2013 at 10:06
\$\endgroup\$
1
  • \$\begingroup\$ Thank you for your answer, guess I have some reading to do. I'm having a hard time finding good examples for Backbone and Mustache though. As in, I can't find any convincing examples that make me want to use it. But thank you again! \$\endgroup\$ Commented May 22, 2013 at 8:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.