...

View Full Version : If client submits value higher than X, then return false



FlashDance
10-10-2011, 04:51 AM
Lets say I have a MySQL value of 4... and I have a HTML INPUT field.. Is there a way to make it so that if a client tries to submit a value higher than 4, then they will be returned a message? Something like:



<SCRIPT type="text/javascript">
function validateForm() {
if (document.forms["form"]["quantity"].value== (+$row['quantity']) {
alert ("Cannot submit because the quantity specified is not available.");
return false;
}
}
</SCRIPT>
<INPUT name="quantity" onsubmit="return validateForm()>

Old Pedant
10-10-2011, 07:46 AM
var maxqty = <?php echo $row["quantity"]; ?>;

function validateForm()
{
if (document.forms["form"].quantity.value > maxqty )
{
alert ("Cannot submit because the quantity specified is not available.");
return false;
}
}

You can drop the PHP value right into the middle of the "if":


if (document.forms["form"].quantity.value > <?php echo $row["quantity"] ?> )

but don't you agree that is hard to read and will be hard to debug later?

Keep the coding neat and simple.

FlashDance
10-11-2011, 11:28 AM
Hi Old Pedant,


I applied the code logic you suggested above into the code I wrote, but it didn't work. When I enter a value that exceeds the value in the MySQL table, the page just goes ahead and submits.
Perhaps I have misinterpreted what you have said?

Javascript:


if (document.forms["form"].quantity.value > $row[sizes]) {
alert ("Cannot submit because the quantity exceeds availability.");
return false;
}


HTML:


<INPUT name="quantity">





but don't you agree that is hard to read and will be hard to debug later?


Personally, I do not. The code is not very long so if one understands how the code is suppose to work then they would not have much code to go over and debug.

Kor
10-11-2011, 11:39 AM
if (document.forms["form"].quantity.value > $row[sizes]) {

The PHP value is not echoed using PHP syntax <?php echo ?>. On the other hand, I doubt that the key [sizes] is PHP defined. Could be


<?php echo $row[$sizes]; ?>

FlashDance
10-11-2011, 11:52 AM
The PHP value is not echoed using PHP syntax <?php echo ?>. On the other hand, I doubt that the key [sizes] is PHP defined. Could be


<?php echo $row[$sizes]; ?>


$row[sizes] is from MySQL

Kor
10-11-2011, 12:13 PM
$row[sizes] is from MySQL
Then make it to be a PHP variable and echo it.

FlashDance
10-11-2011, 12:15 PM
I tried this, but it didn't work.

I tried this, but the page just went ahead and submitted:


Javascript:


function validateForm() {
var integer = parseInt (document.forms["form"]["quantity"].value);
$noavailability = $row['sizes'] + 1;
if (integer > $noavailability) {
alert ("Cannot submit because quantity exceeds availability.");
return false;
}
}

HTML

<INPUT class="quantity" name="quantity" value="1">

FlashDance
10-11-2011, 12:27 PM
This is everything related to the script in regards to the quantity validation.



<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$query = "select * from products where id='$id'"; $result = mysql_query($query); $row = mysql_fetch_array($result);
mysql_query ($query);
mysql_close($link);
?>

<SCRIPT type="text/javascript">
function validateForm() {
if (document.forms["form"]["quantity"].value=="") {
alert ("Cannot submit because a quantity has not been specified.");
return false;
}
var integer = parseInt (document.forms["form"]["quantity"].value);
if (integer > <?php echo $row['sizes']; ?>) {
alert ("Cannot submit because quantity exceeds availability.");
return false;
}
if (document.forms["form"]["size"].value=="") {
alert ("Cannot submit because a size has not been selected.");
return false;
}
}
</SCRIPT>

<FORM action="../../../../cart/addtocart.html" method="post" name="form" onsubmit="return validateForm()">
<DIV>
Add <INPUT class="quantity" name="quantity" value="1"> <SELECT class="size" name="size"><OPTION>Small</OPTION><OPTION>Large</OPTION></SELECT> to <INPUT class="cart" type="submit" value="CART"><INPUT name="id" type="hidden" value="<?php echo $id; ?>">
</DIV>
</FORM>

Kor
10-11-2011, 01:01 PM
Give it a simple echo on the document. See if the variable $row['sizes'] is really defined and it has a value. Or better check with a var_dump() what kind of variable is and which is its structure


<body>
<?php echo $row['sizes'];
var_dump($row['sizes']);
?>

FlashDance
10-11-2011, 03:08 PM
I've decided to start fresh as I have had my code trashed by asking for help on the wrong forum, so I'll explain again from the start:


I am wanting to make it so if a client tries to submit a value in a HTML INPUT form that is higher than a specific value, then JavaScript will deny the form being submitted and return a message to the client.
The value of which the number cannot go over will be variable and be pulled from a MySQL table.

I am thinking the JavaScript and HTML portion of the code being something along the lines of this:



JavaScript:
function validateForm() {
if (document.forms["form"]["quantity"].value > <?php $row['quantity'] ?>) {
alert ("Cannot submit because quantity exceeds availability.");
return false;
}
}

HTML:
<INPUT name="quantity" onsubmit="return validateForm()">


Anyone got any suggestions?

Old Pedant
10-11-2011, 08:29 PM
Bring the page up in your browser.

Click on the VIEW menu of the browser.

Click on the SOURCE or PAGE SOURCE menu item.

You will now be looking at the HTML *as seen by the browser*.

Locate your validateForm function in that HTML.

Copy/Paste what is there in the HTML to here.

Old Pedant
10-11-2011, 08:31 PM
It just occurred to me: Is your JS code in a *separate" xxx.js file??? If so, then of course this won't work. You would have to convert that xxx.js file to xxx.php, as well.

But there's an easier way, if that's the problem.

FlashDance
10-12-2011, 02:42 AM
Hello Old Pedant,


This is the JavaScript source for function validateForm():



function validateForm() {
if (document.forms["form"]["quantity"].value=="") {
alert ("Cannot submit because a quantity has not been specified.");
return false;
}
if (document.forms["form"]["size"].value=="") {
alert ("Cannot submit because a size has not been selected.");
return false;
}
if (document.forms["form"]["size"].value=="Small") {
if (document.forms["form"]["quantity"].value > ) {
alert ("Cannot submit because the quantity exceeds availability.");
return false;
}
}
}


One problem I can see is that <?php $row['sizes'] ?> did not output. When I placed the PHP code inside the HTML it worked, so perhaps I have to brake out of JavaScript or something?


The Javascript (and all the code) is in a single file.

FlashDance
10-12-2011, 02:46 AM
I have found one problem - the function validateForm() isn't even working. I'll look into this now and report back my finding.

EDIT: The form is only not working because <?php $row['sizes'] ?> is producing nothing. When I replace <?php $row['sizes'] ?> with "3", the whole page works!
So, the error lays in getting <?php $row['sizes'] ?> outputting.

Old Pedant
10-12-2011, 02:47 AM
Think you will now have to show the actual PHP code. And now this is purely a PHP problem, nothing directly to do with JS.

Are you possibly ignoring the error(s) you are getting from PHP? Seems to me that's likely the case.

Old Pedant
10-12-2011, 02:48 AM
Of course it's not working. You have a syntax error there where the PHP value is missing. So the function can't compile. So then it can't be called. So then it is doing nothing.

FlashDance
10-12-2011, 03:04 AM
Are you possibly ignoring the error(s) you are getting from PHP? Seems to me that's likely the case.

Your right !!! !!! !!!

Undefined variable: row

This brings me back to what I was saying earlier:
The PHP code that calls the MySQL query sits after the JavaScript. Could this be why?

When I use <?php $row['sizes'] ?> after the PHP-MySQL call (and inside the HTML), it works! However, when I place the PHP-MySQL call code before the JavaScript or at the very top of the document, it still doesn't work.. and the PHP inside the HTML then stops working also. Weird!

Old Pedant
10-12-2011, 03:09 AM
The PHP code that calls the MySQL query sits after the JavaScript. Could this be why?

*OF COURSE*.

If you said that before, I missed it.

The query must be made, the variable must be created and initialized, etc., etc., before it can be used in the page.

THIS IS NO DIFFERENT than any other PHP coding.

You can't do this:


<table>
<tr>
<td><?php echo $row["name"] ;?></td>
<td><?php echo $row["email"] ;?></td>
</tr>
</table>
<?php
$sql = "SELECT name, email FROM table";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
}
?>

And expect the php values to be magically moved from in side the loop to the html, so why would you expect it to be different just because you are plopping values into JS code, instead??

Old Pedant
10-12-2011, 03:11 AM
when I place the PHP-MySQL call code before the JavaScript or at the very top of the document, it still doesn't work.. and the PHP inside the HTML then stops working also. Weird!
Not weird at all. Once you have illegally used the variable, the PHP code is dead. So of course nothing works at that point.

Methinks that a refresher course in PHP is in order.

FlashDance
10-12-2011, 03:26 AM
This is where I have placed the PHP-MySQL code. You say its illegal. I can't understand why? I thought PHP will work anywhere?

This is a chopped n' stripped piece of my code, to show its structure.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<TITLE></TITLE>
<META content="charset=windows-1252;text/html" http-equiv="content-type">
<LINK href="../../../../body.css" rel="stylesheet" type="text/css">
<STYLE type="text/css">
</STYLE>
<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$query = "select * from products where id='$id'"; $result = mysql_query($query); $row = mysql_fetch_array($result);
mysql_query ($query);
mysql_close($link);
?>
<SCRIPT type="text/javascript">
function validateForm() {
if (document.forms["form"]["size"].value=="Small") {
if (document.forms["form"]["quantity"].value > <?php $row['sizes'] ?>) {
alert ("Cannot submit because the quantity exceeds availability.");
return false;
}
}
}
</SCRIPT>
<DIV>
<FORM action="../../../../cart/addtocart.html" method="post" name="form" onsubmit="return validateForm()">
<INPUT name="quantity" value="1">
<SELECT name="size">
<OPTION>Small</OPTION>
</SELECT>
</FORM>

</DIV>

FlashDance
10-12-2011, 03:29 AM
AHH!!!!!!!!!! I found the problem! $id is not declared when I use the PHP-MySQL code at the top! Thats my theory.. Now I will try it and report back.

FlashDance
10-12-2011, 03:34 AM
Yes I was right, but I wouldn't have picked up on that without you.

Thanks Old Pedant! :)

Old Pedant
10-12-2011, 03:36 AM
This is bogus:


<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$query = "select * from products where id='$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
mysql_query ($query);
mysql_close($link);
?>

(1) You are calling mysql_query *TWO TIMES*. The second time you don't assign the value of mysql_query to anything, so (not sure on this) the value of $result and then the value of $row may now bet trashed.
(2) You are closing the database before you are done using it!!!

Old Pedant
10-12-2011, 03:37 AM
Okay, so clearly the $row is still intact despite the second query and the close. Still, not good practice.

FlashDance
10-12-2011, 03:45 AM
(2) You are closing the database before you are done using it!!!

This was the first time I've ever done it. I wanted to see if it would work, and it does. The closing of the database occurs after the last $row is used. I will change it back. Well, actually, I've trashed this document trying to get it working. I'm about to pull a backup and replace it and then re-write in the correct code getting this quantity limiter working, so I'll leave the DB closing SQL string as is. :)

Thanks again Old Pedant! I wish all the best for you!

Old Pedant
10-12-2011, 03:52 AM
The way I would write it:


<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$query = "select sizes, other, fields from products where id='$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$sizes = $row[0];
$other = $row[1];
$fields = $row[2];
mysql_close($link);
?>

Since you are only getting one row, and since surely you aren't using more than a few fields from that row, just go get them and then be entirely done with the DB once you have them.

It just *feels* cleaner to me.

FlashDance
10-12-2011, 04:14 AM
Oh dear! I've spoken way too soon! The code isn't working properly yet. It only worked because I inserted double quotes around the PHP:
if (document.forms["form"]["quantity"].value > "<?php $row['sizes'] ?>")

... but the PHP code still fails to produce the number as can be seen in the source code:
if (document.forms["form"]["quantity"].value > "")

I can confirm however that MySQL is working, as everything else that uses PHP-MySQL works. So, I think this is an issue with the way "<?php $row['sizes'] ?>" is being implemented. Any suggestions?

Old Pedant
10-12-2011, 04:17 AM
SHOW YOUR CODE.

And maybe also see my post #26.

I'm betting that indeed $row['size'] used after the DB close is bogus.

But I don't use PHP, so it's just a guess.

FlashDance
10-12-2011, 04:23 AM
SHOW YOUR CODE.
And maybe also see my post #26.
I'm betting that indeed $row['size'] used after the DB close is bogus.
But I don't use PHP, so it's just a guess.

There was an error in the code where a semicolon was missing, but even fixing that didn't solve anything. PHP does not give me any error.

I saw your example in post #26, but I don't feel comfortable writing like that.

Old Pedant
10-12-2011, 04:27 AM
I saw your example in post #26, but I don't feel comfortable writing like that.

And I don't feel comfortable writing any other way. It's the most efficient and compact and error-free way to do things like this. Whether in PHP or ASP or JSP. Or even in C# VB.NET or C++ or Pascal or PL/1 or C or ... (going back in my languages history in rough reverse order).

And if you won't show your current entire page's code, I can't offer anything else.

FlashDance
10-12-2011, 04:34 AM
I cannot show you the source because this forum has a technical limitation:


The text that you have entered is too long (33091 characters). Please shorten it to 20000 characters long.

FlashDance
10-12-2011, 04:35 AM
The source can be seen here:

http://pastebin.com/VH6JxSMQ

Old Pedant
10-12-2011, 04:44 AM
My head hurts.

And you say that the data in lines such as these:


<B>Name:</B> <?php echo "$row[name]"; ?>
<BR>
<B>Brand:</B> <?php echo "$row[brand]"; ?>
<BR>
<B>Primary colour:</B> <?php echo "$row[primarycolour]"; ?>

is okay???

Maybe time to DEBUG?


<?php
$id = "1";
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$query = "select * from products where id='$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

echo "<hr>DEBUG row[sizes] is " . $row["sizes"] . "<hr>";
?>

I'm beginning to get suspicious that either there is no field of that name in the row or maybe the value really *is* blank.

FlashDance
10-12-2011, 04:53 AM
LOL OMG! I'm a total tool! I DO NOT understand how I missed this!

<?php $row['sizes']; ?>
should have been:
<?php echo $row['sizes']; ?>

Solved.

Old Pedant
10-12-2011, 04:54 AM
You know, if you would avoid doing select * and more correctly list only the fields you need, you'd get an error message if one of the listed fields isn't spelled correctly.

THat is:


$query = "select sizes,name,brand,primarycolour,material,madein,price,sizem,sizel,sizexl "
. " from products where id=$id";


Your <DIV class="sizeavailability"> looks broken, to me.

As written, if you get zero for sizes then none of the other sizes will be shown.

I'd bet that it really should be written thus:


<DIV class="sizeavailability">
<?php
$sizes = $row["sizes"];
$sizem = $row["sizem"];
$sizel = $row["sizel"];
$sizexl = $row["sizexl"];
if ($sizes != 0) echo '<DIV class="sizesmall"><B>Small:</B> ' . $sizes . '</DIV>';}
if ($sizem != 0) echo '<DIV class="sizemedium"><B>Mediuml:</B> ' . $sizes . '</DIV>';}
if ($sizel != 0) echo '<DIV class="sizelarge"><B>Large:</B> ' . $sizes . '</DIV>';}
if ($sizexl != 0) echo '<DIV class="sizeextralargel"><B>Small:</B> ' . $sizexk . '</DIV>';}
// UTTERLY BOGUS: Why do you do this? mysql_query ($query);
mysql_close($link);
?>
</DIV>

Old Pedant
10-12-2011, 04:55 AM
LOL! Well, I stared at it, too.

Personally, I think it's one good reason to enable "short tags".

SO that you can do simply <?= $row["sizes"] ?>

and not need "php" or "echo" or the semicolon.

FlashDance
10-12-2011, 04:59 AM
In my 1.5 month coding experience, I've learned that anothers style of coding is a personal trait. The same way someone organizes their room. They organize it to their personal taste.
Coding is no different.

I just validated my page using W3's validator and the page came out valid. :D


One thing I am going to look into later on though is getting that huge Javascript code shrunk. Its 30Kb worth of code just for that function. I'll be hosting this site from home probably with ADSL2+ Annex M, so 30Kb for just a HTML document is going to hurt.
I'll look into this later though. If I don't continue to build, I lose motivation. Optimizing code will kill motivation. lol

FlashDance
10-12-2011, 05:03 AM
LOL! Well, I stared at it, too.

Personally, I think it's one good reason to enable "short tags".

SO that you can do simply <?= $row["sizes"] ?>

and not need "php" or "echo" or the semicolon.

Its not PHP5 compliant.

Old Pedant
10-12-2011, 05:16 AM
Its not PHP5 compliant.

Well, I'll believe you. But I can't find any place in the PHP5 docs where it says that it is incompatible. No mention of it in deprecated features, for example.

Anyway, that's a personal preference (comes from my ASP and JSP days...both allow <%= as a short hand for <% response.write or equivalent. And I really like it, a lot.

I see a lot of discussion in the PHP docs about short tags interfering with the <?xml...?> declarations. Thank goodness ASP and JSP got it right, using <%...%> instead.

FlashDance
10-12-2011, 05:46 AM
Ahhh, you can see the compliance statement here:

http://www.php.net/manual/en/language.basic-syntax.phpmode.php



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum