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.
Related
I'm using Javascript to create more form fields, to be more specific I'm using jQuery append() to create copies of form fields I already have when a button is pressed.
For example there is an exercise form field, then when someone presses the + button they get another form field to add a second exercise. Now I have to get all these exercises into a PHP file, with no limit so someone could add a 1000 exercises and they would all get sent to my PHP.
I have it setup so jQuery gives them all a name tag with exercisex, the 2nd x being the number of the form field, so the original is exercise1, the second one exercise2, etc.
Now I submit the form and it gets send to another file, submitted.php.
In this file I have it setup for the original form field like this:
$exercise1 = $_POST['exercise1'];
and to put it in an array
$arrExercise = array (
>"exercise1" => $exercise1 );
What I'm looking is for a way that PHP automatically adds this:
$exercise2 = $_POST['exercise2'];
$exercise3 = $_POST['exercise3'];
and adds to the array
"exercise2" => $exercise2
"exercise3" => $exercise3
etc. for all the numbers ofcourse
Now obviously I can't add a unlimited amount into this myself so I was wondering how to get PHP to add them automatically according to how many were added.
I see the obvious risk that someone could spam it by adding a million exercises but that's not a concern for the environment this will be used in.
I tried a for loop but got stuck eventually:
I don't remember the exact code but I tried to add a variable, lets call it n, this variable would get a +1 everytime I pressed the + button so if n=1 at the start, pressing the button once makes it 2, then 3, then 4 etc. and then I got stuck thinking I'd still need to add an infinite amount of
$exercise + n = $_POST['exercise' + n];
if that would even work anyways.
Thanks for any help in advance.
I just solved a similar issue yesterday - here's how.....
The 'key' is to get the form names setup before sending to PHP.
(as you didn't give examples of your form, I will use mine for example - easy enough to port over to your project)
In my project, the user is allowed to add custom menu (nav bar) items as well as links under it, etc.
The way I solved it was to name things where PHP would get a nicely formed array in the $_POST;
<input type="text" name="menu1[Name]" value="">
<input required type="text" name="menu1[data][1][text]" value="">
<input required type="text" name="menu1[data][1][link]" value="">
'rinse/repeat' for all the form values that get added (replacing the '1' in the name with your variable) - you would also replace all 'menu1' with your 'exerciseX'
Now, put a 'Submit' button on the page;
<button type="button" id="custommenusave">Save Changes</button>
A bit of jQuery makes simple work of it....
$("#custommenusave").click(function () {
update_custom_menus();
});
function update_custom_menus() {
var form = $("#form_custom_menus");
$.post("../data/ajax.php", 'function=set_custom_menu&' + form.serialize(), function (data) {
form.submit();
});
}
PHP gets a nice array to work with (I've done a json_encode to make it simpler to see....)
{"menu1":{"Name":"'my menu #1'","data":{"1":{"text":"first","link":"https:\/\/example.com","options":"tab"},"2":{"text":"the second link","link":"http:\/\/example2.com","options":"tab"}}},"menu2":{"Name":"'menu #2!!!!'","data":{"1":{"text":"link in menu #2","link":"https:\/\/example.com","options":"tab"}}}
Then, pull your user's answers and work with them (of course, you should clean any data that comes from a user - no matter how much you 'trust' them!)
This should give you an idea of at least one way (with working code) that you can go.
name of your input should be an array so you can add multiple inputs by same name
<input required type="text" name="exercise[]">
$count = 1;
$finalArray = array();
if(is_array($_POST) && count($_POST) > 0){
foreach ($_POST as $value) {
$finalArray['exercise'.$count] = $value;
$count++;
}
}
print_r($finalArray);
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
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?
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....
Given that when using an html radio box, to send values to a php script, only the selected values is sent to the php script, still holds true.
Do I still need to check that the user has selected something, when I am only interested in the selected value being sent to the php script, if the user does not select anything we do nothing or I guess I could prompt the user to select something.
If so, whats the best way to handle this with regards to radio boxes?
<!--Using the radio box, a single selected value is sent to the php script for processing-->
<td width="100px" height="30px">
<input type = "radio"
name = "selection"
value = "Lays" />Lays Chips 0.99c<br />
<input type = "radio"
name = "selection"
value = "Ruffles" />Ruffles $1.85<br />
The user will be able to click the "submit" button even without selecting an option from your radiobox.
If it's ok to send the form without a selection and you just want to do something different (or ignore it) when nothing is selected, you can do this:
<?php
if (isset(($_POST['selection'])) {
//Use it.. and make sure to validate user input.
} else {
//nothing was selected. Do something or just ignore?
}
?>
OTOH, if you want to prevent submiting without a selection, you will need to use some JavaScript to do it.
Even if the radiobox is not set, you can still post the form back to the server. Unless, of course, you have Javascript that prevents one from clicking on the submit form if the radiobox is not set.
So, you still need to check whether the radiobox is set or not, before working on it.