eMRe
eMRe

Reputation: 3247

how can i generate dynamic hidden values in a form

I have got a shopping cart which is build using jquery and php. and I need to generate hidden values for item id. Every time I click add, the value must be different.

I do not know how to create dynamic values which will be different on each click.

At the moment I created with php the following code.

            <form method="post" action="" class="jcart">
            <? $unique = md5(uniqid()); ?>
                <input type="hidden" name="my-item-id" value="<?=$unique;?>" />
                <input type="submit" name="my-add-button" value="add to cart" class="button" />

            </form>

The problem is unless I refresh the page I'm getting same hidden value. What can I do to get different values without refreshing the page.

Upvotes: 0

Views: 365

Answers (6)

Corey
Corey

Reputation:

Try uniqid() http://php.net/manual/en/function.uniqid.php

Upvotes: 0

Paul
Paul

Reputation: 1545

I think you may need to use jQuery load() function and have a PHP page that generates the md5() id for you like this:

<script>$('input[type=hidden]').prev().load('ajax/uniqueId.php');</script>

the jQuery would be placed next to the Add button.

And your PHP page would look like this...

<?php

echo md5(uniqid());

?>

Upvotes: 0

lebowski
lebowski

Reputation: 1

If the value can be random, you could use a javascript time call like getTime() that will get the number of milliseconds since 1972. It's not likely you'll get a duplicate ID, but you could append a random number to it to be sure.

The best approach would be to use an Ajax call (via jquery) to your server and get the ID from the server.

Upvotes: 0

omars
omars

Reputation: 8694

if you are adding using ajax, set it in the return of the ajax call

Upvotes: 0

Marc B
Marc B

Reputation: 360592

You could store a simple integer in a cookie and use that as the basis for an incrementing counter to generate that "unique" value. As long as you take care to not have multiple 'add' scripts running at the same time and make sure your cookie updating code is bulletproof, it should take care of the uniqueness problem.

Upvotes: 0

Ben
Ben

Reputation: 278

with the date ?

Date.getTime();

Upvotes: 1

Related Questions