php-general Digest 19 Mar 2006 14:42:55 -0000 Issue 4024

Topics (messages 232195 through 232213):

Re: Updating a single line in a file
        232195 by: smr78
        232196 by: Manuel Amador (Rudd-O)
        232213 by: smr78

Re: PHP, SQL, AJAX, JS and populating a SelectBox?
        232197 by: tedd
        232201 by: Manuel Lemos
        232202 by: Daevid Vincent
        232203 by: tedd
        232205 by: Chrome
        232206 by: Greg Beaver
        232207 by: Manuel Amador (Rudd-O)
        232209 by: Greg Beaver

Re: no newline after "?>" in the resulting HTML
        232198 by: Rostislav Krasny
        232199 by: Jim Lucas
        232200 by: Rostislav Krasny
        232204 by: Rasmus Lerdorf

Merging two partially-transparent images results in black pixels
        232208 by: Jason Young

showing any mysql query in a table, help!
        232210 by: pgaio.portugalmail.pt
        232211 by: Chris
        232212 by: Jim Lucas

Administrivia:

To subscribe to the digest, e-mail:
        [EMAIL PROTECTED]

To unsubscribe from the digest, e-mail:
        [EMAIL PROTECTED]

To post to the list, e-mail:
        php-general@lists.php.net


----------------------------------------------------------------------
--- Begin Message ---
"Curt Zirzow" <[EMAIL PROTECTED]> a écrit dans le message de news: 
[EMAIL PROTECTED]
> On Sat, Mar 18, 2006 at 11:01:07AM +0100, smr78 wrote:
>> Hi,
>> What is the best method to update a single line in a text file?
>> I have a file made of identifiers, that is pointed on by a htaccess file 
>> and
>> used by a server to give access to a web site.
>> The file content is like this :
>> login1:pass1\r\n
>> login2:pass2\r\n
>> ....
>> loginn:passn\r\n
>> loginn1:passn1\r\n
>> ....
>> lastlogin:lastpass\r\n
>
> Why dont you use a database for this?  You will run into race
> conditions at some point.
>
> If you need a file based database take a look at sqlite.
>
> Curt.
> -- 
About the race conditions, I didn't mentionned I had some extras code to 
care about concurrent writing on the file
About database, I know that will be the best, but on this small site, I 
can't use full database!
Thank you for your answer
SR 

--- End Message ---
--- Begin Message ---
Replies inlined.

Why dont you use a database for this?  You will run into race
conditions at some point.

If you need a file based database take a look at sqlite.

Curt.
--
About the race conditions, I didn't mentionned I had some extras code to care about concurrent writing on the file About database, I know that will be the best, but on this small site, I can't use full database!
That's why they suggested a sqlite database, which uses a single file.

Thank you for your answer
SR

--- End Message ---
--- Begin Message ---
OK, I take a look on sqlite

Many thanks


""Manuel Amador (Rudd-O)"" <[EMAIL PROTECTED]> a écrit dans le message de 
news: [EMAIL PROTECTED]
> Replies inlined.
>
>>>Why dont you use a database for this?  You will run into race
>>>conditions at some point.
>>>
>>>If you need a file based database take a look at sqlite.
>>>
>>>Curt.
>>>-- 
>>>
>>About the race conditions, I didn't mentionned I had some extras code to 
>>care about concurrent writing on the file
>>About database, I know that will be the best, but on this small site, I 
>>can't use full database!
>>
> That's why they suggested a sqlite database, which uses a single file.
>
>>Thank you for your answer
>>SR
>> 

--- End Message ---
--- Begin Message ---
I need to dynamically update a select box
with results from a SQL database using AJAX,
but I can't find a single example of how to do this.

Basically I have a text input field, and a select box.
As someone types in the input field,
I want the select box to fill in the results of matches.

I can fill in a <DIV> (as per the ten million examples out there)
and that's all fine and dandy, but way too simplistic for what I need.

Select Box?

Do you mean a Selection List, that will change as the user types in an input field like this:

http://www.itsyourdomain.com/

Just type domain name into the search box -- is that what you're looking for?

tedd
--
--------------------------------------------------------------------------------
http://sperling.com

--- End Message ---
--- Begin Message ---
Hello,

on 03/17/2006 11:42 PM Daevid Vincent said the following:
> I need to dynamically update a select box 
> with results from a SQL database using AJAX, 
> but I can't find a single example of how to do this.
> 
> Basically I have a text input field, and a select box. 
> As someone types in the input field, 
> I want the select box to fill in the results of matches.
> 
> I can fill in a <DIV> (as per the ten million examples out there)
> and that's all fine and dandy, but way too simplistic for what I need.

You may want to take a look at this forms generation class that comes
with a plug-in that lets you do precisely what you ask.

The linked select input plug-in lets you switch the group of options of
a select input upon an arbitrary event, which in your case you need to
be when your text input changes its value.

The plug-in can work in two modes: static and dynamic. In the static
mode it loads all the alternative groups of options with the form. This
is not the way you want.

In the dynamic mode it makes an AJAX call that performs some action and
returns the alternative group of options depending on a value passed
from another input to the server.

In both modes it can take the alternative option groups from arrays or
execute some action that retrives the new options. There specialized
variants of the plug-in to take the options from database queries using
different API. Currently supported API are: MySQL, or any other database
supported by the database abstractions Metabase or PEAR::MDB2 .

There is also another plug-in for generic AJAX form submission in case
you need more special effects.

Here are live examples of the static mode:

http://www.phpclasses.org/mirrors.html

http://www.phpclasses.org/browse/view/html/file/9879/name/test_linked_select_page.html


The example scripts for the dynamic mode come with the class:

You may download the class and all plug-ins, examples and documentation
from here:

http://www.phpclasses.org/formsgeneration

-- 

Regards,
Manuel Lemos

Metastorage - Data object relational mapping layer generator
http://www.metastorage.net/

PHP Classes - Free ready to use OOP components written in PHP
http://www.phpclasses.org/

--- End Message ---
--- Begin Message ---
No. All of the examples I find are like the 'google' style suggest-thingy.

I want to dynamically (AJAX) populate an actual:

<select>
        <option value='1'> foo 
        <option value='2'> bar
        <option value='3'> fee
        <option value='4'> fum
</select> 

Basically the core problem is passing back an 'array' of data from mysql
into JS to make the box.

What I've 'hacked' together so far is that I return my values like so from
PHP/mySQL to JS AJAX:

$tmp = "1|foo|2|bar|3|fee|4|fum";

And then in JS, I do this:

tokens = tmp.split('|');

Then use a for(i++2) loop and build up the options (key and value) of the
select box.

But, to me this seems like a hack.

Plus I'm a little worried that there is going to be a size limit of
characters or data or something? After all, AFAIK AJAX uses $_GET method
right? Not $_POST. So I think GET has a limit of like 1024 characters,
whereas POST doesn't have that limit.

My select box could have potentially thousands of items in it. Say for
example, IP addresses. I have supporting select boxes to filter by ranges,
or groups, or whatever, but there's nothing restricting a user from NOT
using them, and just wanting to see ALL the IP addresses...

So, I guess what I'm asking, is, is this the right way to solve this
challenge, or is there a better/more accepted way?

> -----Original Message-----
> From: tedd [mailto:[EMAIL PROTECTED] 
> Sent: Saturday, March 18, 2006 1:02 PM
> To: php-general@lists.php.net; Daevid Vincent
> Subject: Re: [PHP] PHP, SQL, AJAX, JS and populating a SelectBox?
> 
> >I need to dynamically update a select box
> >with results from a SQL database using AJAX,
> >but I can't find a single example of how to do this.
> >
> >Basically I have a text input field, and a select box.
> >As someone types in the input field,
> >I want the select box to fill in the results of matches.
> >
> >I can fill in a <DIV> (as per the ten million examples out there)
> >and that's all fine and dandy, but way too simplistic for 
> what I need.
> 
> Select Box?
> 
> Do you mean a Selection List, that will change as the user types in 
> an input field like this:
> 
> http://www.itsyourdomain.com/
> 
> Just type domain name into the search box -- is that what 
> you're looking for?
> 
> tedd
> -- 
> --------------------------------------------------------------
> ------------------
> http://sperling.com
> 

--- End Message ---
--- Begin Message ---
No. All of the examples I find are like the 'google' style suggest-thingy.

I want to dynamically (AJAX) populate an actual:

<select>
        <option value='1'> foo
        <option value='2'> bar
        <option value='3'> fee
        <option value='4'> fum
</select>

Basically the core problem is passing back an 'array' of data from mysql
into JS to make the box.

What I've 'hacked' together so far is that I return my values like so from
PHP/mySQL to JS AJAX:

$tmp = "1|foo|2|bar|3|fee|4|fum";

And then in JS, I do this:

tokens = tmp.split('|');

Then use a for(i++2) loop and build up the options (key and value) of the
select box.

But, to me this seems like a hack.

Plus I'm a little worried that there is going to be a size limit of
characters or data or something? After all, AFAIK AJAX uses $_GET method
right? Not $_POST. So I think GET has a limit of like 1024 characters,
whereas POST doesn't have that limit.

My select box could have potentially thousands of items in it. Say for
example, IP addresses. I have supporting select boxes to filter by ranges,
or groups, or whatever, but there's nothing restricting a user from NOT
using them, and just wanting to see ALL the IP addresses...

So, I guess what I'm asking, is, is this the right way to solve this
challenge, or is there a better/more accepted way?

A better acceptable way? I'm clueless as to what is better. Ajax is too new to me to make a determination as to what is the best or acceptable way.

I just know that ajax can be used to replace the contents between specific tags in an html document without having to reload the entire page. So, I don't see any reason why you can't replace stuff between <select> tags with stuff you pull out from mysql.

As far as the limit, your assumption is not correct. I just tried a test of over 14,000 characters with no problem at all, see:

http://www.xn--ovg.com/ajax1  Click First page

So, you shouldn't have any problem populating a select box with thousands of characters -- although you may want to LIMIT that in your mysql and pull it out in shorter segments.

tedd

--
--------------------------------------------------------------------------------
http://sperling.com

--- End Message ---
--- Begin Message ---
Ajax can be made to use POST by adding

req.open("POST", url, true); // true creates an asynchronous connection
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

where req is the XHR object

Also why not use the same style of formatting for the response as the
request uses... eg:

foo=My Foo&bar=My Bar&wibble=My Wibble

The first value is the option value and the second is the option text

FWIW I think that using innerHTML is a bad idea as the elements created
aren't included in the DOM tree... creating the elements using the DOM is a
much better idea... It may be more lengthy by that can be cut down some with
clever scripting :)

HTH

Dan

-------------------
http://chrome.me.uk
 

-----Original Message-----
From: Daevid Vincent [mailto:[EMAIL PROTECTED] 
Sent: 18 March 2006 22:45
To: php-general@lists.php.net
Cc: 'tedd'
Subject: RE: [PHP] PHP, SQL, AJAX, JS and populating a SelectBox?

No. All of the examples I find are like the 'google' style suggest-thingy.

I want to dynamically (AJAX) populate an actual:

<select>
        <option value='1'> foo 
        <option value='2'> bar
        <option value='3'> fee
        <option value='4'> fum
</select> 

Basically the core problem is passing back an 'array' of data from mysql
into JS to make the box.

What I've 'hacked' together so far is that I return my values like so from
PHP/mySQL to JS AJAX:

$tmp = "1|foo|2|bar|3|fee|4|fum";

And then in JS, I do this:

tokens = tmp.split('|');

Then use a for(i++2) loop and build up the options (key and value) of the
select box.

But, to me this seems like a hack.

Plus I'm a little worried that there is going to be a size limit of
characters or data or something? After all, AFAIK AJAX uses $_GET method
right? Not $_POST. So I think GET has a limit of like 1024 characters,
whereas POST doesn't have that limit.

My select box could have potentially thousands of items in it. Say for
example, IP addresses. I have supporting select boxes to filter by ranges,
or groups, or whatever, but there's nothing restricting a user from NOT
using them, and just wanting to see ALL the IP addresses...

So, I guess what I'm asking, is, is this the right way to solve this
challenge, or is there a better/more accepted way?

> -----Original Message-----
> From: tedd [mailto:[EMAIL PROTECTED] 
> Sent: Saturday, March 18, 2006 1:02 PM
> To: php-general@lists.php.net; Daevid Vincent
> Subject: Re: [PHP] PHP, SQL, AJAX, JS and populating a SelectBox?
> 
> >I need to dynamically update a select box
> >with results from a SQL database using AJAX,
> >but I can't find a single example of how to do this.
> >
> >Basically I have a text input field, and a select box.
> >As someone types in the input field,
> >I want the select box to fill in the results of matches.
> >
> >I can fill in a <DIV> (as per the ten million examples out there)
> >and that's all fine and dandy, but way too simplistic for 
> what I need.
> 
> Select Box?
> 
> Do you mean a Selection List, that will change as the user types in 
> an input field like this:
> 
> http://www.itsyourdomain.com/
> 
> Just type domain name into the search box -- is that what 
> you're looking for?
> 
> tedd
> -- 
> --------------------------------------------------------------
> ------------------
> http://sperling.com
> 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


__________ NOD32 1.1450 (20060318) Information __________

This message was checked by NOD32 antivirus system.
http://www.eset.com

--- End Message ---
--- Begin Message ---
Manuel Amador (Rudd-O) wrote:

>
>> 1) what if the returned markup is invalid?
>>
>> Well, the browser renders it oddly, and through the fact that your
>> server-side code is straightforward filling in an html template with
>> actual values, all you need to do is view the source (with the firefox
>> web debugging extension you can view generated source) or to add an
>> "alert(res)" in there.
>>  
>>
> Now, how do you automate that in a testing suite?

This is obvious: you need only test the output of the PHP server class,
which is quite simple, as none of the complexity lies in the
javascript.  As long as your ajax javascript is testable for its ability
to work (and HTML_AJAX is), then you are covered.  In other words, the
need to test the javascript end is simply unnecessary.  All you need to
do is to test that the javascript actually properly initiates the ajax
call.  In my case, it involves these lines:

var someCallback = {
    doThis: function(res) {
       document.getElementById('blah').innerHTML = res;
    }
}

function doThisThing(fragment)
{
    var c = new backendclass(someCallback);
    c.doThis(fragment);
}

Obviously, this is simply not complicated enough to warrant extensive
testing of the interface between the javascript -> HTML_AJAX -> php code
and back.  All we need to test is the HTML_AJAX component, and the PHP code.

>   Going beyond, how do you set up unit (or other types of) tests in a
> cheap, straightforward way?  How do you assure quality of an
> application built like this?

In order to unit test the javascript, you would need to do the same
stuff that is done for DOM, but it would be far simpler to set up.  I've
already answered the PHP end.

>
>> 3) tag soup?
>>
>> I hardly think a <select> tag qualifies as "tag soup" but "tag soup" is
>> of course a non-definite term anyways :).
>>  
>>
> Well, returning an JSON or XML document certainly is more structured
> than using a simple SELECT and several OPTION HTML tags.  The point
> here is, precisely, decoupling implementation from interface.

What I think is *still* unclear is that the difference between what you
are suggesting and what is actually working on my website is this:

Your solution:

1) PHP code generates the data from the fragment
2) PHP code converts the data into a text file
3) PHP code serializes it to JSON
4) javascript code unserializes the JSON
5) javascript code parses the text file to grab option/value combinations
6) javascript code creates each option node, and adds the value/text
7) javascript code creates the select node, adds each option
8) javascript code adds the select to the document

My solution:

1) PHP code generates the data from the fragment
2) PHP code converts the data into a string containing the
<select><option> tags
3) PHP code serializes it to JSON
4) javascript code unserializes the JSON
5) javascript code sets the innerHTML to the new select

In your solution, you need to test steps 1, 2, 5, 6 and 7.  In addition,
steps 2, 5, 6, and 7 all require testing in javascript (and time) to
guarantee that you get the result (8).

In my solution, you need to test step 1 and 2 to ensure that bounds are
satisfied and that a proper <select> tag is always generated, and this
only needs to be done in PHP.  Both cases assume you don't need to test
the ajax mechanism itself.

In short, it's just not worth the trouble to triple the number of
necessary tests when the result is identical, and it is actually
*easier* to see what HTML you're going to end up with from the PHP code.

> Sure, your solution mostly works.  But what I still wonder is, is it
> the best solution in terms of software quality? 

I think I've made my opinion sufficiently clear on this point.

Greg

--- End Message ---
--- Begin Message ---
Greg Beaver wrote:


This is obvious: you need only test the output of the PHP server class,
All the more reasons to use a serialization markup language instead of just plain HTML. Testing for specific HTML output may break if the HTML output changes, but not if you're using XML or JSON, because:

1. you are forced to think carefully before changing the output
2. programming techniques such as DOM instead of matching for text are a reality

which is quite simple, as none of the complexity lies in the
javascript.  As long as your ajax javascript is testable for its ability
to work (and HTML_AJAX is), then you are covered.  In other words, the
need to test the javascript end is simply unnecessary.

That's so untrue, unit testing frameworks for JavaScript exist.

 All you need to
do is to test that the javascript actually properly initiates the ajax
call.  In my case, it involves these lines:

var someCallback = {
   doThis: function(res) {
      document.getElementById('blah').innerHTML = res;
   }
}

function doThisThing(fragment)
{
   var c = new backendclass(someCallback);
   c.doThis(fragment);
}

 Going beyond, how do you set up unit (or other types of) tests in a
cheap, straightforward way?  How do you assure quality of an
application built like this?

In order to unit test the javascript, you would need to do the same
stuff that is done for DOM, but it would be far simpler to set up.  I've
already answered the PHP end.
What I think is *still* unclear is that the difference between what you
are suggesting and what is actually working on my website is this:

Your solution:

1) PHP code generates the data from the fragment
2) PHP code converts the data into a text file
3) PHP code serializes it to JSON
4) javascript code unserializes the JSON
5) javascript code parses the text file to grab option/value combinations
6) javascript code creates each option node, and adds the value/text
7) javascript code creates the select node, adds each option
8) javascript code adds the select to the document
It's evident, from your statements, that you've misunderstood me:

1) You output XML or JSON directly from your PHP script. Whether it's via print statements or an elaborated class like the DOM XML functions in PHP, that's your problem. 2) You receive the data and use one of the builtin JavaScript functions to parse it (if you're transferring a valid XML document, that's a piece of cake. Generating a valid XML document is also piece of cake, using DOM-XML in php) 3) You write client-side application code that processes the nodes from the parsed output and does whatever it has to do to your current document's DOM tree. See, it's much more generic. You could use the same output from the server to generate a table, or a SELECT node. Besides, if you want to avoid writing code, libraries for doing this are a dime a dozen. Plus if you reuse code you usually end up with a well-tested choice.

My solution:

1) PHP code generates the data from the fragment
2) PHP code converts the data into a string containing the
<select><option> tags
3) PHP code serializes it to JSON
4) javascript code unserializes the JSON
5) javascript code sets the innerHTML to the new select
Like I said, that's a very specific, non-generalizable, brittle solution. It might work. Then again, it might not. Handling broken connections and other kinds of impromptu errors is much harder than with XML or JSON. At least with XML, you can attest to the validity of the markup before embarking on an innerHTML binge.

In your solution, you need to test steps 1, 2, 5, 6 and 7.  In addition,
steps 2, 5, 6, and 7 all require testing in javascript (and time) to
guarantee that you get the result (8).

In my solution, you need to test step 1 and 2 to ensure that bounds are
satisfied and that a proper <select> tag is always generated, and this
only needs to be done in PHP.  Both cases assume you don't need to test
the ajax mechanism itself.
In short, it's just not worth the trouble to triple the number of
necessary tests when the result is identical, and it is actually
*easier* to see what HTML you're going to end up with from the PHP code.
Just for argument's sake: the result is not identical. Assume, for one second, that you have two PHP functions:

function getCitiesAsHTML($countryName);
function getCitiesAsXML($countryName);

The first issues a snippet of HTML text, with <option>s. The second issues a serialized XML document. The first one is engineered to be used with innerHTML. The second one is engineered to be processed by the client so it can do any generic transformation.

Which one do you think has the greatest potential for reusability in your JS client code? Option 1 or Option 2?

--------------------

Okay, this is the end of the discussion for me. You're stating a bunch of crap which does not correlate with modern accepted software quality practices. You're conveniently ignoring that server-side errors and TCP connection errors are out there, and while they may be only 2% of all traffic, you need your JS application to work 100% of the time or give reasonable feedback as to why it cannot work. You're grossly oversimplifying matters to prove your point, which flies right in the face of orderly, neat, structured, standards-based software development.

Sure, your solution mostly works.  But what I still wonder is, is it
the best solution in terms of software quality?

I think I've made my opinion sufficiently clear on this point.
Indeed.

Greg


--- End Message ---
--- Begin Message ---
Manuel Amador (Rudd-O) wrote:

> Just for argument's sake: the result is not identical.  Assume, for
> one second, that you have two PHP functions:
>
> function getCitiesAsHTML($countryName);
> function getCitiesAsXML($countryName);
>
> The first issues a snippet of HTML text, with <option>s.  The second
> issues a serialized XML document.
> The first one is engineered to be used with innerHTML.  The second one
> is engineered to be processed by the client so it can do any generic
> transformation.
>
> Which one do you think has the greatest potential for reusability in
> your JS client code?  Option 1 or Option 2?
>
> --------------------
>
> Okay, this is the end of the discussion for me.  You're stating a
> bunch of crap which does not correlate with modern accepted software
> quality practices.  You're conveniently ignoring that server-side
> errors and TCP connection errors are out there, and while they may be
> only 2% of all traffic, you need your JS application to work 100% of
> the time or give reasonable feedback as to why it cannot work.  You're
> grossly oversimplifying matters to prove your point, which flies right
> in the face of orderly, neat, structured, standards-based software
> development.

Manuel,

Your insults are not exactly convincing arguments for your case :).  If
you had even taken 1 second to investigate http://pear.php.net/HTML_AJAX
you would know that your arguments about TCP and server-side errors are
irrelevant.  Why?  I'll tell you why!

In fact, to make things easier, I will quote myself from previous
messages.  Consider this current email to be Message #4.  From Message #2:

"2) HTTP 500?

This should be handled internally by the ajax mechanism (HTML_AJAX does
handle this)"

To rephrase what I said above, HTML_AJAX handles server-side and TCP
connection errors.  I neglected to say exactly how it does so in the
message, perhaps that is the confusion.  Upon a timeout or other error,
a javascript alert() is used.  Upon a server-side error (a PHP error in
the server-side script), by default a javascript alert() is raised with
the contents of the PHP error complete with backtrace - very handy for
debugging.

So, that kills straw man argument number one, which I will quote again
for clarity: "You're conveniently ignoring that server-side errors and
TCP connection errors are out there, and while they may be only 2% of
all traffic..."

As we can see, this statement is untrue.  So, moving on:

HTML_AJAX is designed such that you register classes that simply return
regular old PHP values, and it then serializes them into JSON or any of
a number of choices (as I have said, let me quote myself from Message #1:

"I use http://pear.php.net/HTML_AJAX for the actual ajax details, and it
has several serialization options, JSON by default.")

The fact is, your example php functions miss the point by returning HTML
vs. XML.  The return value of my functions are *strings* which are then
serialized into JSON by HTML_AJAX.  If you need to do client-side
transformation, that's not a problem, as contrary to a previous post,
HTML inserted via assignment to innerHTML *is* accessible via DOM,
otherwise getElementById() wouldn't work on the <select>.  To prove
this, you can look in Firefox's DOM inspector.  After loading HTML
inserted via innerHTML, at first it will not show any changes, but by
closing the DOM inspector and re-opening it, it will refresh with the
current page value, and all of the new innerHTMLed HTML will show up.

Also, let's remember back to the original question from Daevid Vincent,
which was (and I quote):

"I need to dynamically update a select box with results from a SQL
database using AJAX, but I can't find a single example of how to do this."

A select box is not a need to do client-side manipulation.  It is a
select box.  Should you need to re-format the data in another format,
there are several options which all boil down to one of:

1) re-factor so that you don't need to re-format on the client side (my
personal favorite)
2) return another format such as an array and manipulate the data on the
client-side

However, it is not useful to talk about some generic time down the road
- what is important is to design your application so that it is easy to
change it.  If you have a whole bunch of complicated client-side logic,
this makes it more difficult to re-factor.  After all, only one of two
things are certain in programming:

You *will* have to refactor that code in the future, or you will quit. 
Whichever comes first.

So, straw man argument #2: "You're grossly oversimplifying matters to
prove your point, which flies right in the face of orderly, neat,
structured, standards-based software development."

is simply insulting :).  I was posting *actual* javascript code from a
well-working application with only the function names changed.  Want the
original code as written?  Here you go:

var addressesCallback = {
    searchAddressesGetHTMLOptions: function(res) {
       document.getElementById('existingaddresses').innerHTML = res;
    }
};

function searchAddresses(text, id)
{
    if (text.length < 3) {
       return;
    }
    var c = new addresses(addressesCallback);
    c.searchAddressesGetHTMLOptions(text, id);
}

and the PHP code that does this (this one is trimmed because it's got
lots of $adrinfo stuff to make the actual addresses and other database
junk):

<?php
require_once 'HTML/AJAX/Server.php';
class addresses
{
    function searchAddressesGetHTMLOptions($fragment, $id)
    {
       // first, do a query using LIKE to grab addresses from the
$fragment which I trimmed
       $options = '';
       // you may want to use a db-independent tool like PDO, but I know
for a fact
       // that this site will never use anything other than mysql for
speed reasons
       while ($adrinfo = mysqli_fetch_assoc($res)) {
          $address = $adrinfo['Line1'] //etc;
          $options .= ' <option value="' . $adrinfo['AddressID'] . '">'
. htmlspecialchars($address) . '</option>';
       }
       return '<select id="addressesdropdown" size="5">' .
          $options . '</select>';
    }
}

class ChiaraServer extends HTML_AJAX_Server
{
    function initAddresses()
    {
       $this->registerClass(new addresses());
    }
}
$server = new ChiaraServer;
$server->handleRequest();
?>

It is worth noting that I also added the central HTML_AJAX_Server code,
which is in a separate file.  There are many "init*" methods in the
actual code, each of which allows on-demand initialization of classes
for faster startup but that is also irrelevant to the task at hand.

You might note that the actual code that creates the <select> is 3 lines
long, 1 for address formatting, 1 for option creation, and 1 for the
actual select tag.  This in turn is serialized into JSON by
HTML_AJAX_Server and then deserialized into a String object which is
passed (res) to the callback searchAddressesGetHTMLOptions, which in
turn sets the innerHTML of the <div> that should contain the <select>.

You may be wondering how to unit-test this code.  For the javascript
unit testing, there are several options, including Selenium at
http://openqa.org/selenium-ide/.  HTML_AJAX has its own custom unit
tests built in using a mock object for the XMLHttpRequest object, you
could examine that to see how it handles TCP errors and PHP server-side
errors, among other things.

Unit-testing the PHP code would involve instantiating an address object,
and passing input to searchAddressesGetHTMLOptions, and comparing the
string output.  This can be done easily with PHPUnit2, SimpleTest, .phpt
testing, or any number of options (Chris might jump in here to mention
ApacheTest ;).

My point?  This is a real-world example of how to solve the problem of
generating a select using AJAX that is fast, easy to maintain, and easy
to modify.  It's not about complexity vs. simplicity or modern accepted
software quality practices vs. a bunch of crap.  It's about good
programming.

I know complexity, I wrote phpDocumentor 1.3 (http://www.phpdoc.org) and
PEAR 1.4 (http://pear.php.net/PEAR).  I also know how difficult it is to
manage complexity effectively, and PHP/javascript is a fantastic tool
for solving your problems, but only if you don't shoot yourself in the
foot before you even begin.

Greg

--- End Message ---
--- Begin Message ---
On Sat, 18 Mar 2006 19:37:48 +0000
[EMAIL PROTECTED] (James Benson) wrote:

> I get the same results, I doubt it's a bug, the person who wrote the 
> article maybe never tried what it would output since they probably know 
> how the echo construct works,

I think it is a bug. That part of the article could been written with
very old version of PHP. By the way, ASP does not delete a newline
after its "%>".

--- End Message ---
--- Begin Message ---
Rostislav Krasny wrote:
Hi,

I've tried to ask the following question on internals@lists.php.net but
has been pointed out that that mailing list isn't appropriate. So I'm
resinding it here.

I am a newbie to PHP. I've installed a php5-cgi-5.1.2_1 from FreeBSD
ports collection and access it by FastCGI protocol from nginx HTTP
server. I've tried an example of "Hello World" PHP script from the
following tutorial page:

http://www.php.net/manual/en/tutorial.firstpage.php

This is how the resulting HTML code is expected to look like, according
to the tutorial:

<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

And following is the HTML code I've got:

<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p></body>
</html>

Why there is no newline afer " <p>Hello World</p>" ?
Is it a PHP bug or the tutorial should be updated?

P.S. I'm not subscribed to this list, please Cc your reply.

put a space after the ?> and you will retain the line feed

jim

--- End Message ---
--- Begin Message ---
On Sat, 18 Mar 2006 13:49:19 -0800
[EMAIL PROTECTED] (Jim Lucas) wrote:

> put a space after the ?> and you will retain the line feed

It also adds that space before the retained line feed, but so it looks
better anyway. Excellent suggestion, thank you! Could it be added to
the FAQ and to the official PHP tutorial? At least to the discussed
part of the tutorial, so PHP beginners like me wouldn't be confused :-)

--- End Message ---
--- Begin Message ---
Rostislav Krasny wrote:
On Sat, 18 Mar 2006 13:49:19 -0800
[EMAIL PROTECTED] (Jim Lucas) wrote:

put a space after the ?> and you will retain the line feed

It also adds that space before the retained line feed, but so it looks
better anyway. Excellent suggestion, thank you! Could it be added to
the FAQ and to the official PHP tutorial? At least to the discussed
part of the tutorial, so PHP beginners like me wouldn't be confused :-)

I added it to the tutorial. It will show up the next time the manual is built.

-Rasmus

--- End Message ---
--- Begin Message ---
Hello,

I have an image that uses partial transparency for borders and such.
At first, I tried using the whole image; creating a truecolor 'holder' image, then imagecopymerge-ing it, but that resulted in the outside transparent areas (the ones that would instead show the 'holder' image) were black, while the portions of transparency on the inside (these are rounded-squares) that had actual other images below them were white.

Then, I made two images. One having the outside transparency, and setting imagesavealpha to make it work as intended... then adding the needed images, then adding the 'window'-type transparent image on top. This gives the best result, but the 'window' image also has partial transparency, and is instead showing in black.

I'm pretty much at wit's end. Everything's imagecopymerge'd, I've tried just about everything I could think of.

Can you actually not have two transparent images on top of one another?
Is there something else I can try?
And as an offshoot question, why won't any transparent images natively load/import as transparent? I always seem to have to call imagecolortransparent on portions that are definitely transparent in Photoshop, etc.

Any help would be much appreciated!
Thank you

-Jason Young

--- End Message ---
--- Begin Message ---
Ok...
it has to be a way to do such a thing.
I do i get the column names?
I can get the number of columns using mysql_num_fields() right?
but what if i want to get the columns name? Wich functtion and how should i use?

the goal is to make a function that prints a table that prints the result of 
any query in a html table.

thx
Pedro

--- End Message ---
--- Begin Message --- You could fetch the rows in an associate array. Then loop over each element in the array printing it out inside <td></td> tags..

print out <tr> before the columns, </tr> after.

To get the header just loop through the keys of the associative array. Whenever you want to show the header.

Unless I'm misunderstanding you that should work.

Chris

[EMAIL PROTECTED] wrote:
Ok...
it has to be a way to do such a thing.
I do i get the column names?
I can get the number of columns using mysql_num_fields() right?
but what if i want to get the columns name? Wich functtion and how should i use?

the goal is to make a function that prints a table that prints the result of 
any query in a html table.

thx
Pedro


--- End Message ---
--- Begin Message ---
[EMAIL PROTECTED] wrote:
Ok...
it has to be a way to do such a thing.
I do i get the column names?
I can get the number of columns using mysql_num_fields() right?
but what if i want to get the columns name? Wich functtion and how should i use?

the goal is to make a function that prints a table that prints the result of 
any query in a html table.

thx
Pedro

mysql_list_fields() should do the trick for you.

check out the function in the php documentation

the first couple examples in the user notes area should give you some good alternatives if this function does not work for you.

Jim

--- End Message ---

Reply via email to