How JavaScript Works in MODX

If you already understand the difference between server-side operations like PHP, and client-side JavaScript in MODX, this article is *not* for you.

People new to JavaScript (JS for short), even if they are experienced PHP coders, are often confused about the relationship between server-side operations and client-side Javascript. StackOverflow is full of questions about how to call PHP functions from JavaScript or how call PHP functions in Javascript. The responses are often terse, and sometimes insulting.

I used PHP for some time and occasionally threw in some JavaScript code I copied from somewhere before I really understood fundamental difference between the two.

Server-side Operations

The server at your web host (or your own machine if you have a localhost install) has one main job. When a user requests a page (by clicking on a link, or typing in a URL), the server looks for the requested page and sends it to the browser. In the very early days of the Web, that was the whole story, and it’s still the most important part. In those days, the pages were HTML files on the server’s drive and were essentially sent directly to the browser for display.

These days, the process is a little more complicated, but still fairly basic. The server may use the rules in an .htaccess file that alter the page request before looking for the file (or telling a banned user to get lost). In MODX, and some other Content Management Systems, for example, a single index.php file handles all the requests and often gets the page content from a table in the database.

In any case, the server processes requests and returns the results to the user’s browser. The server may include JavaScript in the returned page (either directly, or by reference in a URL), but the server does not *execute* the JavaScript, and in fact pays no attention to it at all. As far as the server is concerned, the JS code is just plain text. It merely delivers the raw JavaScript code to the browser. I should mention that we’re ignoring server-side JavaScript, an advanced programming concept that usually requires a custom JavaScript engine on the server and is beyond the scope of this article.

Client-side Operations

The job of actually executing the JavaScript falls to the software built into the user’s browser. Each browser has a built-in JavaScript engine (which the user may have disabled). When rendering a page, if the browser runs into some JS code, it passes it off to the JavaScript engine, which (if JS in enabled) executes it. The JavaScript engine can access (and alter) the HTML elements in the received page, but it knows nothing about what happened at the server to produce it. It only sees the HTML and JS code it receives from the server.

Uses for JavaScript

Some JavaScript code may execute when a page is first loaded (sometimes a lot of it), but after that, it usually only responds to events — clicks, double-clicks, mouse movement, hovering, etc.

JavaScript is of most use when you want to perform actions on a page that don’t require any information from the server. (Ajax requests are an exception that we’ll get to below.) JavaScript validation is a prime example.

Take the case of a contact form. The user enters information and clicks on the “Submit” button. If the user has entered an invalid email address or left key fields blank, there’s no sense in submitting the form to the server, and making sure the form is valid can be done locally in the browser without any communication with the server. JavaScript code tied to the onClick() event of the “Submit” button can execute and check the form for validity. If the form is not valid, the JS code can pop up a message telling the user what’s wrong, and block the submission of the form. The server is completely ignorant of this process. It only sees the completed form if it ever gets submitted.

JavaScript can both examine and modify the HTML code being displayed in the user’s browser. It can sense when the user positions the cursor on an element in the page or when the user leaves that field and clicks somewhere else. It can also find out if an input field or checkbox has been changed. You might use it to hide or show sections of a form based on the value of a checkbox, or to update a running total any time a value is changed in a column of inputs.

Another common use of JS code, often seen in shopping-cart processing, is leading the user through a series of steps. At the conclusion of each step, the user clicks on a “Next” button, or something similar, and the JS code checks the current page for validity, then hides the current page and reveals (or constructs) the next one. The page is never reloaded during this process. The validation or creation of the next step’s page might involve Ajax, which we’ll get to in a bit.

Timers

We’ve been looking at how JavaScript responds to user actions, but what if you want something to happen even when the user isn’t doing anything? Your JS code can set up a timing loop that essentially says, “call this function every x seconds (or milliseconds).” Such a loop could animate a progress bar or log the user out if there’s no activity for a certain amount of time.

Ajax

In handling web pages, especially in “web applications” like Gmail and e-commerce sites, there was a desperate need for the browser to be able to communicate with the server without having to reload the whole page — enter Ajax (an acronym for Asynchronous JavaScript and XMP). Ajax is a method that allows JavaScript code in the browser to make its own requests (technically XMLHttpRequests) to a server without a page reload. The concept was first implemented in the 1990s to update news pages and display a stock ticker.

Ajax is a mystery to many web designers and developers, but it’s actually fairly simple. An Ajax request is just like a regular browser request except that it’s issued by the JS code and doesn’t involve a page reload. The JS code sends a request, and optionally some extra information in the form of variables and their values to some URL on some server. When the response comes back, it goes to the JavaScript rather than being rendered to the screen.

Imagine, for example, a page with a list of users. After each user’s name, is a button called “More Info” that lets the viewer drill down for more information about that user. The button’s onClick() event will trigger some JavaScript code that sends an Ajax request to a page on the server, along with the user’s name or ID. The page on the server contains some PHP code that looks up the user and “echos” the user’s information, which gets sent back to the browser, which hands it off to the JS code that issued the request. That JS code then alters the displayed page to show the user’s information (e.g., in a popup or slider).

In the example we saw earlier for shopping-cart processing, at some point, there will be a check to see if the user is already registered on the site. This requires contacting the server (since the browser has no idea whether the user is registered or not). The JS code will send an Ajax request containing enough information to identify the user (e.g., an email address or user ID). The server will check the database, and respond to the Ajax request with information indicating if the user is registered, and if so, some of the user’s information (e.g. shipping address) that can be used to populate the next page.

JSON

It doesn’t have to be, but the response to an Ajax request is almost always in the form of a JSON string. JSON is simply a method of encoding information in the form of a string of plain text. The user list information described above, might come back looking like this:

{firstName:John,lastName:Doe,phone:555-1234}

Here’s the same JSON string formatted to make it a little easier to read:

{
   firstName:John,
   lastName:Doe,
   phone:555-1234
}

JSON strings can contain simple information like the example above, or extremely complex nested arrays of data containing dates, strings, numbers.

Applying this to MODX

All MODX tags on a page (including snippet tags) will be parsed and any snippets will execute before the page is sent to the user’s browser, where the JS will be interpreted and executed for the first time. MODX pays no attention to the JavaScript on a page, it simply sends it to the browser. Similarly, the JS engine in the browser pays no attention to PHP or MODX tags — it can’t because a) the browser has no PHP interpreter or tag parser, b) those can only be handled by the server and all JavaScript is handled in the client browser, and c) the tags are all gone by the time the page reaches the browser.

JS can be used to set form fields that will show up as $_REQUEST variables (that a snippet could get access to) when the form is submitted to the server, and you can submit a form with JavaScript, but usually the point of using JavaScript is to *avoid* reloading the whole page.

You can send variables from MODX/PHP to the Javascript in various ways as long as the code that sets them up executes before the page is sent to the browser. The easiest method is to have a snippet that sets placeholders, which replace tags in the JS code on the page. For example, the JS code running in the browser has no way on its own to know the pagetitle of the page being rendered. To set a pagetitle variable in JavaScript based on the pagetitle that MODX knows about, you might use something like this as part of the JS code:

$output = '<script type="text/javascript">
    pagetitle = "[[*pagetitle]]";
</script>

MODX would replace the tag with the actual pagetitle of the page being accessed before the page is sent to the browser and that pagetitle would be the value of the pagetitle variable in JavaScript. In other words, MODX is modifying the text of the JavaScript code before it’s sent to the user’s browser. A similar method is used to allow the JS code to use MODX lexicon strings, though the lexicon keys and values are usually written directly into the JS code without the use of placeholders.

For going the other way and sending information from the JavaScript code back to MODX, though, Ajax is really the only practical method. Trying to use JS to alter the code of a MODX tag, for example, won’t ever work because the JS engine in the user’s browser will never see a MODX tag. Except for Ajax requests, there is no practical way for the JS code executing in the browser to communicate with the server in any way. The JS code could submit a form to the server, but that would involve a page reload and would be much slower than using Ajax.

JS in the MODX Manager

In MODX Revolution, the Manager is done almost entirely in JavaScript. When you access the “Manage Users” page, for example, MODX sends JavaScript to the browser, which when executed, renders the whole page. The JS code received by the browser also sends an Ajax request to the user/getlist processor, which queries the database, converts the resulting user information for all users into a JSON string and returns it to the browser. The JS code in the browser then populates the grid with the user information.

The JavaScript code contains triggers that fire JS events when the user does something in the form like clicking a button or selecting a context menu item. When you right-click on a user in the grid and tell MODX to delete the user, for example, the JS code sends an Ajax request containing the user’s ID to the user/delete processor. The processor is just a bit of PHP code in the MODX processors directory. The PHP code in the processor deletes the user from the database and sends a success message (in JSON format) back to the JS code. When it receives the success message, the JS code calls the getlist processor again (with a new Ajax request), and the grid is redrawn without the user. A similar process is used to delete elements from the Element tree, the only difference being that it’s a tree rather than a grid.

Summing Up

Understanding how JavaScript works can help a lot when you’re trying to create a web site that responds intelligently to user actions. JavaScript can examine and modify the HTML code of a web page and respond to user actions. Ajax allows the JS code to communicate directly with the server and then modify the page without forcing a page reload.


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray

I am the author of MODX: The Official Guide and over 30 MODX add-on components. I host Bob's Guides, a source of valuable information for MODX users, and I've been very active in the MODX Forums with over 14,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *


9 − = 7

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>