Currently showing entries with the tag: PHP

page 1 of 1
1 

Javascript and ASP.NET Hacks

September 12, 2007 • 7:25AM • permalink
Both ASP.NET and Javascript can be extremely useful, in entirely different ways. ASP.NET is a great server-side environment and Javascript can be used to enhance the client-side experience. In my experience, junior developers often have a difficult time getting the two to play nicely together, so I thought I would share a few common tricks. (Please note tricks apply whether you code using Visual Basic or C#. Also, many of these tricks or similar implementations of them are trivial to implement in many other server-side languages, such as PHP, Python or JSP.)

1) Data Injection (ASP.NET => Javascript)

First, in the code-behind area of the page, we setup a simple string variable from an external source:


private string username;
public string Username
{
   get { return username; }
   set { username = value; }
}

public void Page_Load(object sender, EventArgs e)
{
   username = Request["username"];
}



Then, in the front-end part of the page, we can use this variable for a Javascript injection:


<head>
   <script type="text/javascript">
      alert('<% =Username %>');
   </script>
</head>



The result, is that when the page loads, the value that is in username is injected into the Javascript. So if the value Adam is passed into the page, the Javascript is transformed at runtime to:


<head>
   <script type="text/javascript">
      alert('Adam');
   </script>
</head>



So that when the page loads, the alert box appears with the requested username:




2) Input Injection (Javascript => ASP.NET)

There are many ways to get data from a HTML form to the ASP.NET code, including the basic query string and basic form post. Sometimes though, a server control doesn't contain the dynamic nature needed to properly collect user input. In the following example, we're going to collect data from multiple checkboxes and pass them back as a comma-delimited string.

Before I begin, you may ask why I wouldn't just use a CheckboxList or a series of single Checkboxes. You could (especially after reading the third trick that I will present below), but that would make it a little more difficult to do a few dynamic tricks with the checkboxes, like a Select All or Select None functionality.

First, the back-end code:


private string received_values;
public string ReceivedValues
{
   get { return received_values; }
   set { received_values = value; }
}

public void Page_Load(object sender, EventArgs e)
{
   received_values = Request.Form["sent_value"];
}


All we're doing is making the results of a HTTP form post, with the input name "sent_value", publically accessible.

Then, on the front-end, we're going to create our checkboxes based on the contents of a static array. This is only to make a simple example, and our "IDValues" could represent anything from friends on a buddylist, stocks in a portfolio, books in a library, software titles in a shopping cart - anything you could retrieve from a database, XML feed, etc.

Here's the entire code listing. The explanation is below it.


<form id="the_form" method="post">
   <% int[] IDValues = new int[] { 5, 10, 25, 50 }; %>
   <% for (int x = 0, cnt = IDValues.Length; x < cnt; ++x) { %>
      <input type="checkbox" id="someid_<% =IDValues[x] %>" /> <% =IDValues[x] %>
   <% } %>
   <input type="hidden" id="sent_value" name="sent_value" value="" />
   <input type="button" onclick="doSubmit(); return false;" value="Submit" />
</form>

<% if (!string.IsNullOrEmpty(ReceivedValues)) { %>
   <strong>Received Values:</strong> <% =ReceivedValues %>
<% } %>
<script type="text/javascript">
   function doSubmit()
   {
      var frm = document.getElementById('the_form');
      var post_string = "";
      for (var x = 0, cnt = frm.elements.length; x < cnt; ++x)
      {
         if (frm.elements[x].checked)
           post_string += frm.elements[x].id.substring(7) + ",";
      }

      if (post_string.length > 0)
         post_string = post_string.substring(0, post_string.length - 1);

      document.getElementById('sent_value').value = post_string;
      frm.submit();
   }
</script>



It's actually very simple! We create four checkboxes, easily identified by the prefix 'someid_' in their id property. When the button is clicked, we obtain a reference to the form object and loop through all of its elements. If the item is checked (obviously indicating a checkbox in our example), then we remove the 'someid_' prefix and append the id to a running string, with a comma-delimeter.

After traversing the whole form, we cleanup the string by removing the extraneous comma and store the value in a hidden input tag we've created already. This is the key to posting the resulting values to the back-end.

Upon submission, the ReceivedValues string will be populated and will be output, like so:




3) Javascript on ASP.NET Controls (Javascript <=> ASP.NET)

Finally, there are a few additional tricks you can mix in to ease the integration of Javascript and ASP.NET. A very simple example would be a form that requires both client-side validation and server-side validation.

I'll assume the reader can already output an error message using either Javascript or ASP.NET. In this example, we'll assume that we have an existing system to validate a page and upon error, set the InnerHtml property of a div object with the ID 'ErrorMessage'. (Note that divs are implemented as HttpGenericControl objects on the back-end)

If we decided to add in Javascript validation as well (possibly to implement a 'strong password' indicator like Live.com), we don't want to have to create a new location for Javascript error messages.

Using a simple trick, we don't have to:


<form runat="server">
   <div id="ErrorMessage" runat="server"></div>
   <script type="text/javascript">
      document.getElementById("<% =ErrorMessage.ClientID %>").innerHTML = "Cool, eh?";
   </script>
</form>



That's all there is to it! While this example is oversimplified, it is easy to see how it can be implemented and extended. This applies to all the examples given above. With the plethora of ASP server controls and Javascript methods available, not to mention AJAX implementations, it's very easy to see how you can make your sites much more dynamic by using the above tricks.


How to Create Dynamic Blocks in Drupal

October 14, 2007 • 10:21PM • permalink
One of my clients uses the Drupal CMS Framework, which requires me to code custom modules and create custom blocks. Drupal (and PHP in general) make a lot of things very easy, but in some cases (Drupal in particular) make the simple things VERY difficult. I've come across quite a few cases where I needed to create dynamic blocks of content that can be stored and retrieved. At first I thought Drupal would make it impossible, but the solution is actually quite simple.

For this example, I'm going to build a simple Google AdSense module that will allow the creation of an infinite number of blocks.


The Assumptions

1) This module was built using Drupal 4.7. I'm not familiar enough with other Drupal environments to assure that this will work, but if anybody tries testing it on other Drupal versions - please let me know so I can update this blog entry!

2) I'm going to assume that the reader has built a basic Drupal module before and does not need a basic explanation of hooks.

3) I'm going to assume that there was previously a variable_set('google_adsense_code', 'pub-XXXXXXXXXXXX-XXXX') call in some form that will allow the site administrator to set their personal AdSense code.


The Database

Now, let's setup a basic database schema for this module. (Note, this was executed on MySql 5.0.22)


CREATE TABLE IF NOT EXISTS gadsense_blocks (
   bid INT AUTO_INCREMENT PRIMARY KEY,
   width INT,
   height INT,
   type VARCHAR(32)
);



The above would either be executed directly on the database server or embedded in a Drupal module .install file to create the table the first time the module is installed.

The above table is very simple with an auto-incrementing bid, the width and height of our target ad, and a simple text field we'll use to store whether our ad is a text or image ad (or both).


The Core Module Hooks

As I said above, I'm going to assume the reader has built a basic Drupal module before and can understand the below without explanation.


function gadsense_help($section = 'admin/help#gadsense') {
   switch ($section) {
   case 'admin/modules#description':
      return t('Creates an area for Google AdSense support.');
   }
}


function gadsense_perm() {
   return array('administer adsense');
}


function gadsense_menu($may_cache) {
   $items = array();

   $items[] = array(
      'path' => 'admin/settings/gadsense/list',
      'title' => t('Google AdSense Ads'),
      'callback' => 'list_ads_page',
      'access' => user_access('administer adsense'),
      'type' => MENU_CALLBACK,
   );

   $items[] = array(
      'path' => 'admin/settings/gadsense/add',
      'title' => t('Google AdSense Ads'),
      'callback' => 'create_ads_page',
      'access' => user_access('administer adsense'),
      'type' => MENU_CALLBACK,
   );

   return $items;
}




The Administrator Pages

Now that we've got our core module created, we can get to work! We're going to create two pages for basic administration. The first page, the main admin page, will list all the blocks we've created so far and offer a link to create a new one.


function list_ads_page() {
   $result = db_query('SELECT * FROM {gadsense_blocks} ORDER BY width + " x " + height ASC');
   $rows = array();
   while ($field = db_fetch_object($result)) {
      $rows[] = array($field->bid, $field->width, $field->height, $field->type);
   }
   if (count($rows) == 0) {
      $rows[] = array(array('data' => t('No ad blocks have been defined.'), 'colspan' => '6'));
   }

   $header = array(t('id'), t('width'), t('height'), t('type'));

   $output = theme('table', $header, $rows);
   $output .= '<br /><br />';
   $output .= l("Add a New Block", "admin/settings/gadsense/add");

   return $output;
}



This will form the page that you see here (by default):



The second page will perform the first half of our Drupal "magic". We're going to build the page to create our blocks. First we need to draw the form. Again, I'm going to assume you're competent with Drupal module building and just supply the code:


function create_ads_page() {
   $form = array();

   $sizes = array('120x600', '160x600', '728x90', '468x60', '300x250');
   $types = array('text', 'image', 'text/image');

   $form['ad_size'] = array('#type' => 'select', '#title' => 'Ad size', '#options' => $sizes);
   $form['ad_type'] = array('#type' => 'select', '#title' => 'Ad type', '#options' => $types);

   $form['submit'] = array('#type' => 'submit', '#value' => 'Submit');

   return drupal_get_form('create_ad', $form);
}



Which will show the following page:




When submitted, the following code is executed.


function create_ad_submit($form_id, $form_values) {
   $ad_sizes = array('120x600', '160x600', '728x90', '468x60', '300x250');
   $width = 0;
   $height = 0;
   $type = '';

   //check for valid sizes
   foreach ($ad_sizes as $key => $value) {
      if ($form_values['ad_size'] == $key) {
         $dimensions = explode('x', $value);
         $width = $dimensions[0];
         $height = $dimensions[1];
      }
   }

   if (intval($form_values['ad_type']) <= 2) {
      $types = array('text', 'image', 'text/image');
      $type = $types[$form_values['ad_type']];
   }

   if ($width == 0 || $height == 0 || $type == '') {
      drupal_not_found();
   }
   else {
      db_query("
      INSERT INTO {gadsense_blocks}
         (width, height, type)
      VALUES
         (%d, %d, '%s')",
      $width, $height, $type);

      drupal_set_message('Ad block created');
      drupal_goto('admin/settings/gadsense/list');
   }
}



After splitting the ad size selection into $width and $height variables and grabbing the ad $type, we insert a new record into our gadsense_blocks table. As shown above, this will create give it a unique bid value, which we'll reference later.

I'll create a few different blocks, and now our main gadsense page will be populated. Like this:



Now, the last thing we need to do is implement the block hook for both the list and view operations.


function gadsense_block($op='list', $delta=0) {
   if ($op == "list") {
      $result = db_query('
   SELECT
      *
   FROM {gadsense_blocks}
   ORDER BY width + " x " + height ASC');

      $rows = array();
      while ($field = db_fetch_object($result)) {
         $block[$field->bid]["info"] = t('Google AdSense - '.$field->width.'x'.$field->height);
      }

      return $block;
   }
   else if ($op == 'view') {
      $result = db_fetch_object(db_query('
   SELECT
      *
   FROM {gadsense_blocks}
   WHERE bid = %d',
   $delta));

      if ($result->bid > 0) {
         $block['subject'] = 'Advertisement';
         $block['content'] =
   '
   <script>
   <!--
      google_ad_client = "'.variable_get('google_adsense_code', '').'";
      google_ad_width = "'.$result->width.'";
      google_ad_height = "'.$result->height.'";
      google_ad_format = "'.$result->width.'x'.$result->height.'_as";
      google_ad_type = "'.$result->type.'";
   //-->
   </script>
   <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
   </script>
   ';

    }

   if ($block)
     return $block;
   }
}



In the list operation, we select the gadsense blocks from out of the database and use them to populate the global block list. This is the "magic" behind our module.

Normally modules use hardcoded integers for indexes in the block hook, but as long as they are unique, Drupal couldn't care less what the index values actually are. Since we use the auto incrementing primary key column from our MySql database, we know the values will be unique.

Now, our /admin/block list will contain blocks that mirror our gadsense list:



The other operation we implement in our block hook is the view operation. This is what draws the block content - in our case, a Google AdSense ad.

The unique bid value that we used to index our block in the list operation is handed to us in the view operation. Then we just lookup the information about the ad's width, height and type and output the javascript that is required to call Google's script.

So, if we check the box to add the 468x60 ad block that we created, we'll see that it appears like this:




The Enhancements...

The finished version of the module that I created has numerous enhancements that you can easily add yourself, such as the ability to edit the block settings, delete a block, clone a block, change the AdSense tracking code, add an AdSense channel, etc.

Additionally, you can tie in to any setting that Google offers on the AdSense platform. Specifically, my module offers a color wheel to set the text color, border color, and other layout specific features.


The Google AdSense module is just one simple use for this concept. Dynamic blocks can be used in millions of situations such as allowing users to create their own blocks for display or share with their friends, index the blocks using the current date and show Holiday specific blocks, automatically import affiliate links and create dynamic blocks and many others. Once you start experimenting with it, I'm sure you'll come up with all sorts of unique ideas!





page 1 of 1
1 




Tags

Generics bitwise book review Microsoft Windows AnimeConPics Immutable String testing Regular Expressions anime JSP Google AdSense API shortcut internals Linux operator help Erlang Drupal Demand Media enhancements IIS Google query Microsoft job MSDN c sharp AdSense Adam anime convention parsing Mikomicon interface programming languages interview protocol Windows Generic Method RegEx injection tools languages driver string parsing Javascript Adrianne dynamic block HTTP Introduction