|
Title: Couple of questions regarding javascript php interaction. Post by: thepreacher on January 22, 2007, 07:57:20 PM Sorry this is kind of embarrassing but my consolation is that you are only a novice once. I have a few issues i need help with:
1. I have 2 submit buttons with different names and values. For one when it is pressed the data on the form is submitted and stored on a database and for the other, it stores the data base and allows the user to keep entering data. The action script is a php script. Using php is there a way to determine in the action script which button was pressed so that i can perform the necessary action? 2. Say I have a javascript which validates a from but the action for the form itself is a php script, After i validate the form, how to i send all the form data to the php script to be stored in the database? Is it AJAX? 3. Generally, i will like to know the various means of exchanging data between Javascript and PHP Title: Re: Couple of questions regarding javascript php interaction. Post by: Diablo84 on January 23, 2007, 05:51:48 AM First and foremost, add the following to a separate PHP file:
Code
This will give you an idea of how the $_POST superglobal array, is populated by the HTTP Post data. $_POST is an associative array, with the name of the form elements providing the string keys, and the element values, providing the corresponding array values. Rather then using multiple submit buttons, I recommend you use a checkbox. It's a much cleaner approach, and makes life much easier server side. Let's look at another example: Code
If the checkbox is checked, it's 'key'=>'value' data will be present in the $_POST array, thus (isset($_POST['mycheck'])) will evaluate as true. If it's not checked, it's data will not be present (or 'set'), and the if construct will evaluate as false. You may wish for the checkbox to be checked by default, so for example, the script will continue to allow the user to enter more data, until they uncheck it. <input type="checkbox" name="mycheck" value="1" checked> Alternatively, you may wish to leave it unchecked by default, with the addition of a "predictive" piece of code. For example, if the user checks the box to add more data, there is a good chance that they will continue to add more data after that. <input type="checkbox" name="mycheck" value="1" <?php if (isset($_POST['mycheck'])) echo 'checked'; ?>> Once they have finished adding data, they will then be required to uncheck the box, to finalize their work. NOTE: if you are working with a valid XHTML document, the correct checkbox syntax is: <input type="checkbox" name="mycheck" value="1" checked="checked" /> ----- As for your second question, I have had an article in the works for the past few weeks, which would have been ideal for answering this one. Unfortunately, I have not had the time to finish it. It's important to remember that JavaScript executes in the users browser, it is client side validation, in an environment that you have no control over. As such, you cannot enforce the validation, not without intentionally killing your page if the user has JavaScript disabled. To cut to the chase, server side validation is ESSENTIAL, where as anything client side, is an optional addition to your validation. You should ideally use PHP to check that every expected key is present, and each keys corresponding value, is of the expected type. As you are working with databases, the importance is increased ten fold, you do not want to open your script up to an SQL injection attack. http://us3.php.net/manual/en/function.mysql-real-escape-string.php Before the days of AJAX, the only established way for client side to communicate with server side, is via the HTTP Post (ie. a form), or the URL query string. As your data is already in a form, your JavaScript validation should either prevent the submission of the form, if the data is invalid, or let it continue as normal. A very basic example: Code
There are others who will be able to better advise you in the field of JavaScript, so I am not going to go into much more detail then that. If you find yourself in a position where you want to pursue the use of AJAX, I can help you with the server side part of the process. It's not particularly different from the normal processing of form data, you validate the POST/GET data, run your database query, output the corresponding updated value. If you have any questions regarding the PHP related details, please feel free to ask. Title: Re: Couple of questions regarding javascript php interaction. Post by: VGR on January 23, 2007, 10:04:16 AM okayyyy I didn't read all of it but I roughly agree. The first idea is the required way to learn about POST forms for a novice (no offense). Be warned though :
- that I don't recommend checkboxes : they are not transmitted if not set (in other words, the value in value="" is transmitted only if checked). The same could be said about radiobuttons, where you usually have to use HTML arrays, something I don't recommend to a novice. It's even worse when you actually ***rerally need*** to use arrays, and you've arrays of radiobuttons... or of checkboxes... - that you ***can*** have a FORM action="someurl?param=something&otherparam=somethingelse etc" method="POST" effectively MERGING $_POST and $_GET data ; in this case (it can be useful) I recommend to have a look at $_REQUEST[] in stead or to take the hebit to use it exclusively to GET and POST. Sometines data can be provided to the same script using an in situ FORM (=POST) or via the access URL (=GET). Use REQUEST or use method="GET" in the FORM or use : $variable=if (isset($_POST['variable']))?$_POST['variable']:((isset($_POST['variable']))?$_GET['variable']:$_GET['variable']:''); and test against '' afterwards this is just a suggestion though - that using HTTP upload can lead to a new set of variables being passed to the $_POST[] ; check out these. the www.php.net/manual/en site and its contributed users notes is perfect for learning PHP "sur le tas" as I did Now, more generally speaking about javascript-to-PHP communication, you've to clearly set up your mind once for good : - PHP is server-side - javascript is client-side - usually you don't ***need*** to communicate between both. - the PHP script GENERATES the javascript code (as the other DHTML output) so you can "pass" values from PHP to the client's browser, but "statically" in a sense. - unless you want to have a dynamic application client-side, restrain javascript to in situ data handling and protection to prevent a round-trip to the server (but still validate finally on the server, of course) - if you want such an applicationclient-side, then use the HTTPrequestObject now admitted by W3C and named "AJAX". You've a marvelous tutorial oin this site on the various ways to use AJAX for what it is useful when programming in PHP : requesting or updating data on the server from the client's web page without having to re-send the whole HTML page. typos are not impossible above regards Title: Re: Couple of questions regarding javascript php interaction. Post by: rdivilbiss on January 23, 2007, 12:58:10 PM Just expanding on the valuable advice given so far:
Quote 1. I have 2 submit buttons with different names and values. For one when it is pressed the data on the form is submitted and stored on a database and for the other, it stores the data base and allows the user to keep entering data. The action script is a php script. Using php is there a way to determine in the action script which button was pressed so that i can perform the necessary action? Yes you can, but I agree this is not a good idea...but my code below does this. One problem will be with form validation. If you use two submit buttons the JavaScript validation script will execute and you won't know which button was pushed, (without some complicated cross-browser event handling code which we don't want to get into.) So the partial submit button we can use just a regular button with an onlick event. NOTE: If the person using your form does not have JavaScript enabled, the submit button will submit the form without passing through validation (which is why you must always validate server side, no matter what) and the partial submit button will not work at all. Quote 2. Say I have a JavaScript which validates a from but the action for the form itself is a php script, After i validate the form, how to i send all the form data to the php script to be stored in the database? Is it AJAX? Answered before by both VGR and Diablo84. All communication from your form back to the form handler (even if the same page) is accomplished by sending the field name value pairs via a POST or on the URL (GET). If JavaScript is enabled you can stop the form from submitting by returning false from your validation script. If no JavaScript...the form will submit without validation. An additional issue, as I mentioned above, is the partial submit button. If your validation required all required fields to be completed before submitting and your partial submit button was in fact a type submit and not a type button, then you could not submit a partial form because your validation would return false. Quote 3. Generally, i will like to know the various means of exchanging data between JavaScript and PHP Again, already answered, but I expanded a little in my example to allow the posted data to be echoed back to the screen and to repopulate the form fields (which you would want to do on a partial submit). NOTE: An often overlooked XSS vector is $_SERVER['PHP_SELF'] which you note I did not use in my example form. Just Google for "XSS PHP_SELF" to see many examples. Basically, if your page is named, myPage.php and your form action is set to $_SERVER['PHP_SELF'] then a malicious person need only type in their browsers address http://www.domain.com/myPage.php/"><script>alert('xss')</script> to inject script into your page. http://www.securityfocus.com/archive/1/archive/1/434294/100/0/threaded (http://www.securityfocus.com/archive/1/archive/1/434294/100/0/threaded) http://forum.hardened-php.net/viewtopic.php?id=20 (http://forum.hardened-php.net/viewtopic.php?id=20) So anyway...my example is just sort of tying together everyone's comments so far. http://www.cafesong.com/test/twoSubmits.php (http://www.cafesong.com/test/twoSubmits.php) Code
Title: Re: Couple of questions regarding javascript php interaction. Post by: VGR on January 23, 2007, 01:46:55 PM saide note : I never did (and am too lazy to) check the value of $_SERVER['REQUEST_METHOD'] when using a FORM set method="POST" but with action="someurl?getparams"
probably tricky to detect Title: Re: Couple of questions regarding javascript php interaction. Post by: rdivilbiss on January 23, 2007, 04:28:43 PM saide note : I never did (and am too lazy to) check the value of $_SERVER['REQUEST_METHOD'] when using a FORM set method="POST" but with action="someurl?getparams" probably tricky to detect Yes, I often do not, it depends on the page. When I have a page which presents a form and then posts it back to itself, then I want to know if I entered the page from a link to the page or by posting the page to itself. Note: I never mix URL parameters with any form. I only use POST. The only possible exception, would be if some parameter was passed to the form from a link prior to presenting the form to the browser. In that case, my logic stands and I would pull the parameters, and write them to hidden form fields so I can pick them up when the form is posted back to itself. For example: Code
FWIW Title: Re: Couple of questions regarding javascript php interaction. Post by: VGR on January 24, 2007, 12:19:48 AM I quickly looked at your code sample. It is what a novice (no offense, again) would have to do. Some remarks
I prefer for efficiency (and clarity) reasons to write Code: <?php $locformfield=""; // init $message=""; if (isset($_POST)) { // posted from same script $error=FALSE; if ($errorcondition) { // set $error and $message accordingly to the failed data validation step } // repeat as necessary if you want to aggregate all error validation messages into $message, or use "else" if you don't. if ($error) { // we will shortly fall through. // take over submitted data for correction $locformfield=$_POST['formfield']; // add stripslashes() it can't do any harm even if not ini_get(gpc_magic_quotes) ; apply strip_tags() also if you want ; warning preg_match() is slow and tedious to build & maintain ; on the contrary, strip_tags() is easy and will allow the basic subset of allowed tags (b, i, u, etc) to be kept // fall-though } else { // no error set, met's go // perform update/insert/partial etc } } // display FORM if ($message<>'') $message="<span class='error'>$message</span>"; echo<<<EOS $message> <form action="$SCRIPT_NAME" method="POST"> <input type="text" name="formfield" value="$locformfield"> </form> EOS; ?> be warned against register_globals=On ; in that case $formvalue will already hold the value of $_POST['formfield']; Title: Re: Couple of questions regarding javascript php interaction. Post by: VGR on January 24, 2007, 12:21:38 AM and redirect to same page (or an other one) at the end of the section named "// no error set, met's go" (typo) if you want to clear out the POST data and prevent re-submitting the data if the user presses F5 ; also solves the "back button" issue IMHO.
Powered by SMF 1.1 RC2 |
SMF © 2001-2005, Lewis Media
Joomla Bridge by JoomlaHacks.com |