Navigate
Home
ArticleWiki
Forum
Journal
Search
Newsletter
Links
Tech News
expertsrt.com
Welcome Guest.
Username:

Password:

Remember me

Couple of questions regarding javascript php interaction.
Welcome, Guest. Please login or register.
December 04, 2008, 12:06:13 AM
11306 Posts in 1249 Topics by 499 Members
Latest Member: haulaslemycle
Experts Round Table Network  |  Serverside Technology  |  PHP  |  Couple of questions regarding javascript php interaction. « previous next »
Pages: [1]
Author Topic: Couple of questions regarding javascript php interaction.  (Read 255 times)
thepreacher

Offline Offline

Posts: 78


« 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
Logged
Diablo84

Offline Offline

Posts: 6


« Reply #1 on: January 23, 2007, 05:51:48 AM »

First and foremost, add the following to a separate PHP file:

Code
Language: php (GeSHi-highlighted)
<?php
if (isset($_POST['myinput'])) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
?>
 
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="myinput" value="test">
<input type="text" name="myinput2" value="test2">
<input type="submit" name="Submit" value="Submit">
</form>

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
Language: php (GeSHi-highlighted)
<?php
if (!empty($_POST)) {
if (isset($_POST['mycheck'])) {
 echo "Checkbox is checked";
 //do this
}
else {
 echo "Checkbox is NOT checked";
 //do this instead
}
}
?>
 
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="myinput" value="test">
<input type="checkbox" name="mycheck" value="1">
<input type="submit" name="Submit" value="Submit">
</form>

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
Language: javascript (GeSHi-highlighted)
<script language="JavaScript">
function validateForm() {
if (document.getElementById('myinput').value != 'test') {
 return false;
}
return true;
}
</script>
 
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onSubmit="return validateForm()">
<input type="text" id="myinput" name="myinput" value="test">
<input type="submit" name="Submit" value="Submit">
</form>

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.
« Last Edit: January 23, 2007, 05:53:44 AM by Diablo84 » Logged
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #2 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&amp;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
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #3 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://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


Code
Language: php (GeSHi-highlighted)
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
if (isset($_POST["submit1"])) {
if ($_POST["submit1"]=="Submit") {
echo("perform logic for a full submit<br>");
}
} else {
echo("perform logic for a partial submit<br>");
}
$myinput = $_POST["myinput"];
$myinput2 = $_POST["myinput2"];
 
// we retieved the values of the form field posted BUT
// this is tainted information we can not trust.
// Also, magic quotes may be enabled, and for example
// if someone submitted their name as O'Brian, it may now be
// O\'Brian.  So, to get the actual values we may need to
// strip the slashes added by magic quotes.
if (get_magic_quotes_gpc()) {
$myinput = stripslashes($myinput);
$myinput2 = stripslashes($myinput2);
}
// Finally, before echoing those values back to the screen
// or to the form, we need to filter for malicious data.
$regExPattern = "/^[a-zA-Z0-9\-\'\ \,\.]+$/";
preg_match($regExPattern, $myinput, $arr);
// if $arr is empty you have illegal characters.
if (empty($arr)) {
$myinput="";
}
preg_match($regExPattern, $myinput2, $arr);
if (empty($arr)) {
$myinput2="";
}

echo("myinput=$myinput<br>");
echo("myinput2=$myinput2<br>");
} else {
// first time displaying the page or a refresh
$myinput = "";
$myinput2 = "";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>2 Submits</title>
<script type="text/javascript">
<!--
function validate(oFrm) {
if (oFrm.myinput.value=='') {
alert('Please enter a value for the first field');
return false; // prevent the form from submitting
}
if (oFrm.myinput2.value=='') {
alert('Please enter a value for the second field');
return false; // prevent the form from submitting
}
return true; // let the form be submitted to twoSubmits.php
}
 
function doPartial() {
// submits a partially completed form - skips validation
document.frm.submit();
}
//-->
</script>
</head>
 
<body>
<form name="frm" method="post" action="twoSubmits.php" onsubmit="return validate(this)">
 <input type="text" name="myinput" value="<?=$myinput?>"><!--<<< data from PHP returned to form--><br>
 <input type="text" name="myinput2" value="<?=$myinput2?>"><br>
 <input type="submit" name="submit1" value="Submit">
 <input type="button" name="submit2" value="Partial" onclick="doPartial();">
</form>
</body>
</html>
« Last Edit: January 23, 2007, 01:19:13 PM by rdivilbiss » Logged

Rod
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #4 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
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #5 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
Language: php (GeSHi-highlighted)
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$myinput = filter($_POST["myinput"]);
$myinput2 = filter($_POST["myinput2"]);
       $param1 = filter($_POST["param1"]);
} else {
// first time displaying the page
       $param1 = filter($_GET["param1"]);
$myinput = "";
$myinput2 = "";
}
 
function filter(pItem) {
 // some filter function her to handle tainted data and magic quotes.
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Called with Params</title>
</head>

<body>
<form name="frm" method="post" action="myPage.php">
 <input type="text" name="myinput" value="<?=$myinput?>"><br>
 <input type="text" name="myinput2" value="<?=$myinput2?>"><br>
 <input type="submit" name="submit1" value="Submit">
 <input type="hidden" name="param1" value="<?=$param1?>">
</form>
</body>
</html>

FWIW
Logged

Rod
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #6 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'];
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #7 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.
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
Pages: [1]
« previous next »
    Jump to: