I am having a form inside a php script. I am doing the validation using javascript.
<?php
$con = mysql_connect("servername","login","passsword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbadminatms", $con);
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
$sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
VALUES
('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
$emailID = $_POST['email'];
$postedBy = $_POST['name'];
$message = $_POST['comments'];
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
}
}
else
{
echo '
<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">
<p id="errorMsg">All fields are required</p>
<label for="name" class="label" id="nameLabel">Your name: </label><input id="name" type="text" size="30" name="name" class="field"/>
<br /><br />
<label for="email" class="label" id="emailLabel">Your Email id: </label><input id="email" type="text" size="30" name="email" class="field"/>
<br /><br />
<label for="comments" class="label" id="commentsLabel">Comments:</label>
<div id="commentsSection">
<textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>
</div>
<p><input type="submit" value="Submit" id="submit"/> <input type="reset" /></p>
</form>';
}
mysql_close($con);
?>
Everrything’s is working fine but I can’t validate the form using javascript.
The relevant excerpt is:
Two things:
Your use of double quotes within the attribute will end it prematurely (the browser will only see
onsubmit="javascript:return validate(", which is invalid and will be tossed by the JavaScript interpreter). Use single quotes instead within the attribute value:Do you actually have a JavaScript function called
validatethat’s included in the page somewhere, either directly or via an external JavaScript file?Separately, note that if you use
onsubmit, you don’t usejavascript:at the beginning, just:The
javascript:pseudo-protocol is only used where the HTML would normally contain a link, as with thehrefattribute of anchors.onsubmitand similar don’t accept links, just JavaScript code, so you don’t use it. (It’s largely harmless if you do, because coincidentally it looks like a label in JavaScript, and so the code parses okay and runs. But it’s wrong.)Off-topic, but important: NEVER rely on client-side validation; client-side validation is purely a user experience improvement exercise (helping people send you things you’ll accept), never a replacement for server-side validation. Your PHP code as quoted is wide open to SQL injection (or even innocent issues — what happens if there’s a
'in one of the fields, for instance?). Search for “SQL Injection PHP” to find lots of way so correctly process submitted data.