Detect how many times the users have click the button - php

Just want to know if there is a way to detect how many times a user has clicked a button by using Jquery.
My main application has a button that can add input fields depend on the users. He/She can adds as many input fields as they need. When they submit the form, The add page will add the data to my database. My current idea is to create a hidden input field and set the value to zero. Every time a user clicks the button, jquery would update the attribute of the hidden input field value. Then the "add page" can detect the loop time. See the example below.
I just want to know if there are better practices to do this. Thanks for the helps.
main page
<form method='post' action='add.php'>
//omit
<input type="hidden" id="add" name="add" value="0"/>
<input type="button" id="addMatch" value="Add a match"/>
//omit
</form>
jquery
$(document).ready(function(){
var a =0;
$("#addMatch").live('click', function(){
//the input field will append //as many as the user wants.
$('#table').append("<input name='match"+a+"Name' />");
a++;
$('#add').attr('value', 'a'); //pass the a value to hidden input field
return false;
});
});
Add Page
$a=$_POST['a']; //
for($k=0;$k<$a;$k++){
//get all matchName input field
$matchName=$_POST['match'.$k.'Name'];
//insert the match
$updateQuery=mysql_query("INSERT INTO game (team)
values('$matchName')",$connection);
if(!$updateQuery){
DIE('mysql Error:'+mysql_error());
}
}

I'm a bit confused. After this:
$('#add').attr('name', 'a'); //pass the a value to hidden input field
shouldn't you actually store the value of a?
$('#add').attr('name', 'a').val(a);

$('#add').attr('name', 'a').val(a); ????
That's not correct, you should use:
$('#add').attr('value', a);
send the content of the "a" variable to the "value" property of element with ID "add"
I do believe that's what you want to do....

Related

PHP Form, collect several input on single input fields

Okay the title might be confusing, as i myself still confused as how to phrase it.
Hi, i am a beginner in PHP, and definitely no experience in js or other languages.
I'm trying to make an input type (datalist), where when the user press enter, or select the options from the list, de input would passed into an array, then displayed as static text next to the original input field, while the original input field would be emptied, allowing user to type/select another option, and when the user chose other option/press enter, the new value would be added to the array. And then when the user click the submit button, the whole array of that field would be then passed as POST.
Well if my explanation still confusing, just imagine those sites where you can submit an articels, and we can type/chose the 'tags' for the articles.
I heard tou have to implement js on this one, can anyone please help explain it to me? I would really appreciate it
Thankyou
A way of doing that would be to setup a form with the input paired with a button plus divs for appending the user's input and then going through the logic below
the user inserts a value into the input and clicks a button
The button click activates a jquery event where the function obtains the user input
It then checks if the value is empty and then appends the value in a <p> tag to the display div and an input of type hidden to the hidden div with the name attribute as name[].
Later when you submit the form you can obtain the values using the names[] variable which will store them as an array. You can edit this to anyway you want.
For the html
<input id="name" name="name" type="text"/>
<font size="1">Add Name</font>
<div id="display"></div>
<div id="hidden"></div>
And then for the javascript
// Add name
$("#add_name").click(function (e) {
//prevent submit of form
e.preventDefault();
var name = $('#name').val();
//check if input is empty
if(name){
$("#display").append("<p>" + name + "</p>");
$("#hidden").append("<input type='hidden' name='names[]' value='" + name + "'>");
} else {
alert("Please insert name before submitting")
}
$('#name').val("");
});
Let me know if it helps or if i can help you further

Pass table value to a form on button click

I am new here and also don't know PHP.
I have got a project in which there is a table containing a Buy button in one cell and its value in another cell.
I want it like that, when the user clicks on "BUY", it's value gets passed to a contact form.
Like for example: ?buyrate={value from table cell}
I have got the form working to receive the value from the URL.
Eg: ?buyrate=25 . The form field gets the value 25.
But i dont know how to get the value from the cell, so that the admin can be able to change the Value and doesn't need to change the Button URL every time.
Please help anyone.
Thanks
Since you are already getting buyrate from the URL (I assume from a $_GET ie $buyrate = $_GET['buyrate'];), why don't you simply use that value in your button code, like such:
<input type="submit" name="buyrate" value="<?php echo $buyrate; ?>" />
Without seeing code, we're not sure what else you want to submit, but this should pass that value to whatever your form action is.
you need to send data via jquery to contact form like
//include jquery.js here
<script>
$(document).ready(function(){
$('#but').click(function(){
var val=$('#v').html();
window.location.href="somepage.php?buyrate="+val;
});
});
</script>
<table>
<tr><td id="but"><button value="Buy" /></td></tr>
<tr><td id="v">60</td></tr>
</table>
//this is just an example you can modify the code as per your conditions and requirements.

Calculating values in PHP with buttons

I am creating a calculator in PHP and I should have this kind of structure of my HTML, where my numbers are clickable buttons, and the number that has been first clicked will be the first value and the second number I click will be the second value. I have no idea on how its gonna work, is it possible? if so how here's my code
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id = "structure">
<?php
if(isset($_GET)){
$value += $_GET;
}
?>
<form method = "GET " action = "calculator.php">
<input type = "submit" name = "one" value = 1>
<input type = "submit" name = "two" value = 2>
<input type = "submit" name = "three" value = 3>
<input type = "submit" name = "operand" value = "+">
</br>
<input type = "submit" name = "four" value = 4>
<input type = "submit" name = "five" value = 5>
<input type = "submit" name = "six" value = 6>
<input type = "submit" name = "operand" value = "-">
</br>
</form>
</div>
</body>
</html>
I haven't put all the numbers in the calculator for posting purposes
As others mentioned, the best way to do this is to use Client-side coding (Javascript). However, if you have to write a PHP code, then you need to submit the form twice. The first time, put the input variable (first number) in a hidden input element of the form and have print the html again this time with the extra hidden input element. The second time, look for that hidden input value: if it exists then it means that the new input is the second number and the hidden input is the first number. Get the value of the hidden input, get the new number, add them together and display the results. Make sure you reset the hidden input value.
Since this is a book exercise and the point is for you to write the code, I'm not going to give you any code. But, I can point you in the right direction (or at least one of them).
Consider using some kind of value that can be sent with each request that stores the current accumulated value of all operations. This probably should be displayed somewhere and also placed in a field that PHP will be able to read on form submit (Hint: have you ever heard of the hidden input type?). How will you keep track of the last operation? Maybe you could use another one of these fields to store the operation until another button is pushed.
What code can you use to check if the form is submitted? How can you check which button is pushed. Which values will be set if + is pushed? How about if a number is pushed? What if multiple numbers are pushed in a row?
More things to consider: Try playing with a real calculator. When are results displayed? What order of operations is used? Every operation has a left hand side and a right hand side. What happens when you push multiple numbers in a row. What about decimals? Should there be a clear button?
You'll need a way to keep track of previous inputs. Every time you click a button, a request gets sent to the server with that info (in $_GET) but the old inputs are no longer available. A few methods:
Hidden form elements
Each time the user clicks, you read the value and output it back into the page in a hidden form element. Each time you have to read the value of the hidden element using your existing method with $_GET, figure out what you need to do mathematically, and save the old stuff and new stuff into the hidden element again for the next input.
See this page for an example.
Cookies
You can use setcookie to set a cookie with the value the user entered. Each time the user clicks a button, you want to load the value from the cookie and append the current input. When the user clicks the = button, you load the cookie data and parse the expression. You make it easier and store the parts of the expression in some kind of delimited string in the cookie so you have operand,operator,operand and then you can easily compute the result. Hitting a clear button would clear the value of the cookie.
This tizag tutorial is a pretty good example of what you want to do with cookies.
Javascript
Obviously the easiest way. Since the state will be maintained, you don't need to pass values back and forth.

How to identify if the submitted value came from the autocomplete script?

In my form there is a textbox and submit button. When a user starts typing, after the 3rd letter the autocomplete script does it's magic.
There are two possibilities.
The user types a word, there are matches and he clicks on one match. This selected match is added to the textbox and then hits the submit button.
The user types a word, there/there are not matches but he decides to hit the submit button without selecting one of the suggested.
My question is how can I identify whether he hit the button in case 1 or in case 2.
rpc.php is the file that looks for suggested values through the mySQL.
A solution is to check the string if there is on the database but I do not want this.
Another solution is to transform the jQuery script and php code that shows the product name and instead of putting the product in the textbox, it should take him to the results page. This solves my problem also.
<script type="text/javascript">
$().ready(function() {
$("#s").autocomplete("rpc.php", {
width: 250,
selectFirst: false,
minChars: 3,
scroll:true,
matchContains: true,
scrollHeight: 250
});
});
</script>
<form method="get" action=".php">
<input type="text" name="s" id="s" class="inputsearch">
<input type="submit">
</form>
Use autocomplete's change method to set a flag in the form, eg
/// Create an hidden element to store the flag value,
/// 1 for AC used, 0 for user entered
var flag = $("<input>").attr("type", "hidden")
.attr("name", "ac_flag")
.val(0);
// append flag to form
$("form").append(flag);
$("#s").autocomplete("rpc.php", {
change: function(event, ui) {
flag.val(ui.item != null ? 1 : 0);
},
// and the rest
});
The "change" event fires when the value in the text field changes. When an AC item is chosen ui.item will contain an object reference to the selected item from the list. If no selection was made, ie the user simply entered text, ui.item will be null.
Your form handler can then check for $_GET['ac_flag'] to determine whether or not the value came from the autocomplete list.
Quick mockup example here - http://jsfiddle.net/9GQgh/
The simplest approach would be to modify the autocomplete plugin itself to set a flag when the user chooses a value from it, and clear it when the user modifies their selection. The flag could be anywhere, but for the sake of simplicity I'd suggest a hidden form field, like:
<form method="get" action=".php">
<input type="text" name="s" id="s" class="inputsearch">
<input type="hidden" id="flag" name="inputCameFromAutocomplete" value="false">
<input type="submit">
</form>
So in the autocomplete plugin, when the user makes a selection, you could add something like:
$("#flag").val("true");
If you wanted to you could make the id/selector of the flag element part of the plugin config/options so that it is more reusable.
You would also want to do something like:
$("#s").keypress(function() {
$("#flag").val("false");
});
...as part of your initial setup, so that the flag is reset whenever the user manually types something into the field.

how can i get values from multiple forms and submit them?

I have several forms inside DIVS on my page.
I have one form which contains a text field and is always visible, and this is where the user hits 'enter' key and submits...
I want to get values selected in the other forms on the page, and submit them all together, not one by one, so that my PHP code can use "ALL VALUES" and search a mysql database...
Is this possible by javascript using the "<form onsubmit>" to call a javascript?
any codes would be appreciated...
thanks
Without some Javascript hocus-pocus, you can't. One form = one request.
You can do it with JS, and you have a few options. The easiest would be to loop through all the forms on the page, and basically duplicate all the input fields and values into one form and then submit that combined form.
With jQuery it'd go something like this:
$("form").submit(function() {
combineAndSendForms();
return false; // prevent default action
});
function combineAndSendForms() {
var $newForm = $("<form></form>") // our new form.
.attr({method : "POST", action : ""}) // customise as required
;
$(":input:not(:submit, :button)").each(function() { // grab all the useful inputs
$newForm.append($("<input type=\"hidden\" />") // create a new hidden field
.attr('name', this.name) // with the same name (watch out for duplicates!)
.val($(this).val()) // and the same value
);
});
$newForm
.appendTo(document.body) // not sure if this is needed?
.submit() // submit the form
;
}
You need to make a script which will collect the data from the forms, and inject them into the only form that is visible. Only one form will be submitted, you can not submit multiple forms.
You can create multiple hidden fields, or you can construct a single hidden field in that form, then use javascript to collect all the data from the various forms, then create a JSON string, set the value of the hidden one, and submit.
Edit:
Say you have a single hidden input like this:
<input type='hidden' name='hiddenfield' id='hiddenfield' />
you could use JQuery to do this:
$('#hiddenfield').val('myvalue');
To get the value from other forms is as simple as calling $('#elementid').val()
before form submission. To use JQuery, go to the jquery website, download the library, and link it (follow their installation guide).
you can add an onsubmit to that form, and then collect other values with javascript:
<input type="hidden" name="hidden1" id="hidden1" />
<input type="hidden" name="hidden2" id="hidden2" />
<script>
document.getElementById("the_form").onsubmit = function(){
document.getElementById("hidden1").value = document.getElementById("other-field1").value;
document.getElementById("hidden2").value = document.getElementById("other-field2").value;
};
</script>
Wrap the whole Page in your form tag (if possible) and use the server side code, along w/ Javascript, to handle your business rule validation.
kind of a hack solution, but it should minimize the necessity for Javascript "hacks" depending on your skill level with javascript.

Categories