Jump to content
Larry Ullman's Book Forums

synergy

Members
  • Posts

    8
  • Joined

  • Last visited

Everything posted by synergy

  1. I have a script that processes the mail, in an external file. However, I use a self-processing form as well (instead of sending the data to a separate file, there is a PHP conditional statement above the DOCTYPE declaration that checks if the form has been submitted). I'm doing this because I want to preserve user input on the page if there are errors. The parts of the script that are specific to the form are embedded in the PHP code block on the .php page itself. The reusable parts are in a separate file.
  2. Hi there, I have a relatively simple sounding question that hopefully entails a simple answer. I am currently developing a website that is a scroll-down type; everything is on one page, you know the one. My 'contact' section is at the very bottom of the page, and I am of course doing form validation with PHP. The validation part works, I have no trouble with that. However, if validation fails, the browser takes me back all the way back to the top of the page; this is inconvenient for obvious reasons. I am aware of the 'header()' function, which I can use to keep me at the bottom of the page if an error occurs. As an example, at the top of my HTML page before the DOCTYPE, I can write: if ($errors) { header(Location: 'somelocation.php#contact'); } This works, but for some reason it prevents my PHP embedded in my html to work. If I have: <h2>Title</h2> <?php if($errors) { ?> <p class="warning">Please fix the errors</p> <?php } ?> 'Please fix the errors' does not appear. It does appear however, if I remove the header function from the page, so I know the problem is related. Alternatively, this question also can be asked in the case of, what happens if the form is validated correctly, the 'header' function is called, and I want to stay at the bottom of the page and display some HTML saying 'Thanks, your form has been submitted'? (I don't want to go to a 'thank-you' page or anything, just stay in the same spot and give a 'thanks' on the page) I assume I'd run into the same problem. Is there a solution to this? Thanks in advance!
  3. Hi again, Thanks Hartley! Wonderful. Thanks for finding that error! I've actually taken what you gave me and applied to the example in the book (to make it work with a click). I also put some stuff into a 'sendAjax' function because it just makes more sense to me that way (you click the button and that event is what generates everything): //ajax2 test function addEvent(obj, type, fn) { 'use strict'; if(obj && obj.addEventListener) { obj.addEventListener(type, fn, false); } else if (obj && obj.attachEvent) { obj.attachEvent('on' + type, fn); } } function $(id) { 'use strict'; if (id && typeof id === 'string') { return document.getElementById(id); } } //-------------------------AJAX begins here----------------------------------------- //Step 1: Function to create ajax object function getXMLHttpRequestObject() { 'use strict'; var ajax; if(window.XMLHttpRequest) { ajax = window.XMLHttpRequest(); } else if (window.ActiveXObject) { ajax = new window.ActiveXObject('MSXML2.XMLHTTP.3.0'); } return ajax; } //Step 2: Define result handler. This is the function that will be called during the Ajax transaction. function ajaxHandlingFunction() { 'use strict'; if(this.readyState == 4) { if( (this.status >= 200 && this.status < 300) || (this.status == 304) ) { document.getElementById('output').innerHTML = this.responseText; } else { document.getElementById('output').innerHTML = 'Error: ' + this.statusText; } } }//end of ajaxHandlingFunction window.onload = function() { 'use strict'; var button = $('btn'); addEvent(button, 'click', sendAjax); }; function sendAjax(){ var ajax = getXMLHttpRequestObject(); ajax.open('GET', 'resources/test.txt', true); addEvent(ajax, 'readystatechange', ajaxHandlingFunction); ajax.send(null); } One last question, what does Larry mean when he says "the object that is the target of the event will be the same XMLHttpRequest object"? Thomas
  4. Hi again, Thanks Hartley for the replies! Appreciated. So let's see: 1. I see what you did with the DOM level 2 approach. Very cool. So 'this' refers to the window object?... 2. About firebug: Here is an image of the error I get, with the code I gave above ('from ajax2.js'). Why am I getting this error? 3. From the book's examples, I am still confused about using the event object. In other words, I'm confused about variable scoping. Larry mentions to use the event object of the ready state event handler on page 458, and this confuses me, because being a newb I don't see how using this event object is the workaround to not being able to access the 'ajax' variable. In other words, when you create a SEPARATE ready state event handler (not an anonymous function, ie, not 'ajax.onreadystatechange = function(){ etc...), you lose access to the ajax variable you previously made. So in this function: window.onload = function() { 'use strict'; var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = function(){ if(ajax.readyState == 4){ if( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) { document.getElementById('output').innerHTML = ajax.responseText; } else { document.getElementById('output').innerHTML = ajax.statusText; } } }//end of onreadystatechange anonymous function document.getElementById('btn').onclick = function() { 'use strict'; ajax.open('GET', 'resources/test.txt', true); ajax.send(null); }; //end of onclick anonymous function }; //end of onload anonymous function You have access to the ajax variable and thus have access to it when defining your ready state handler. if I try to do it seperately, as in my example from 'ajax2.js' in my first post, I lose access to the ajax variable. The confusing this is, in the book, Larry defines the variable ajax twice... once as: var ajax = e.target || e.srcElement; // page 458 AND, in the window.onload function on page 459 (all part of the same script): var ajax = getXMLHttpRequest(); SO... why is this variable defined twice? It just confuses me. Sorry about my questions being rather all over the place.
  5. Hi there, Just trying out writing my own simple Ajax application. Now, in the book the first example of Ajax is defined with two files, ajax.js and test.js. So they are: From ajax.js: function getXMLHttpRequestObject() { 'use strict'; var ajax; if(window.XMLHttpRequest){ //Not IE ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { //Older IE ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } return ajax; } // end of getXMLHttpRequestObject() From test.js: window.onload = function() { 'use strict'; var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = function(){ if(ajax.readyState == 4){ if( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) { document.getElementById('output').innerHTML = ajax.responseText; } else { document.getElementById('output').innerHTML = ajax.statusText; } } }//end of onreadystatechange anonymous function document.getElementById('btn').onclick = function() { 'use strict'; ajax.open('GET', 'resources/test.txt', true); ajax.send(null); }; //end of onclick anonymous function }; //end of onload anonymous function This code obviously works. Now, because of variable scrope, ajax is only defined once using the getXMLHttpRequestObject()... I get that, because everything is within this window.onload function and all variables are accessible. The onreadystatechange function is defined anonymously and thus has access to the ajax variable. Now, I wanted to experiment creating the event listener using the DOM LEVEL 2 approach (addEventListener method), but I find that I cannot access the variable ajax because of variable scope. I DID READ on page 458 the workaround for this, but I am left confused. Larry says to "get the object that referenced the event" and ends that "...the target of the event will be the same XMLHttpRequest object." What does that mean? I don't understand how defining the event object gives you access to that variable. That's my first question. My second question is from my code. I tried using the event object to define it, but the error I am getting is 'ajax.open is not a function' from Firebug. It would seem then that ajax is not defined, or not defined properly... so I am confused as to why my code doesn't work. I used the DOM LEVEL 1 approach for the event handler because I just don't know how to use the addEventListener way. Here is my code: function addEvent(obj, type, fn) { 'use strict'; if(obj && obj.addEventListener) { obj.addEventListener(type, fn, false); } else if (obj && obj.attachEvent) { obj.attachEvent('on' + type, fn); } } function $(id) { 'use strict'; if (id && typeof id === 'string') { return document.getElementById(id); } } //-------------------------AJAX begins here----------------------------------------- //Step 1: Function to create ajax object function getXMLHttpRequestObject() { 'use strict'; var ajax; if(window.XMLHttpRequest) { ajax = window.XMLHttpRequest; } else if (window.ActiveXObject) { ajax = window.ActiveXObject('MSXML2.XMLHTTP.3.0'); } return ajax; } //Step 2: Define result handler. This is the function that will be called during the Ajax transaction. function ajaxHandlingFunction(e) { 'use strict'; if (typeof e == 'undefined') e = window.event; var ajax = e.target || e.srcElement; if(ajax.readyState == 4) { if( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) { document.getElementById('output').innerHTML = ajax.responseText; } else { document.getElementById('output').innerHTML = 'Error ' + ajax.statusText; } } }//end of ajaxHandlingFunction window.onload = function() { 'use strict'; var button = $('btn'); var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = ajaxHandlingFunction; button.onclick = function(){ ajax.open('GET', 'resources/test.txt', true); ajax.send(null); }; }; Any ideas on why I get 'ajax.open isn't a function', and how would you do this using the addEventListnener approach? Sorry for the long post, but I guess it reflects my confusion.
  6. Hi again Larry, I figured it out! Hours and hours of debugging came down to a typo mistake in the if-else segment of the select element. I noticed that it wasn't displaying an error even if I didn't pick anything. I defined: var foodType = U.$('food'); And wrote later on: if(foodtype.selectedIndex != 0) { removeErrorMessage(foodtype.id); } else { addErrorMessage(foodtype.id, 'Select something PLZ'); error = true; } ...I forgot to capitalize the 't' in 'foodtype'. So that fixed that. However, my question now is, why did that throw off the entire function (ie. why did the function still not prevent the default behavior)? There were still errors in the form (I left it blank when I tested it), so the variable 'error' still would have been 'true'. Any ideas sir? Thanks, Thomas
  7. Hi Larry, Fixed those and it still doesn't appear to be working. I'll keep looking at it, it's really puzzling.
  8. Hi, Re-creating some form validation code from scratch for practice (basically the stuff from the end of the Forms chapter) and for some reason or another, I can't prevent the form from submitting. The errors pop up briefly (if I didn't fill out an input or left it blank), but quickly disappear again due to the fact the form gets submitted (I can tell because a hash tag appears in the URL after submission). I'm thinking it has something to do with preventDefault(), but I just can't find any errors with it and I've been looking at it for hours. Any idea why? Here is the code I've written for practice: THE HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Playing with Forms 2</title> <link rel="stylesheet" href="css/manoForm2.css" media="screen"> </head> <body> <form action="#" method="post" id="form" novalidate> <fieldset><legend>Register, and be cool.</legend> <div class="one"><label for="firstName">First Name</label><input type="text" name="firstName" id="firstName" required></div> <div class="one"><label for="lastName">Last Name</label><input type="text" name="lastName" id="lastName" required></div> <div class="one"><label for="email">Email</label><input type="email" name="email" id="email" required></div> <div><label for="food">Choose your food</label><select name="food" id="food"> <option value="">Pick a food</option> <option value="Meat">Bacon</option> <option value="Other">More Bacon</option> </select></div> <div class="two"><input type="checkbox" name="checkbox" id="checkbox">I agree to some stuff.</div> <div class="two"><input type="submit" value="Register" name="submit" id="submit"></div> </fieldset> </form> <script src="js/registernew.js"></script> <script src="js/error2.js"></script> <script src="js/utilities2.js"></script> </body> </html> THE Javascript From registernew.js: function validateForm(e) { 'use strict'; if (typeof e == 'undefined') e = window.event; var firstName = U.$('firstName'); var lastName = U.$('lastName'); var email = U.$('email'); var foodType = U.$('food'); var error = false; if(/^[A-Za-z]{2,20}$/.test(firstName.value)){ removeErrorMessage(firstName.id); } else { addErrorMessage(firstName.id, 'First name PLZ'); error = true; } if(/^[A-Za-z]{2,20}$/.test(lastName.value)){ removeErrorMessage(lastName.id); } else { addErrorMessage(lastName.id, 'Last name PLZ'); error = true; } if(/^[\w\.-]+@{1}[\w\.-]\.{1}[a-z]{2,6}$/.test(email.value)){ removeErrorMessage(email.id); } else { addErrorMessage(email.id, 'Enter emailz PLZ'); error = true; } if(foodtype.selectedIndex != 0) { removeErrorMessage(foodtype.id); } else { addErrorMessage(foodtype.id, 'Select something PLZ'); error = true; } if(error){ if(e.preventDefault){ e.preventDefault(); } else { e.returnValue = false; } } }//end of validateForm function function toggleSubmit(){ 'use strict'; var checkbox = U.$('checkbox'); var submit = U.$('submit'); if(checkbox.checked){ submit.disabled = false; } else { submit.disabled = true; } }//end of toggleSubmit function window.onload = function() { 'use strict'; submit.disabled = true; U.addEvent(U.$('form'), 'submit', validateForm); U.addEvent(U.$('checkbox'), 'change', toggleSubmit); }//end of onload function From error2.js: function addErrorMessage(id, msg) { 'use strict'; var elem = document.getElementById(id); var newId = id + 'Error'; var span = document.getElementById(newId); if(span) { span.firstChild.value = msg; } else { span = document.createElement('span'); span.id = newId; span.className = 'error'; span.appendChild(document.createTextNode(msg)); elem.parentNode.appendChild(span); elem.previousSibling.className = 'error'; } }//end of addErrorMessage function removeErrorMessage(id){ 'use strict'; var elem = document.getElementById(id + 'Error'); if(elem){ elem.previousSibling.previousSibling.className = null; elem.parentNode.removeChild(elem); } }//end of removeErrorMessage From utlities2.js: var U = { $: function(id) { 'use strict'; if(id && typeof id === 'string') { return document.getElementById(id); } }, addEvent: function(obj, type, fn) { 'use strict'; if(obj && obj.addEventListener) { obj.addEventListener(type, fn, false); } else if(obj && obj.attachEvent) { obj.attachEvent('on' + type, fn); } }, removeEvent: function(obj, type, fn) { 'use strict'; if(obj && obj.removeEventListener) { obj.removeEventListener(type, fn, false); } else if(obj && obj.detachEvent) { obj.detachEvent('on' + type, fn); } } };//end of U object I am omitting the CSS because I barely wrote any for this form except for floating the .one elements and giving the label a width. If anyone can see what the error is, I'd appreciate it. Again, the problem is that the form is not being prevented from being submitted, and that the error messages flicker because of this (at least I think that's why). Thanks!
×
×
  • Create New...