Jump to content

KevinM1

Moderators
  • Posts

    5,222
  • Joined

  • Last visited

  • Days Won

    26

Everything posted by KevinM1

  1. Not to derail the thread, but technically that's not JSON. That's object literal notation. JSON is a subset of object literal notation that requires identifyers to be strings themselves (http://www.json.org/js.html). So: var myJSON = { "id" : "mySound1", "url" : "../mpc/audio/CHINA_1.mp3" }; Is JSON. Small nit to pick, I know, but the two aren't entirely the same. To me, it's like saying ++i and i++ are the same thing. Close, but not quite. It also doesn't help when people like Dustin Diaz continue to call object literal notation JSON. Anyway, it's just a pet peeve of mine. My communication degree has turned me into something of a language/terminology fiend.
  2. In what way is it not working?
  3. I think a good rule of thumb is to ask yourself whether or not you need direct possession of an object for it to do its job. For instance, a lot of factories (classes used to construct objects out of raw data) use static methods. Why? Because you don't want your hands on the factory, you want them on the object(s) the factory creates. The same goes for nloding's validator. He doesn't need to have possession of a validator object, he just needs the boolean return value (whether the data passed in is valid or not). Keep in mind, though, nothing is set in stone. You could very well need to create a validator object, for example. One such reason would be to count the number of failed inputed values. It makes more sense to keep that functionality as part of the object than to litter the client code with the incrementation of those values. I hope this helps and hasn't muddled things further.
  4. This is the question everyone seems to ask themselves when they first start. It's important to note that classes aren't just a way to group functions. While you can go that route, that doesn't mean you're truly programming in an object oriented way. The heart of OOP is the dynamic interaction of objects at runtime. Objects create other objects, which, in turn, communicate with even more objects. These objects themselves contain objects, which do different things based on the data passed to them. What does this all mean? The biggest difference you'll see if/when you grasp OOP is the lesser number of outright scripts involved in the creation and running of a website. Instead of having a host of scripts, each with a different job (index.php brings the user to login.php, which may then forward them to another script), you'll have one script which will delegate to the correct object when a request is formed. If a user needs to be logged into the system, the script calls on the login object to do the work. Need to display database records? The script calls the display object, which, in turn, accesses the database object. In PHP 5, this is made easier (and more dynamic) by the __autoload() function, which automatically loads class files when an object of that type is created/accessed. It removes the need to keep track of your includes/requires. The thing to keep in mind is that classes are more than merely a way to group functions. If that's all you view them as, you might as well just stick with procedural programming. If you're interested in 'getting' OOP, I suggest getting PHP 5 Objects, Patterns, and Practice by Matt Zandstra (http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/ref=sr_1_2?ie=UTF8&s=books&qid=1211888410&sr=1-2) and Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four (http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1211888480&sr=1-1).
  5. The code I gave you should work. I made a small test case that uses the same method of appending 'i' to the id of a group of elements, and it works correctly: <html> <head> <title>JavaScript loop test</title> <script type="text/javascript"> window.onload = function() { for(var i = 1; i < 4; i++) { var divObj = document.getElementById("div" + i); divObj.onmouseover = function() { this.style["border"] = "1px solid black"; } divObj.onmouseout = function() { this.style["border"] = ""; } } } </script> </head> <body> <div id="div1"> This is div1 </div> <div id="div2"> This is div2 </div> <div id="div3"> This is div3 </div> </body> </html>
  6. You do realize that sessions, by default, use cookies, right?
  7. Try: function start() { for(var i = 1; i < 6; i++) { var videoObj = document.getElementById("video" + i); var overlayObj = document.getElementById("overlay" + i); videoObj.onmouseover = function() { overlayObj.style.display = 'inline'; } overlayObj.onmouseout = function() { this.style.display = 'none'; } } }
  8. D'oh, the function should be array_keys(), not array_key_exists().
  9. Yeah, the HTTP_REFERER would be perfect if it always worked. :\ Trying to harden GET is a bit tricky. It's easiest when you know what values you'll allow to be passed into the system via URL. Then, you can just create a regex that checks the value of the URL component vs. the values you'll allow. Trying it the other way - storing a whitelist of commands/parameters and checking it against each key in $_GET - is a bit more complicated. You could try something like: <?php $safe = array("cmd", "page", "id"); //list of commands/parameters allowed to be passed into the system via URL $results = array(); function isSafe($getInfo) { foreach($safe as $allowed) { for($i = 0; $i < count($getInfo); $i++) { $results[] = array_key_exists($allowed, $getInfo); } } return $results; } //... if(isset($_GET) && isSafe($_GET)) { $safeGetResults = isSafe($_GET); //handle the results and process } ?> It's not particularly elegant, and I'm sure someone else can come up with a better way of doing it, but the idea is there. Regarding the exchange of database info: for simple encoding/decoding, you could probably switch to Base64 and back, or uuencode, but that would result in larger values being saved in the database. If the database is storing critical info, there's probably a way to encrypt/decrypt it. Does base SQL have encryption built in? Like an AES function or something?
  10. Are you talking about actually hiding the div from the page source (i.e., when a user chooses "View Source")? If so, then the only way I can think of 'hiding' that bit of the source code is to have your script dynamically create the element and its content: <html> <head> <title>Element creation test</title> <script type="text/javascript"> window.onload = function() { var myDiv = document.createElement("div"); var myText = document.createTextNode("This is a dynamically created div"); var myBody = document.getElementsByTagName("body")[0]; myDiv.appendChild(myText); myBody.appendChild(myDiv); } </script> </head> <body> </body> </html> If JavaScript isn't enabled, then the div isn't created, so it won't show up in the source code. Note that I didn't use myDiv.innerHTML = something. In my experience, things added to an element using innerHTML never show up in the source at all, so it's useless if you want dynamically created markup to appear in the source. This is pretty simple. Modifying the code above: <html> <head> <title>Element creation test</title> <script type="text/javascript"> window.onload = function() { var myDiv = document.createElement("div"); var myText = document.createTextNode("This is a dynamically created div"); var myBody = document.getElementsByTagName("body")[0]; myDiv.appendChild(myText); myBody.appendChild(myDiv); var testClick = document.getElementById("testClick"); testClick.onclick = function() { myDiv.style.display = (myDiv.style.display == 'none') ? 'block' : 'none'; return false; } } </script> <style type="text/css"> div { display: none; } </style> </head> <body> <a id="testClick" href="http://www.google.com/">Click me!</a> </body> </html>
  11. Well, fixed-width would probably be the easiest way to fix it, as you wouldn't have to worry about screen resolution (for the most part). That left/right movement you've been noticing should go away, as the containing block will remain the same size. In other words, if you have a site with a width of 900px, and you tell the drop-down to be top: 100px and left: 500px, it will position itself relative to the 900px, not the browser window.
  12. Question: Is the rest of your site fixed-width?
  13. I'm not sure if a direct attack (i.e., injection) using GET is possible. It obviously depends on how the value is used, but in my experience, GET is typically used to retrieve database info, not set it. That said, there is still some danger of indirect attacks. There are two possibilities that immediately come to mind: 1. A site uses GET for user login. Dumb, but it happens with newbies. The link is something like: www.somesite.com/login?user=name&pass=pass. One could then brute force their way onto the site as an administrator. 2. More likely, and dangerous, is the case of the lazy coder who uses the $_REQUEST array to handle everything instead of the separate $_GET and $_POST arrays. So, even if user login is handled by a form that sends data through POST, since the script is using $_REQUEST, an attacker can keep feeding it modified URLs until they get in as admin.
  14. As much as I dislike doing other people's homework, the following should suffice: <!-- Note: language attribute is deprecated. Use type attribute instead. --> <script type="text/javascript"> /** *Function that validates an e-mail address input * *Arguments: *None. * *Return value: *None (alert message upon failure). */ function validateEmail() { var emailAddr = emailInput.value; //value of the input var hasAt = 0; //does the value have an '@'? for(var i = 0; i < emailAddr.length; i++) //iterate through the address to check for the '@' { if(emailAddr.charAt(i) == "@") //if the address has an '@' { hasAt++; //set it to true } } //since hasAt is an integer, it can be treated as a boolean if(!hasAt || emailAddr.charAt(0) != "") //if there's no '@' or the first character is blank { alert("Your e-mail address is not valid."); //alert validation failure } } </script> You should be careful about using charAt() to check a value's length. Just because the first character in a string is blank, it doesn't necessarily mean the entire form input is blank. You should probably check to see if the entire length of the value (in this case, emailAddr.length) is equal to 0. Not only that, but even if an inputed value has an '@', that doesn't mean it's a valid e-mail address, either. I mean: Isn't a valid address, yet your function will treat it as one.
  15. Sorry to bump this up, but I figure it's better to do that than to make another top-level thread. Like I said before, I like working on the nuts-and-bolts of code because I feel it helps me understand what's going on. I know it's not technically necessary, but I believe it helps me learn, so it's necessary to me. I'm also a bit of a perfectionist, and like a good challenge. So, on things like this, I tend to work on them even when I probably shouldn't. Add my ego to the mix, and you get my first couple of snarky replies. I sincerely apologize for those. So, to get to the point, the good news is that I got my personal library code to work. Turns out there was an extra comma in the MP.Form.Validate namespace/object, so that was messing up the whole thing. I've also gotten the function to successfully create a XMLHttpResponse/ActiveXObject working. So, in essence, I have the main building block in place. I decided to test my new creation by having it work with the PHP script I used in conjunction with my JQuery AJAX tests (I'm loving JQuery, btw. Still have to get used to some of the syntax, but it's great). It works, but after receiving the response from the server, the system hangs. It seems almost as though the connection isn't closing. This happens regardless of whether or not I'm using the short, JQuery-esque, currently commented version of the createXmlHttpRequestObject() function or the long version, which is currently active. Is there a way to manually close an XMLHttpRequest connection? Or is something else going on? I've put the relevant code below: MPlib.js (only the important parts): var MP = {}; //----------------------------------------------------------------------------------------------- MP.Ajax = { /** *Function that equalizes XMLHttpRequest objects. * *Arguments: *None * *Return value: *@xmlHttp - either a new XMLHttpRequest object (if IE7, Mozilla, Safari, or Opera), a new ActiveXObject (if IE's < 7), or null (if none of the above). * *Original Code: *From "Building Responsive Web Applications: AJAX and PHP" by Christian Darie et al. */ createXmlHttpRequestObject : function() { /* var xmlHttp = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); return xmlHttp; */ var xmlHttp; try { //try the hard way because IE7 doesn't implement XMLHttpRequest() properly var xmlVersions = new Array('MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'); //iterate through the array until we get one that works for(var i = 0; i < xmlVersions.length && !xmlHttp; i++) { xmlHttp = new ActiveXObject(xmlVersions[i]); } } catch(e) { //try the easy way for the good browsers xmlHttp = new XMLHttpRequest(); } //return object (if we have one) or null return xmlHttp; } }; ajaxtest.html: <html> <head> <title>XMLHttpRequest Test</title> <script type="text/javascript" src="js/MPlib.js"></script> <script type="text/javascript"> window.onload = function() { alert(MP.constructor); alert(MP); alert(MP.Ajax); alert(MP.Ajax.createXmlHttpRequestObject); var xmlHttp = MP.Ajax.createXmlHttpRequestObject(); if(xmlHttp) { alert("XMLHttpRequest object is type: " + xmlHttp.constructor); var param = encodeURIComponent("red"); var paramStr = "action=" + param; xmlHttp.open("POST", "jqueryajax.php5", true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.onreadystatechange = handleRequest; xmlHttp.send(paramStr); } else { alert("Cannot obtain XMLHttpRequestObject"); } function handleRequest() { if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) { try { readResponse(); } catch(e) { alert("Could not interact with the server"); } } } } function readResponse() { document.write(xmlHttp.responseText); } } </script> </head> <body> </body> </html> jqueryajax.php5: <?php if(isset($_POST['action'])) { $action = $_POST['action']; if($action == 'red') { echo "<strong>This box is red</strong>"; } else if($action == 'blue') { echo "<strong>This box is blue</strong>"; } } ?> Again, I'm going to use a professional library for legitimate projects. This is just for my own learning.
  16. Is there any real difference between the two, other than how their doctype is declared? I read something about 1.1 being 'module based.' Does this mean it can be mixed and mashed with other XML-based markup languages (like, say, a set of locally defined mathematic tags)?
  17. Thanks for finding the typo. I'm amazed that it went through both IE and FF with it. Neither have given me an error for the library file. Are there any major differences between the various versions of the MSXML2.XMLHTTP ActiveX objects? Because I'm tempted to just gut the other versions from the function (not that will help the non-construction of the MP object). Oh, I tried some JQuery this afternoon. I was hesitant at first, with the $("blah") syntax, but it seems simple enough. Certainly easier to type than YUI's stuff. Do you find more object-focused libraries (Prototype, for example) necessary? I ask because JQuery seems good with the nitty-gritty aspects of JavaScript, but doesn't really have much beyond that.
  18. Well, none of the alerts you suggested fired. I was thinking that it was a typo as well, but Firebug doesn't catch anything either. Here's my entire library. Once again, apologies for the indent issues. Notepad++ hates message boards, apparently: /** *This is my first attempt at building a JavaScript library. *While most of my code will use a pre-existing library (YUI, Scriptaculous, JQuery, Prototype, or Moo.fx), *I still have other helper functions I'd like to use. * *Date: May 19, 2008 */ /** *Global namespace */ var MP = {}; //----------------------------------------------------------------------------------------------- /** *DOM namespace */ MP.DOM = { /** *Function to get/set element attributes. *It normalizes those tricky cases of 'for' = 'htmlFor' and 'class' = 'className'. * *Arguments: *@elem - element we're accessing. *@name - name of the style. *@value - value of what we're setting (if any). * *Return value: *@object (CSS style) - the style of @elem[@name]. * *Original code: *From "Pro JavaScript Techniques" by John Resig. */ handleAttr : function(elem, name, value) { //Make sure a valid name was provided if(!name || name.constructor != String) { return ''; } //Figure out if the name was one of the weird naming cases name = {'for' : 'htmlFor', 'class' : 'className'}[name] || name; //If the user is setting a value, also if(typeof value != 'undefined') { elem[name] = value //If we can use setAttribute if(elem.setAttribute) { elem.setAttribute(name, value); } } //Return the value of the attribute return elem[name] || elem.getAttribute(name) || ''; }, //----------------------------------------------------------------------------------------------- /** *Function to create a new DOM element. *It normalizes XHTML and HTML element creation. * *Arguments: *@elem - type of element we're creating. * *Return value: *@object (DOM element) - DOM element of type @elem. * *Original code: *From "Pro JavaScript Techniques" by John Resig. */ createElem : function(elem) { return document.createElementNS ? document.createElementNS('http://www.w3.org/1999/xhtml', elem) : document.createElement(elem); } }; //----------------------------------------------------------------------------------------------- /** *Form namespace */ MP.Form = {}; //----------------------------------------------------------------------------------------------- /** *Form handling/validation namespace. */ MP.Form.Validate = { /** *Function to see if a required input has had information entered into it. * *Arguments: *@elem - element we're checking. * *Return value: *@boolean - whether or not a required field value has been entered. * *Original code: *From "Pro JavaScript Techniques" by John Resig. */ checkRequired : function(elem) { if(elem.type == "checkbox" || elem.type == "radio") { return getInputsByName(elem.name).numChecked; } else { return elem.value.length > 0 && elem.value != defaultValue; } }, //----------------------------------------------------------------------------------------------- /** *Helper function to find all input elements that have a specific name (good for those pesky checkboxes and radio buttons). * *Arguments: *@name - name of the elements we're looking for. * *Return value: *@results - an array of form inputs whose name matches @name. * *Original code : *From "Pro JavaScript Techniques" by John Resig. */ getInputsByName : function(name) { //The array of input elements that will be matched. var results = []; //Counter to keep track of how many have been checked. results.numChecked = 0; //Find all input elements in the document. var inputs = document.getElementsByTagName("input"); for(var i = 0; i < inputs.length; i++) { //Find all inputs that have the name we're looking for. if(inputs[i].name == name) { //Add it to the array results.push(input[i]); //Remember how many of the fields have been checked, if any if(input[i].checked) { results.numChecked++; } } } return results; }, //----------------------------------------------------------------------------------------------- /** *Function that validates an e-mail address. *This version accepts either an empty string or a properly-formed e-mail address. *If an e-mail address is required, either use the checkRequired() function, or modify this to not accept an empty string. * *Arguments: *@elem - the element whose value we're checking. * *Return value: *@boolean - whether or not the field value is valid. * *Original code: *From "Pro JavaScript Techniques" by John Resig. */ validateEmail : function(elem) { return elem.value == '' || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(elem.value); }, //----------------------------------------------------------------------------------------------- /** *Function that validates an inputed URL. *This version accepts either an empty string, the default value (in this case, 'http://'), or a properly-formed URL. *If an URL is required, either use the checkRequired() function, or modify this to neither accept an empty string nor the default value. * *Arguments: *@elem - the element whose value we're checking. * *Return value: *@boolean - whether or not the field value is valid. * *Original code: *From "Pro JavaScript Techniques" by John Resig. */ validateURL : function(elem) { return elem.value == '' || !elem.value == 'http://' || /^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/i.test(elem.value); }, //----------------------------------------------------------------------------------------------- /** *Other validation functions to be added later. */ }; MP.ajax = { /** *Function that equalizes XMLHttpRequest objects. * *Arguments: *None * *Return value: *@xmlHttp - either a new XMLHttpRequest object (if IE7, Mozilla, Safari, or Opera), a new ActiveXObject (if IE's < 7), or null (if none of the above). * *Original Code: *From "Building Responsive Web Applications: AJAX and PHP" by Christian Darie et al. */ createXmlHttpRequestObject : function() { var xmlHttp; try { //try the easy way first xmlHttp = new XMLHttpRequest(); } catch(e) { //try the hard way next (IE6 or older) var XmlVersions = new Array('MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'); //try every version until we get one that works for(var i = 0; i < xmlVersions.length && !xmlHttp; i++) { try { xmlHttp = new ActiveXObject(xmlVersions[i]); } catch(e) { xmlHttp = null; } } } //return object (if we have one) or null return xmlHttp; } }; EDIT: Just for clarity's sake, those three alert functions aren't firing at all. It's not a matter of 'undefined' popping up. Nothing is popping up.
  19. That's quite vague. What are you trying to do, specifically?
  20. If you're using 'visibility: hidden' try switching it to 'display: none' (or vice-versa).
  21. I know, but I'd still like to figure out why IE is giving me problems with this seemingly obvious assignment. I'm certain it's a Microsoft hiccup, as Firebug reports it as clean. It's bugging me.
  22. Because I'm learning the nuts and bolts of both JavaScript and AJAX at the moment, and would like to get a clear idea of what's really going on behind the scenes (or, in AJAX's case, how a simple asynchronous exchange is structured and handled) before abstracting it all away behind a 3rd party library? Like I said in my library's comments, I'll use a 'real'/professional library when doing 'real'/professional things (I've had my eye on YUI for a while, in part because its syntax is normal). Right now I'm at the learning stage. I figure any errors/bugs/issues I encounter now will give me valuable experience in dealing with them (or similar ones) when I move on. In any event, I do appreciate your suggestion, but it doesn't help me at the moment. I'd really like to know why IE is choking on my function invocation so I can possibly avoid that problem in the future.
  23. So, I'm currently expanding my JavaScript library. Basically, it's a bunch of functions found elsewhere that I want in a centralized location. I've gone the route of creating namespaces for each logical division of my library. So, there's a global namespace, a DOM namespace, a form namespace, etc. The specialized namespaces (DOM, form, etc) are children of the global namespace. I'm currently trying my hand at some AJAX stuff. Right now, I have one function designed to return to me a proper XMLHttpRequest object or ActiveXObject depending on the browser. As always, it works in Firefox, but not IE7. So, here's the relevant part of my library (apologies for the lack of indents...Notepad++ indents don't seem to copy over correctly): /** *This is my first attempt at building a JavaScript library. *While most of my code will use a pre-existing library (YUI, Scriptaculous, JQuery, Prototype, or Moo.fx), *I still have other helper functions I'd like to use. * *Date: May 19, 2008 */ /** *Global namespace */ var MP = {}; //----------------------------------------------------------------------------------------------- MP.ajax = { /** *Function that equalizes XMLHttpRequest objects. * *Arguments: *None * *Return value: *@xmlHttp - either a new XMLHttpRequest object (if IE7, Mozilla, Safari, or Opera), a new ActiveXObject (if IE's < 7), or null (if none of the above). * *Original Code: *From "Building Responsive Web Applications: AJAX and PHP" by Christian Darie et al. */ createXmlHttpRequestObject : function() { var xmlHttp; try { //try the easy way first xmlHttp = new XMLHttpRequest(); } catch(e) { //try the hard way next (IE6 or older) var XmlVersions = new Array('MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'); //try every version until we get one that works for(var i = 0; i < xmlVersions.length && !xmlHttp; i++) { try { xmlHttp = new ActiveXObject(xmlVersions[i]); } catch(e) { xmlHttp = null; } } } //return object (if we have one) or null return xmlHttp; } }; Here's my test code to see if it works: <html> <head> <title>XMLHttpRequest Test</title> <script type="text/javascript" src="js/MPlib.js"></script> <script type="text/javascript"> window.onload = function() { var xmlHttp = MP.ajax.createXmlHttpRequestObject(); if(xmlHttp) { alert("XMLHttpRequest object is type: " + xmlHttp.constructor); } else { alert("Cannot obtain XMLHttpRequestObject"); } } </script> </head> <body> </body> </html> IE keeps telling me that MP is undefined at the spot where I attempt to run the function. It's not, as it works perfectly in Firefox, and I get no errors in Firefox's error console nor in Firebug. IE still claims it's undefined even when I try to pre-assign it like so: var MPNamespace = MP; var xmlHttp = MPNamespace.ajax.createXmlHttpRequestObject(); Any ideas on how to make IE recognize my global namespace?
  24. True, which is why I wrote, in my rewritten version of your function, 'return false;' Returning false should stop the default action (in this case, normal form submission and subsequent page reload) from happening. This is the same reason why a lot of hyperlinks with onclick callback functions return false -- chances are, you don't want the link to actually be followed. I suggest trying my version of things before giving up. It might not work right off the bat (I wrote it off the top of my head, so I didn't test it), but something along those lines should work. In any event, I also suggest trying to separate your JavaScript from your markup. By that, I mean, at the most, things like this: <html> <head> <title>Blah blah blah</title> <script type="text/javascript"> window.onload = function() { //JavaScript stuff } </script> </head> <body> </body> </html> But NOT things like this: <body onload=someFunction()> The reasons are many, but here's two off the top of my head: 1. By keeping code external, you can create reusable libraries of code. Very helpful if you have a fancy AJAX technique you want to port to another site. 2. You greatly reduce the burden of site construction and maintenance. It works more or less like the relationship between (X)HTML and CSS. By keeping JavaScript external, you can have one (or a handful) of files that give dynamism to your entire site. More than that, you don't have to dig through markup to find script errors. Everything is where it's supposed to be, so fixing/adding to it is much simpler as a result. Just something to think about. IMO, the upfront work it takes to port everything to external files is nothing compared to combing through markup to copy a neat function or find script errors.
  25. Hmm, what you're trying to do is a bit odd on the surface. It looks like you're trying to force POST data into a GET-like format. In any event, your method of going through each input is correct. In order to use 'this', you need the function to know that the object in the current context is the form. I suggest trying some unobtrusive (read: not stuck in the middle of your HTML) JavaScript: <html> <head> <title>Blah blah blah</title> <script type="text/javascript"> window.onload = function() { var searchForm = document.getElementById("searchForm"); searchForm.onsubmit = compilePostData; } function compilePostData() { var postStr = ""; for(var i = 0; i < this.elements.length; i++) { postStr += "&" + escape(encodeURI(this.elements[i].name)) + "=" + escape(encodeURI(this.elements[i].value)); } makePOSTRequest('action.php', postStr); return false; } </script> </head> <body> . . . <form id="searchForm" action="action.php" method="POST"> . . . </form> </body> </html> With all that said, I don't really see the point in constructing POST data in this way, as PHP can automatically parse a form input's name from the data it holds: <input type="text" name="tags" /> <?php foreach($_POST as $key => $value) { echo "Form input name: $key -- Form input value: $value"; //This will print: Form input name: tags -- Form input value: } ?> On the surface, it just looks like you're making more work for yourself, as you'll probably need to parse the name from the value any way. Just something to keep in mind.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.