Jump to content
Larry Ullman's Book Forums

David

Members
  • Posts

    20
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by David

  1. Modified the recursive function on page 19 to return divs instead of an ordered list.

     

    Function:

        function make_list($parent, $sub=FALSE) {
            
            // set attribute
            if (!$sub) {
            
                $attribute = 'id="menu"';
    
            } else {
            
                $attribute = 'class="submenu"';
            }
            
            // set tasks access
            global $tasks;
           
     
            foreach ($parent as $task_id => $todo) {
           
                // new loop?
                if (!$sub) { echo '<div id="main">'; }
                
                // build div
                echo '<div ' . $attribute . '>' . $todo . '</div>';
         
                // check for next array
                if (isset($tasks[$task_id])) {
                    
                    // call function again
                    make_list($tasks[$task_id], TRUE);
                
                } else {
                
                    // close 'main' div
                    echo '</div>';
                
                }
            }
        }

    Output:

    <div id="main">
        <div id="menu">Task 1</div>
        <div class="submenu">Subtask 1</div>
        <div class="submenu">SubSubTask 1</div>
    </div>
    <div id="main">
        <div id="menu">Task 2</div>
        <div class="submenu">Subtask 2</div>
        <div class="submenu">SubSubTask 2</div>
    </div>
    <div id="main">
        <div id="menu">Task 3</div>
        <div class="submenu">Subtask 3</div>
    </div>
    <div id="main">
        <div id="menu">Task 4</div>
        <div class="submenu">Subtask 4</div>
    </div>

    The problem is:

     

    Both the SubTask and SubSubTask divs have the same class of 'submenu'.

        <div class="submenu">Subtask 1</div>
        <div class="submenu">SubSubTask 1</div>

    I'm trying to get them to have different class names, like so:

        <div class="submenu">Subtask 1</div>
        <div class="subsubmenu">SubSubTask 1</div>

    How might I structure the function to accomplish this?

     

    Any ideas would be helpful.

     

     

     ~ David

  2. There's no Bellyache section on the forum (or if there is, I'm blind), so the alternative is putting it right here in public eye. My apologies.

     

    I'm confused on the benefit of using HTML_QuickForms2 in terms of actual learning value.

     

    Yes, it's a class, much like the built-in PHP classes already being used, and I accept the benefit of having it handle the heavy lifting for forms (validation, etc), but from a learning perspective, it would seem that actually working through the process 'by-hand' might deliver substantially more 'rubber-meets-the-road' value.

     

    It's one of the rare disappointments I've come across in the many LearnFromLarry books I own.

     

    In any case, it is what it is.

     

    Still much good information in the book, despite the (apparent) shortcoming.

     

     

    ---

  3. Suggestion (1): alert the data variable to the screen right before the ajax.send method call . . .

    Suggestion (2): Try reducing your foo.php script down to literally a single echo statement like the following:

    echo 'Just testing if this string is returned.';

    Suggestion (3): alert the Ajax response text right after the "if ( (ajax.status >= 200 ..." line . . .

     

     

    The result of implementing Suggestion (1) is:

     

    mysite/foo.php?comments=test%20string&user=1

     

    The string looks to be constructed as one should expect.

     

    =====================================================

     

    The result of implementing Suggestion (2) is:

     

    "Just testing if this string is returned."

     

    The php page looks to return the expected value.

     

    =====================================================

     

    Alerting the ready.State variable produces the following sequence:

     

    ready.State is: 1

    ready.State is: 2

    ready.State is: 4

     

    =====================================================

     

    And *here* is the interesting part:

     

    "ajax.status is: 0"

     

    For some reason ajax.status does not move beyond goose-egg.

     

    Back to the drawing board (or in this case, keyboard).

     

     

     

     ~ David

  4. Could you please post the surrounding code, including how a value is assigned to the data variable?

     

     

    When you say "post . . . how a value is assigned to the data variable", do you mean this?

    function sendThingy() {
    	
    	'use strict';
        
        // Get form elements:
        var comments = document.getElementById('comments');
        var user = document.getElementById('user');
    	
    	if (comments.value.length > 0) {
    	
    		var ajax = getXMLHttpRequestObject();
    
    		ajax.onreadystatechange = function() {
    
    			if (ajax.readyState == 4) {
    	
    				if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) {
    
    					document.getElementById('chat').innerHTML = ajax.responseText;
    
    				} else {
    		
    					document.getElementById('chat').innerHTML = 'Error: ' + ajax.statusText;
    				}
    			}
    		};
    		
    		ajax.open('POST', 'http://www.example.com/foo.php', true);
    		
    		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    		
    		var data = 'comments=' + encodeURIComponent(comments.value) + '&user=' + encodeURIComponent(user.value);
    		
    		ajax.send(data);
    		
    		return false;
    	
    	} else {
    	
    		alert('You forgot to enter a comment');
    		
    		return false;
    	}
    }
    

     ~ David

  5. Have a situation where - when submitting form data to a php script - the ajax script stalls at:

    ajax.send(data);
    

    When the script stalls, it throws no error messages and returns no results. It just stalls. The php script runs all of its scripty things perfectly sans ajax, so I know the php and mysql is solid. It's just when it comes to incorporating the ajax that there is any issue.

     

    But wait - there's more.

     

    When the script is under the influence of ajax, and stalls, the Firebug console displays this line of text in red (red obviously indicating some kind of error, even though there's no error message given):

     

    "POST mysite/foo.php               script.js (line 60)"

     

    The reference to (line 60) is the very line where the aforementioned ajax.send call resides.

     

    Now, here's where things get really screwy:

     

    If I go into Firebug, right-click on that red console line (shown above) and select 'resend' - everything works perfectly.

     

    What the . . .heck?

     

    Is there something obvious happening here that everyone (besides me) knows, or should I post some of the code for further scrutiny?

     

     ~ David

  6. Perhaps if you could explain what you mean . . . in terms of actual code and/or errors.

     

    No error is shown, instead, the php code merely stops executing.

     

    The query itself runs just fine on the database. I can put real, live zero's in their respective columns

    until the hens come home, so the query is proven sound. In addition, any number between 1 and 5

    works just fine when run through the php script.

     

    However, when a 'zero' gets selected in the drop-down and runs through the php script, it (the script)

    wonks out right at the point where it should be sending the query. The 'else' error displays instead.

    Seems the script won't recognize 'zero' as an integer, even though it's been specifically cast as one.

     

    I try to avoid cluttering the place up with buckets of code, but if it helps clarify, here's an abbreviated set:

     

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    	if (isset($_POST['amount'])) {
    
    		$a = $_POST['amount'];
    
    		$b = (integer)$a;
    
    	} else {
    
    		$b = false;
    	}
    
    	if ($ {
    
    		$query = "Make me handsome and rich!";
    
    	} else {
    
    		echo '<p>Oops, not this time, Sorry!</p>';
    
    	}
    
    } // end main submit
    
    // main page
    
    $number = range(0,5);
    
    echo '<select name="amount">';
    
    foreach ($number as $key => $value) {
       echo  '<option value="' . $key . '">' . $value . '</option>';
    }
    
    echo '</select>';
    

     

     

    That being said, there's no reason why you should send the amount through mysqli_real_escape_string() at all.

     

    Good point. My 'copy and paste' habits betray me here.

     

     

     ~ David

  7. Have a select situated like so:

     

    $number = range(0,5);
    
    <select name="amount">
    
    foreach ($number as $key => $value) {
       echo  '<option value="' . $key . '">' . $value . '</option>';
    }
    
    </select>
    

     

    The handling script contains:

     

    if (!empty($_POST['amount'])) {
    
    	$a = mysqli_real_escape_string($dbc, $_POST['amount']);
    
    	$b = (integer)$a;
    
    } else {
    
    	$b = false;
    }
    

     

    It works swimmingly enough, until a '0' $key-value buggers the handling script.

     

    The script swears on a stack of manuals it's being fed something other than the integer 'zero'.

     

    How does one get '0' (zero) to be - and stay as- the *number* zero, and not a NULL or FALSE, etc.

     

     

     ~ David

  8. One method for passing attractive variables between scripts is to append them to an URL like so:

    <a href="edit.php?x=1">edit</a>
    

    The issue being that "x=1", while provocatively visible in the URL, is easily coerced to become "x=99",

    or some other arbitrary value of dark intent and high suspicion.

     

    Is it merely that I have yet to find the session-based solution for this in the book?

     

    Obvious session assignments, i.e., registering a user name as a session variable, are straightforward.

     

    But the example listed above seems to present a different sort of challenge.

     

     ~ David

  9. Hello there!

     

    The thread referenced (at the bottom) covers how to display two forms on a single page.

     

    However . . .

     

    In the case referenced, both forms are visible on the page by default, and it is only *after* a submit has been detected that the script detects the form sent, and calls the appropriate code.

     

    It seems possible to display only one of the forms based on a user's site visit status.

     

    For example, assume a page contains code for both 'Form A' and 'Form B'.

     

    What I'm looking for is:

     

    1) When the user visits the page for the first time, 'Form A' is displayed by default, then;

     

    2) On any subsequent visit to the page by the same user, during the same session, 'Form B' is displayed by default.

     

    Of course, the submit still gets handled by the processing script, but that's already been covered in the thread referenced.

     

    What's got me snookered is how to determe the visitors status (i.e., new or return visit) so that the appropriate form can be displayed.

     

     ~ David

     

    Reference:

    http://www.larryullman.com/forums/index.php?/topic/1362-two-forms-on-one-page/

  10. Attempted to generate a tooltip from code listed on pages 384 and 385.

     

    HTML was looking like this:

     

    <div>
    <label for="username">Username<span class="tooltip">Some snappy tooltip here</span></label>
    <input type="text" name="username" id="username"/>
    </div>
    

     

    Tested page. No tooltip.

     

    Instead, the console.log shows:

     

    TypeError: target.previousSibling.lastChild is null
    "target.previousSibling.lastChild.style.visibility = 'visible';"
    

     

    Tested the download files. Tooltip works.

     

    My code is exactly like the download files, and won't make a tooltip.

     

    So, after ((timeSpent >= 1 hour) && (currentHair < previousHair)), I remove the hard return after </label> on a whim . . . and Viola! - tooltip appears!

     

    Now the HTML code looks like this:

     

    <div>
    <label for="username">Username<span class="tooltip">Tooltip</span></label><input type="text" name="username" id="username"/>
    </div>
    

     

    Apparently adding hard returns (formating page for easier reading) introduces a new DOM node that prevents 'previousSibling' in the javascript function from reaching all the way back to <label>.

     

    So then, no hard returns if you expect to go tripping through the DOM.

     

    Hope this helps save some hair.

     

    ~ David

     

    Win 7 Home Premium

    Firefox 17.0

  11. When I test the form . . .without filling (it) in I get “Error!”

    If I fill (it incorrectly) I still get "Error!” message with no notification of what I have done wrong.

    If I complete the form correctly . . . I just get a blank page with the header and footer displayed.

    I downloaded the completed lesson from the website and tested (it . . . and it) behaves in exactly the same way . . .

    (All the other forms I've created) work fine.

     

    Odd that:

    1) Other forms work, but not this one. Presuming this form uses the same database script as the other.

    2) Although error messages are assigned, you only see “Error!” - and not corresponding error message.

     

    And most odd of all is:

    3) You downloaded the completed lesson and tested the form (and it) behaves in exactly the same way...

     

    I didn't see anything wrong, but that don't mean it aint there.

     

    Commenting everything out - and testing one element at a time until it works correctly - usually helps me track down, club* and remove the funky monkey screwing with my code.

     

    *(no monkeys are harmed when I fix code.)

     

    ~ David

    • Upvote 1
  12. Just a couple of ideas:

     

    Thank you.

     

    Ideas will help get me going in the right direction - or at least any direction, at this point..

     

     

    - Have the actual book contents in separate PDF files, and then manage those as files with metadata about the files in the DB.

     

    This would definitely get the job done in short order.

     

    You could not have known - however - that I had neglected to mention that the reader will need to be able to perform a search and see every hit returned with a link attached that - when clicked - takes them to the part of the book (or, displays the 'page') where the search term(s) are/is located.

     

     

    - Use one of the TEXT or BLOB datatypes (i.e., TEXT, MEDIUMTEXT, LARGETEXT, BLOB, MEDIUMBLOB, etc.). The TEXT and BLOB datatypes are capable of storing massive amounts of data. In addition, while it may appear so in the DB interface, the data is not actually stored in the DB, but in separate text files to which pointers are stored in the DB.

     

    Interesting. Very interesting. And, this method would concievably allow for a search function to perform as required.

     

    Again, thank you for the insight.

     

    ~ David

  13. A database design example commonly available pressumes that one wants to organize a collection of books, and depicts the usual author, title, isbn, etc., breakdown, and may even normalize to several tables.

     

    Generally not seen, however, is an example that includes the books contents, i.e., chapters, headings, footnotes, and body copy

     

    Any thoughs on why this is?

     

    Would MYSQL even be capable of managing the task?

     

     

    ~ David

  14. By the way, why did you set first to the node.value, but last to just the node? Also, why did you put the getdata computation in parentheses? Just curious.

     

    I don't know.

     

    The code was cobbled together from various examples that purport to do what I am intending to accomplish.

    I'd reckon the original coder (whose code I've 'borrowed') decided to do it that way.

     

    When (if?) I reach a point of actually understanding any of this, I figure to through and make it all proper.

     

    You're right about that setTimeout() function. It pauses the code execution for a specified time.

     

    What I am finding, however, is that the timer will not 'reset to zero' if there has been another

    keystroke - it merely 'pauses' the ultimate code execution called by each keystroke.

     

    The net result of this is that the code still checks each letter as it's typed - but with a time delay added.

     

    In a moment of brilliance, I deduced that clearTimeout() might be the missing link:

     

    function checkName(keyEvent) {
    
     // kill timer if running
     if (x) {
       clearTimeout(x);
     }
    
     // create new variable
     var x;
    
     // set specified time
     x = setTimeout(function(){
    
       // funky AJAX happens here
    
     }, 3000);
    
    }
    

     

    Still didn't work the way it should.

     

    I suppose it should go something like this:

     

    function checkName(keyEvent) { 
    
     // kill previous timer, if running 
    
     // reset timer to zero
    
     // listen for keystoke
    
     // if no keystroke, and timer has reached 3 seconds {
    
         // execute AJAX call
    
     // } otherwise a keystoke occurred {
    
         // rinse and repeat
     //} 
    
    }
    

     

    Or something.

     

    - David

  15. The code validates a first/last name combination.

     

    function checkName() { 
    
     // set data constant variables
     var first = document.getElementById("first_name").value;
    
     // identify field to watch
     var input = document.getElementById("last_name");
    
     // if the text field has value, process the content
     if (input.value) {
    
       // query to be run on database
       getdata = ("webaddress.php?f=" + first + "&l=" + input.value);
    
       // other AJAX stuff goes here
    
     }
    
    xhr.open('GET', getdata, true);
    xhr.send(null);
    
    }
    
    <input id="first_name" type="text"/>
    <input id="last_name" type="text" onkeyup="checkName()"/>
    

     

    The current setup calls the function on each keystroke in the last_name field.

     

    What I would like to do is get the code to listen for a pause in the keystrokes - perhaps a pause longer than three seconds - before sending the AJAX request.

     

    The idea would be to somehow delay the function from firing until the typing has most likely been completed.

     

    Onblur is right out because the balance of the form is invisible until the name validates.

     

    Any ideas or suggestions would be appreciated.

     

    - David

×
×
  • Create New...