0

I would like to have a class creating any code from given options and output it in a chosen way.

I have written class for generation of simple JavaScript code for such cases where is needed to prepare JavaScript in PHP.

That class has some bug that causes some problems with assembling of output code into larger blocks - and so I decided to rewrite it without that bug (I got idea how to solve it).

All code is generated once (and once per change of text of section).

Problem

How to set (how to keep):

  • what pieces of code may be generated
  • what limitations have each generated piece of code
1

Do not generate code, generate values instead.

Why you need encapsulation

I would suggest that you avoid code generation from one language to another for two reasons:

  • It makes the code difficult to read; small snippets of JavaScript in among lines of PHP cannot be picked up by IDEs and is difficult to follow even for programmers well versed in both languages.
  • It breaks encapsulation since you are inevitably mixing front-end code with back-end code.

How to encapsulate

JavaScript is a powerful client-side scripting language that enables you to perform a whole range of functions in the client's browser; one such function is making HTTP requests to gather information and data that it requires. You can find an introduction to AJAX and XMLHttpRequests here: Getting Started - Ajax | MDN

This allows you to write a JavaScript file that performs the function you intend to carry-out but does not contain the data that it needs to perform it. This script can make a request back to your server to a different resource that generates the data. Once it has the information, it can then proceed.

XMLHttpRequests such as this can even be performed in-line or asynchronously; i.e. it can be done before the page finishes loading or it can be done in the background after the page as finished rendering.

Using this feature of JavaScript, you will completely separate your client-side code and your server-side code.

How to exchange Data

For simple data exchanges I would suggest that you use the JSON format, it is well supported in PHP (with native functions that can convert both to and from JSON) and, obviously, in JavaScript where it can easily be decoded into variables.

You can find an introduction to the JSON data format here: JSON - JavaScript | MDN

To exchange the data you simply:

Generate the JSON file

Gather the variables you wish to pass to the client as a collection of PHP variables (i.e. arrays, integers, etc.). You then pass them through the json_encode function and then print the resulting value to the output buffer.

Decode the JSON file

When the JavaScript file fetches the JSON, you simple parse the data and you will be rewarded with all of the data you need as valid JavaScript variables.

A simple example

By way of example, let us say you want your webpage that presents search results to a user but you don't want them to have to make a new page request every time they click 'search' (page loads are a pain, after all).

You would begin with the search results page; this provides the template and instructs the client to get the JavaScript file.

search.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Search Results | MyApp</title>

    <script type="application/javascript" src="search.js"></script>
  </head>
  <body>
    <h1>Search</h1>
    <form>
      <input type="text" value="Search..." onchange="search(this.value);">
    </form>

    <h1>Results</h1>
    <div id="results_container"></div>
  </body>
</html>

search.js

// First all the code that fetches the data from the server    
var search = function(keyword) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE 6 and older
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // Set a function that will process the response
    httpRequest.onreadystatechange = function() {

      // If the request is complete
      if (httpRequest.readyState === 4) {

        // If the request succeeded
        if (httpRequest.status === 200) {

          // clear old results
          document.getElementById('results_container').innerHTML = '';

          // print new results
          var data = JSON.parse(httpRequest.responseText);
          for(x=0; x < data.length; x++) {
            addResult(data[x]['item']);
          }

        // If the request failed
        } else {
          console.log('Uh Oh! something went wrong...');
        }

      // If the request is not complete
      } else {
        console.log('No problem... I\'ll just wait longer.');
      }
    };

    httpRequest.open('GET', 'http://www.example.org/search.php?keyword='+keyword, true);
}

// And then, all the code that does the processing stuff
var addResult = function(name) {
    item = document.createElement("div");
    item.innerText = name;
    document.getElementById('results_container').appendChild(item);
}

search.php

header('Content-Type: application/json')

$keyword = $_GET['keyword'];
// validate the keyword for malicious input

$resultsArray = // Do something like query a DB, parse a .txt file, ask a carrier pigeon, et al.

// for example purposes, suppose we have the following result array:
$resultsArray = [
    ['relevancy' => 3.7, 'item' => 'horse'],
    ['relevancy' => 1.8, 'item' => 'cart'],
    ['relevancy' => 2.1, 'item' => 'ass'],
    ['relevancy' => 2.1, 'item' => 'donkey'],
];  


function compare_relevancy($a, $b) {
    if ($a['relevancy'] == $b['relevancy']) return 0;
    return ($a['relevancy'] < $b['relevancy']) ? -1 : 1;
}

// Sort the results
usort($resultsArray, 'compare_relevancy');

// Output the results as JSON
echo json_encode($resultsArray);

This is obviously an incomplete implementaiton, but it is a functioning example of how to pass data between a PHP back-end and a JavaScript front-end.

Not the answer you're looking for? Browse other questions tagged or ask your own question.