how can i generate dynamic hidden values in a form - php

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.

with the date ?
Date.getTime();

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.

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

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.

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());
?>

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

Related

passing variable to PHP through javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I'm kinda new to working with JS and PHP and stumbled upon a little problem. Im trying to pass the ID of a textbox I clicked through to PHP and then query a database with that ID. I tried the following code to check if the variable gets passed on, but nothing is alerted:
<script type="text/javascript">
function Like(ID)
{
<?php
$id = ID;
print "alert('$id');";
?>
}
</script>
<input type="text" id="1" onclick="Like(this.id)" >
What I'm trying to accomplish:
I've got a database of videos with a unique ID. I have 2 buttons next to each video for either liking or disliking. The 2 buttons will have an id based on the ID of the video. For example video number 2 has 2 buttons: like(id=L2) and dislike(id=D2). When the user clicks either one of those buttons, I want to update the videos table's "likes" column without the page reloading. Would that be possible?
You aren't going to be able to do this the way you have written it. PHP runs once on page load. So, when you click the input, your function will already be evaluated by php as this:
<script type="text/javascript">
function Like(ID)
{
alert('ID');
}
</script>
The ID is a bareword to php, so it treats it like a constant if defined, or a string (and may generate a warning). Assuming you don't have a contant ID, then it prints the alert line with the string "ID" in the $id variable.
By the time your javascript is called, all you will ever get is alert('ID').
To query a database, you have to pass the data back to the server. This will either load a new page, or if you want it to happen without a page load, you need to make the call to the server asynchronously (in the background), and modify the page based on the result. This is called AJAX. You will need to understand how server-code (php) and client-code (php) work, and then you will better be able to understand how AJAX brings those together to do what you want.
Since you asked this in a comment:
Well, I've got a database of videos with a unique ID. I have 2 buttons next to each video for either liking or disliking. The 2 buttons will have an id based on the ID of the video. For example video number 2 has 2 buttons: like(id=L2) and dislike(id=D2). When the user clicks either one of those buttons, I want to update the videos table's "likes" column without the page reloading. Would that be possible?
I'll tell you a way to achieve it, and it doesn't even require Javascript! :) (at least at first).
It's an old fashioned HTML form element. Since you'll be posting data you should use action post. The code can look like this:
<form method="post" action="/requests/like-video/" class="like-video">
<div>
<input type="hidden" name="video_id" value="<?php echo $video->id ?>">
<input type="submit" value="Like">
</div>
</form>
<form method="post" action="/requests/dislike-video/" class="dislike-video">
<div>
<input type="hidden" name="video_id" value="<?php echo $video->id ?>">
<input type="submit" value="Dislike">
</div>
</form>
Once you have that in place (and working) it's just a matter of hijaxing those forms. A super easy way of doing that is to use jQuery's Form plugin and simply run:
$('form.like-video').ajaxForm(OPTIONS_GO_HERE);
$('form.dislike-video').ajaxForm(OPTIONS_GO_HERE);
Doing it this way ensures users without JS also get a fully functional site.
It's called progressive enhancement.

Simple Calculator without page reload

I have two input boxes, the first input box will accept a value that will be subtracted from the value stored in a cookie. The second input will auto generated the difference while I am typing.
What is the best solution for this?
The best solution is to use vanilla Javascript only.
You can read cookies directly from Javascript:
http://www.quirksmode.org/js/cookies.html
You can make the second input un-editable using readonly attribute:
http://www.w3schools.com/tags/att_input_readonly.asp
You can do math directly in the onkeyup event of the first input:
http://www.w3schools.com/jsref/event_onkeyup.asp
Hook the keyup and mouseup events on the first input box. In the handler do parseInt() on its value, if !isNaN() calculate the difference and write it to the second input box.
I don't see, why you would need ajax for a subtraction!
As cookies can be created, read and erased by JavaScript you can accomplish this task using javascript. As Eugen Rieck points out you can use keyup/down events.
You only need Javascript. Use Serverside (PHP|PYTHON|JAVA|PERL) only if you need to store it on server. Or wants to show results to other people.
For your case , server side is only needed If you want to:
Store it on the server so other people can see it.
Multi User subtraction ?
Log what visitor did.
<script>
function subtract(first, second)
{
total = first - second;
obj("total").value = total;
}
function obj(id)
{
return document.getElementById(id);
}
</script>
<input type="text" id="first" onkeyup="javascript:subtract(this.value, obj('second').value)" />
-
<input type="text" id="second" onkeyup="javascript:subtract(obj('first').value, this.value)"/>
=
<input type="text" id="total"/>

Checkbox that submits form on click

I'm using Codeigniter and wants to know how I can make a checkbox that submits the form on click?
Secondly, this checkbox will be one of several checkboxes that will act as a filter like products > $20, products < $30, how do i pass it in the url? I'm thinking /1+2+3
Haven't worked with Codeigniter much, but I can answer how to make the form submit on checking the checkbox with JS:
<form id="something">
<input type="checkbox" name="foo" id="foo" value="yes" />
</form>
<script type="text/javascript">
$("#foo").click(function() {
if ($(this).is(":checked"))
$("#something").submit();
});
</script>
The javascript questions seem to have been solved already; let's step to the codeigniter ones.
You can pass the url in one of those two ways.
Idiomatic but limited: as /1/2/3/4/etc. The controller function handling that url could both use func_get_args to read them or, if you already know how many parameters will be passed at the most, give a default value of null to all non-necessary paramenters;
Not Codeigniterish but seriously better for search parameters: enable the query strings on your config file, pass arguments as you would normally with GET (min=2&max=3 and so on) and get their value with CI's input class ($min = $this->input->get('min')).
This has nothing to do with PHP, nor CodeIgniter. The solution is to submit the form in the onclick event of the element.
<input type="checkbox" name="filterx" onclick="document.forms[0].submit()" />
You can use the OnSubmit event of the form to nicely format the url, if you like.
To do this, you can
get the values of all desired elements,
build a nice url from it,
set the url using location.href = yourniceurl,
cancel the regular submit by returning false.
Note that both solutions require javascript to be enabled. So it is a good thing to have other means of submitting the form (submit button). Don't rely on submitting by pressing Enter. Opera will use the Enter key for toggling the checkbox instead of submitting the form.
If you like, you can hide the submit button using Javascript, that way, users having Javascript will have their form auto-submitted, while users without can use the button.
You will need to make sure that your server side form validator not only accepts the nice url, but the ugly url (which posts values like ?filterx=on) too.

Clearing a selected item from a dropdown using PHP

I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to onclick() and receive the event on the server side, then you will need to use an AJAX call. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.
you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html
use jquery
jquery auto suggestion

Accessing text in a field placed by JS, via PHP

In PHP, in a particular CMS I am using a custom field, which works like google suggest.
As in, for each letter I type an SQL query is performed and matching records are displayed. When clicking on a record it fills the field with that record.
I am fairly certain this is all done with JavaScript.
I need to know how I can access the resultant content of that field, with the text placed through JS, before it is submitted so I can explode() it.
The CMS I am using is using mootools, so a solution relying on mootools would be ideal.
(This answer assumes that you have control over the markup of your forms (the form that requires a string "explosion" before submit) and/or you feel comfortable tinkering with whatever plugins you're using.)
first, make sure that you aren't submitting your form using an actual submit button (). We'll need to submit the form using javascript after fiddling with the field's contents.
next, make sure that your input box (the one you're grabbing text from) and your hidden inputs have unique ids. This will make it easier to query the DOM for the data we need.
Inside your form, in place of a "real" submit button, create a form button:
<form action="something.php" name="myform">
<input type="hidden" id="hiddenItem">
// SOME STUFF
<input type="text" id="autocomplete_field" value="whatever"/>
// SOME OTHER STUFF
<input type="button" value="Submit" onclick="processForm(this)"/>
</form>
Then, write a javascript function to process the string and submit the form:
processForm = function(el){
text = $('autocomplete_field').get('value');
// Lets assume the strings separates words (what you're exploding apart) using spaces
// something like 'DOGS CATS BIRDS PETS'
var array = text.split(' ');
// returns ['DOGS','CATS','BIRDS','PETS']
$('hiddenItem').set('value',array[0]);
// #hiddenItem now has the value 'dogs'
//SUBMIT THE FORM
el.getParent('form').submit();
};
Hope this helps!
You could try to use JS to send the field on some event (onkeyup?) to your php script. After it does it's part, store the result as a session variable and you can retrieve that later.
Try using jquery's get function.
Was that your question?

Categories