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:
- In an MVC environment, should the Ajax data part be in the URL?
- I will be splitting up the functions into different files an the production environment.
- 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.