Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryGenerators and Converters

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Idea Generator, Part III

Note: More so than many at this website, this article assumes you are technically inclined and have a good bit of experience with HTML.

This is the last of the 3-part series for implementing functionality similar to Plot Ideas page for writers.

The software fills in each blank of a sentence with a pseudo-random selection from a list of replacements. The list of replacements can be specified by the person viewing the web page.

There are two blanks for the sentence with this idea generator. After it is implemented, upgrades can include changing the sentence and changing the number of blanks.

This is the longest of the 3 parts. You'll need to refer to the previous parts, Idea Generator, Part I and Idea Generator, Part II when implementing.

Let's get started.

Here is an example of the functionality.

The following sentence has two boxes of text from which replacements will be selected to complete the sentence. The boxes of text are editable. Change them to have other or more selections.

The
cow jumped
fox leaped
crow flew
ant crawled
over the
moon
campfire
radish plant
!

Here is the div that contains a generated idea.

For another generated idea, either click this link or .

Note: The generated idea will not always be different than the previously generated idea. The software does not remember what the previous idea was — it just goes ahead and generates one.

Implementing the Functionality

Some is nearly the same. Much has changed. The previous parts of this series will be referred to.

There is a good bit to do here. Buckle in and let's go.

IdeaGenerator.php

Let's upgrade the IdeaGenerator.php String-Replacement Content Generator PHP script first of all. Then it will be in place for your test page.

The version you installed during the first part of this series has had a number of changes interspersed throughout. The changes were for handling replacement lists from the web page rather than coded into the script.

The latest is now version 1.1 of June 6, 2021. Either replace version 1.0 entirely with version 1.1 or make a new version 1.1 installation.

Here is the source code. Customization notes follow.

<?php
/* String-Replacement Content Generator
   Version 1.1
   June 6, 2021
   (Upgrade to use on-page replacement suggestions.)
   Version 1.0, April 30, 2021
   Will Bontrager Software LLC
   https://www.willmaster.com/
*/


/*
There are two customizations. 
The first is a template for the content.
The second is default content when no replacement choices are provided.
*/

// Template for content.
$ContentTemplate = <<<END
The {REPLACEMENT1} over the {REPLACEMENT2}!
END;

// Default content to use when no replacement choices are provided.
$DefaultReplacement = '[blank]';

/* End of customizations */

// Accept and conform lists received.
$ReplacementLists = $th = array();
foreach( $_POST as $k => $v )
{
   $match = array();
   if( preg_match('/^list(\d+)$/',$k,$match) ) { $th[$match[1]] = ConformListFromWebsite($v); }
}
ksort($th,SORT_NUMERIC);
foreach( $th as $k => $v ) { $ReplacementLists[] = $v; }

// Select list items and replace placeholders in content.
$ListsLength = count($ReplacementLists);
$content = $ContentTemplate;
for( $i=0; $i<$ListsLength; $i++ )
{
   $replacement = SelectAnItem($ReplacementLists[$i]);
   $content = str_replace('{REPLACEMENT'.($i+1).'}',$replacement,$content);
}
$content = preg_replace('/\{REPLACEMENT\d+\}/',$DefaultReplacement,$content);

// Reply with the generated content.
echo $content;

function ConformListFromWebsite($s)
{
   global $DefaultReplacement;
   $s = preg_replace('/<[^>]*?>/s',"\n",$s);
   $s = preg_replace('/\&nbsp;/i',' ',$s);
   $retarray = array();
   foreach( preg_split('/[\r\n]+/',trim($s)) as $line )
   {
      if( preg_match('/\S/',$line) ) { $retarray[] = trim($line); }
   }
   if( ! count($retarray) ) { $retarray[] = $DefaultReplacement; }
   return $retarray;
}

function SelectAnItem($arr)
{
   $count = count($arr)-1;
   $itemIndice = mt_rand(0,$count);
   return $arr[$itemIndice];
}
?>

None of these customizations are required.

The $ContentTemplate value is the same as version 1.0:
The {REPLACEMENT1} over the {REPLACEMENT2}!
It may be modified.

A new customization is the default replacement when no replacement is otherwise available. For the value of the $DefaultReplacement variable, [blank] may be replaced.

When you upload the PHP script, make a note of its URL.

Next is the test web page. We'll install the Ajax first, then the functionality.

The Ajax

On the web page where the idea generator will be presented, install the JavaScript containing the Ajax engine.

This one is some different than the one presented in the second article of this series, which introduced the concept of getting new generated ideas with a click.

Here is the source code for the JavaScript. Customization notes follow.

<script type="text/javascript">
function GetAnotherGeneratedIdea()
{
   /* Customization section. */

   // Specify the relative URL of IdeaGenerator.php
   var url = "/ideas/IdeaGenerator.php";

   // Specify the id value of the div or other HTML container to publish the generated idea.
   var id = "generated-idea";

   // Specify the number of replacement lists to send to IdeaGenerator.php
   var number_of_lists = 2;

   /* End of customization. */
   var http = new XMLHttpRequest();
   if(! http) { alert("Unable to connect to the software."); return; }
   var params = new Array();
   for( var i=1; i<=number_of_lists; i++ )
   {
      params.push("list"+i+"="+encodeURIComponent(document.getElementById("replacement-list"+i).innerHTML));
   }
   http.onreadystatechange = function()
   { 
      if(http.readyState == 4 && http.status == 200)
      {
         document.getElementById(id).innerHTML = http.responseText;
      }
   }
   http.open("POST",url,true);
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.send(params.join("&"));
}
GetAnotherGeneratedIdea();
</script>

The above source code has three places to customize.

The first two customizations are described in Idea Generator, Part II and are identical to what you learned there. Replace /ideas/IdeaGenerator.php with the URL of the PHP script (described further above). The second is good as it is unless you change the HTML (described further below).

The third customization is new. It specifies how many replacement lists the page contains. Leave it at var number_of_lists = 2; for now. The number may be changed if you decide to add or remove replacement lists for your website's version.

Paste the JavaScript into the web page source code anywhere that JavaScript can run. Near the bottom, immediately above the cancel </body> tag is good.

The User Interface

The interface has three parts:

  1. The place where the replacement lists are provided.

  2. The div that contains the latest generated idea.

  3. The link and/or button to generate another idea.

The first part is new for this article. The last two are copied from Idea Generator, Part II.

Let's do the first part, the place where the replacement lists are provided:

Instead of using inline CSS repetitively, here is the style sheet for the selection sentence and the selection list boxes.

<style>
.selection-sentence { 
   display:inline-block; 
   vertical-align:top; 
   }
.selection-list { 
   border:1px solid #ccc; 
   padding:0 .5em .5em .5em; 
   }
</style>

Put those styles either in your CSS style sheet or separate on the web page where ideas will be generated.

Now, the sentence with the replacement lists. It represents the sentence that will be the generated idea. The replacements lists are positioned where a word or phrase will be selected for the sentence. (The example functionality further above presents the idea.)

Here is the HTML for that sentence. The replacement lists are populated.

<div class="selection-sentence">The</div> 

<div id="replacement-list1" class="selection-sentence selection-list" contenteditable="true">cow jumped<br>
fox leaped<br>
crow flew<br>
ant crawled</div> 

<div class="selection-sentence">over the</div> 

<div id="replacement-list2" class="selection-sentence selection-list" contenteditable="true">moon<br>
campfire<br>
radish plant</div> 

<div class="selection-sentence">!</div> 

The id values of the replacement lists need to be as specified. The first is replacement-list1 and the second is replacement-list2. If you add a third one, it will need to be replacement-list3 (and the Ajax var number_of_lists = 2; updated accordingly).

Paste the HTML into your web page. It, and the style, can then be modified as you please — except the id values of the replacement lists need to be as mentioned.

The div that contains the latest generated idea and the link and/or button to generate another idea are the same as presented in the Idea Generator, Part II article of this series.

For completion, that code is repeated here.

<div id="generated-idea" style="border:3px solid #ccc; padding:.25em 1em; border-radius:2em; text-align:center;"></div>

<p>
For another generated idea, either <a href="javascript:GetAnotherGeneratedIdea()">click this link</a> or <input type="button" value="tap this button" onclick="GetAnotherGeneratedIdea()">.
</p>

Once your test page is working, generating ideas as expected, you are in position to make changes so the functionality works on your website the way you want it to.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC