Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Adding JavaScript to PHP Module

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Adding JavaScript to PHP Module

Postby jp2code » Tue Jan 14, 2014 9:10 am

I want to find a way to add JavaScript to my PHP Modules before the DOM renders them.

I have found several examples of how to pass JavaScript VARIABLES to PHP (using ajax), but nothing that allows someone to pass the actual JavaScript to PHP.

I have a project that creates each HTML object from a library of PHP Modules. Each PHP Module is a descendant of AbstractHTMLEntity:

Code: Select all
<?php

abstract class AbstractHTMLEntity {

  /**********************************************************************/
  /* Class properties
  /**********************************************************************/
  private $value = '';
  private $attributes = array();
  private static $entity_with_name_attr = array('input', 'select', 'textarea');
  private static $entity_with_value_attr = array('input', 'option');
  private static $attr_with_multi_values = array('class');
  protected $element_type;
  protected $tip = '';
  protected $entity_value_as_content = false;

  /**********************************************************************/
  final public function setAttribute($name, $value) { // If the specified attribute supports multiple values...
    if(in_array($name, self::$attr_with_multi_values) === true){
      // Expand list into attribute value array
      $this->attributes[$name] = explode(' ', trim($value));
    } else { // Otherwise Just use it
      $this->attributes[$name] = $value;
    }
  }

  /**********************************************************************/
  final public function addAttribute($name, $value) {
    // If attribute is already present...
    if(isset($this->attributes[$name])) {
      // If the attribute has a single value...
      if(is_array($this->attributes[$name]) === false) {
        // Create array
        $this->attributes[$name] = array($this->attributes[$name]);
      }
      // If the specified attribute supports multiple values...
      if(in_array($name, self::$attr_with_multi_values) === true) {
        $values = explode(' ', trim($value)); // Expand list into attribute value array
        foreach($values as $value) {  // For each new attribute value...
          if($this->hasAttribute($name, $value) === true) { // If this attribute has the specified value...
            $this->removeAttribute($name, $value); // Remove it
          }
        }
        // Combine the existing and new value arrays
        $this->attributes[$name] = array_merge($this->attributes[$name], $values);
      } else {
        // Push value onto the value array
        $this->attributes[$name] = array($value);
      }
    } else { // If the specified attribute supports multiple values...
      if(in_array($name, self::$attr_with_multi_values) === true) {
        // Expand list into attribute value array
        $values = explode(' ', trim($value));
        // Assign new value array
        $this->attributes[$name] = $values;
      } else { // Otherwise Just use it
        $this->setAttribute($name, $value);
      }
    }
  }

  /**********************************************************************/
  final public function removeAttribute($name, $value) { // If attribute is already present...
    if(isset($this->attributes[$name])) {
      // If the attribute has a single value...
      if(is_array($this->attributes[$name]) === false) {
        // If the current value is the one being removed...
        if(trim($this->attributes[$name]) == trim($value)) {
          // Clear the value
          $this->attributes[$name] = '';
        }
        // If there are no more values for this attribute...
        if(trim($this->attributes[$name]) == '') {
          // Remove the entire attribute
          unset($this->attributes[$name]);
        }
      } else { // Otherwise...
        // Look for specified value in attribute values array
        $key = array_search($value, $this->attributes[$name]);
        // If value found...
        if($key !== false) {
          // Remove it
          unset($this->attributes[$name][$key]);
        }
        // If there are no more values for this attribute...
        if(count($this->attributes[$name]) == 0) {
          // Remove the entire attribute
          unset($this->attributes[$name]);
        }
      }
    }
  }

  /**********************************************************************/
  final public function getAttribute($name) { // Declare local variables
    $value = '';
    // If the attribute has a single value...
    if(is_array($this->attributes[$name]) === false){
      // Just use it
      $value = trim($this->attributes[$name]);
    } else { // Otherwise...
      // Implode values array
      $value = trim(implode(' ', $this->attributes[$name]));
    }
    // Return value
    return $value;   
  }

  /**********************************************************************/
  /* jQuery-esque wrapper around addAttribute() and getAttribute()
  /* Note: It will not operate an enumeration of abstract HTML entities
  /* similiar to jQuery, which operates on the first element in an
  /* enumeration and isn't overloaded to accept all the various argument
  /* combinations as the jQuery method of the same name
  /**********************************************************************/
  final public function attr() { // Declare local variables
    $name = '';
    $value = '';
    // Retrieve the arguments passed
    $args = func_get_args();
    // Switch on number of arguments
    switch(func_num_args()){
      // If one argument...
      case 1:
        // Retrive the first argument
        $name = $args[0];
        // Retrieve the specified attribute
        $value = $this->getAttribute($name);
        break;
      // If two arguments...
      case 2:
        // Retrive the first and second argument
        $name = $args[0];
        $value = $args[1];
        // Add the specified attribute value
        $this->addAttribute($name, $value);
        break;
      // Otherwise...
      default:
        // Do nothing
        break;
    }
    // Return value
    return $value;   
  }

  /**********************************************************************/
  final public function hasAttribute($name, $value) { // Declare local variables
    $has_attribute = false;
    // If attribute is already present...
    if(isset($this->attributes[$name])) {
      // If the attribute has a single value...
      if(is_array($this->attributes[$name]) === false) {
        // If the current value is the one being inquired upon...
        if(trim($this->attributes[$name]) == trim($value)) {
          // Attribute value located
          $has_attribute = true;
        }
      } else { // Otherwise...
        // Look for specified value in attribute values array
        $has_attribute = (array_search($value, $this->attributes[$name]) !== false);
      }
    }
    // Return result
    return $has_attribute;
  }

  /**********************************************************************/
  final public function setClass($value) { // Specific call to set attribute method
    $this->setAttribute('class', $value);
  }

  /**********************************************************************/
  final public function addClass($value) { // Specific call to add attribute method
    $this->addAttribute('class', $value);
  }

  /**********************************************************************/
  final public function removeClass($value) { // Specific call to remove attribute method
    $this->removeAttribute('class', $value);
  }

  /**********************************************************************/
  final public function hasClass($value) { // Specific call to has attribute method
    return $this->hasAttribute('class', $value);
  }

  /**********************************************************************/
  final public function isRequired() { // Specific call to has attribute method
    return $this->hasAttribute('class', 'required');
  }

  /**********************************************************************/
  final public function makeRequired() { // Specific call to addClass method
    $this->addClass('required');
  }

  /**********************************************************************/
  final public function makeReadOnly() { // Specific call to addAttribute method
    $this->addAttribute('readonly', 'readonly');
  }

  /**********************************************************************/
  final protected function renderAttributes() { // Declare local variables
    $output = '';
    $value = '';
    $value_prop = '';
    $value_current = false;
    $value_found = false;
    $name_current = false;
    // If there are attributes...
    if(isset($this->attributes)){
      // For each attribute...
      foreach($this->attributes as $k => $v){
        // If current attribute is the value attribute...
        switch($k){
          // Name attribute
          case 'name':
            // Current item is name attribute
            $name_current = true;
            break;
          // Value attribute
          case 'value':
            // Current item is value attribute
            $value_current = true;
            // Value attribute found
            $value_found = true;
            // Save value
            $value = htmlentities($this->attr($k));
            break;
        }
        // If current attribute is name attribute and element type supports it...
        if($name_current === true){
          // If element type supports it...
          if(in_array($this->element_type, self::$entity_with_name_attr) === true){
            // Include the attribute and its value
            $output .= " $k=\"{$this->attr($k)}\"";
          }
        } else if($value_current === true ) { // If current attribute is value attribute...
          // If value should not be rendered in the content and element supports value attribute...
          if($this->entity_value_as_content === false && in_array($this->element_type, self::$entity_with_value_attr) === true){
            // Save value property value
            $value_prop = $this->getValue();
            // If value attribute value and value property value are different...
            if($value !== $value_prop && !empty($value_prop)){
              // Use value property
              $value = htmlentities($value_prop);
            }
            // Include the attribute and its value(s)
            $output .= " $k=\"$value\"";
          }
        }
        // Otherwise, if not empty...
        else if(!empty($v)){
          // Include the attribute and its value(s)
          $output .= " $k=\"{$this->attr($k)}\"";
        }
        // Reset flags
        $value_current = false;
        $name_current = false;
      }
    }
    // If value attribute not found and there is a value...
    if($value_found === false && $this->entity_value_as_content === false && in_array($this->element_type, self::$entity_with_value_attr) === true){

      // Save value property value
      $value_prop = htmlentities($this->getValue());

      // Include the attribute and its value from the value property
      $output .= " value=\"$value_prop\"";
    }
    // Return rendered attributes
    return $output;
  }

  /**********************************************************************/
  public function setElementType($value) {
    if(isset($value)){
      $this->element_type = $value;
    }
  }

  /**********************************************************************/
  public function setValue($value) {
    if(isset($value)){
      $this->value = $value;
    }
  }

  /**********************************************************************/
  /* Just an natural language alias for setValue method
  /**********************************************************************/
  public function setDefaultValue($value) {
    $this->setValue($value);
  }

  /**********************************************************************/
  /* Just an natural language alias for setValue method
  /**********************************************************************/
  public function setInitialValue($value) {
    $this->setValue($value);
  }

  /**********************************************************************/
  public function getElementType() {
    return($this->element_type);
  }

  /**********************************************************************/
  public function getValue(){
    return($this->value);
  }

  /**********************************************************************/
  public function setToolTip($tip) {
    if(isset($tip)){
      $this->attributes['title'] = $tip;
    }
  }

  /**********************************************************************/
  public function getToolTip() {

    return($this->attributes['title']);   
  }

  /**********************************************************************/
  abstract public function render();
}

?>

This PHP Module allows me to add or remove attributes to the HTML control before the DOM renders it.

Below, for example, is how the HTMLForm_Text object is created from the AbstractHTMLEntity:

Code: Select all
<?php

class HTMLForm_Text extends AbstractHTMLEntity {

  public function __construct($element_name) {

    // Set element type
    $this->setElementType('input');

    // Specify default attributes
    $this->attr('type', 'text');
    $this->attr('name', $element_name);
    $this->attr('id', $element_name);
  }

  public function render() {
    $output = "<{$this->getElementType()}{$this->renderAttributes()} />";
    return($output);
  }
}
?>

We use the HTMLForm_Text control like this:

Code: Select all
$name = new HTMLForm_Text('Name');
$name->makeRequired();
$name->setValue(get_session('fullname'));


Using the HTMLForm_Text control and example above, I would like to find a way to insert a JavaScript or jQuery block.

Code: Select all
$name = new HTMLForm_Text('Name');
$name->attributes[] = { 'onchange', '$($this).keyup(function() { $(this).val($(this).val().toUpperCase()); } );';
$name->setValue(get_session('fullname'));

I can't seem to understand how I would make something like that work.

Is it possible? If so, how would I do that?
-
The example above shows how script might be added inline, but I would also like to see ideas on how to add script like this to the <head> of the HTML document.
User avatar
jp2code
New php-forum User
New php-forum User
 
Posts: 2
Joined: Sat Dec 17, 2011 7:42 pm
Location: Longview, TX

Return to PHP coding => General

Who is online

Users browsing this forum: No registered users and 10 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron