2 weeks ago I taught myself html, css and javascript in my spare time. I know the basics of all three of these languages. I just need a little help with the submit button and server side programming.
Here's my problem:
I made a website (html & css) that randomly generates two things to rate (for example, girls). Under these, there is a radio button for left or right. Then under that there is a submit button. When you enter left or right and hit submit, there is no rating algorithm, so it just goes to the next file (which repeats this). I want to know how to put in a rating algorithm to keep score (like elo or a rating/10). How should I approach this? I thought of a couple of ways, but I don't know if I can pull it off in JS or I'll have to learn php.
For JS, the only idea I have is maybe making and if/else if. For example:
If girl1 and girl2 are available and girl1 is chosen:
Run this algorithm.
Else if girl1 and girl2 are available and girl2 is chosen:
Run this algorithm.
If I do this, will the variables change and be saved when anybody uses the site, or are there limits?
I will also be using a web hosting service, I don't have my own server.
Thanks a ton!
This is the form that you would use for selection. Lets say a file named abc.php
Write a bit of html in abc.php
<form method="POST">
<input type="radio" name="person" value="1" />
<input type="radio" name="person" value="2" />
<input type="submit" name="submit" />
</form>
This is the server side scripting
And a bit of php in abc.php
<?php
if(isset($_POST['submit']))
{
$person = $_POST['person'];
echo $person;
}
?>
This $person has now the value either 1 or 2. Since you have gotten the value now you can use it. for instance
<?php
if(isset($_POST['submit']))
{
$person = $_POST['person'];
echo $person;
ratePerson($person);
}
function ratePerson($person)
{
//some logic of your algorithm
}
?>
Related
I'm quite new to PHP so apologies for not being fully aware of code structures.
In a PHP file I have a form with the options in a drop-down menu being populated from a database query (how many rounds for a tournament based on the number of entrants). Once a user has selected an option for the round of fixtures they want to view that option gets passed as a variable to determine what to display on form submit. On form submit the rest of the page changes to display the fixtures from the database that relate to the Round that the user selected from the drop-down.
My challenge is that after selecting the Round number from the drop-down menu I have to click the submit button twice - once to assign the variable and then the second press of submit to be able to use the variable as part of the process to display the fixture information from the database.
I'm aware that it is possible to use JS to store a variable that can then be used on form submit but I'm not sure how to integrate it with the way the form / has been written.
After looking at a few places on the web (like W3Schools) I've got some basic JS and have tried that but I think there's still a disconnect between the user selecting and storing the variable ready to be used when the submit is clicked.
//Basic JS
<script>
function getFormIndex() {
document.getElementById($_POST['roundselect']).innerHTML =
document.getElementById("roundselect").selectedIndex;
}
</script>
//PHP Elements
if(isset($_POST['submit'])){
$roundnum = $_POST['roundselect']; }
<?php
function setround(){
$roundnum = $_POST['roundselect'];
echo $roundnum;
}
?>
//Form
<div class="h2_select">
<? if($fnum) {
$select_opt = (isset($_GET['round'])) ? $_GET['round'] : 1;
?>
<form method="post" action="/tournaments/<?=$lid; ?>/fixtures/<?= $roundnum; ?>" name="rf">
<!--<input type="hidden" name="id" value="/<?=$lid; ?>" />
<input type="hidden" name="page" value="/fixtures" /> -->
<span class="minput">Select Round
<select size=1 class="mselect" name="roundselect" onChange=getFormIndex();>
<? for($i=1; $i <= $total_rounds; $i++) { ?>
<option value="<?= $i ?>" <?php if($i == $select_opt){ echo 'selected'; } ?> > <?= $i?> </option>
<? }
?>
</select>
<input type="submit" name="submit" value="<?= $lang[185] ?>" class="minput"/>
</form>
<? } ?>
</div>
To confirm, the form works and displays the correct information. The problem is that I currently need to click "submit" twice.
Thanks
Good start, I would do it with a bit of AJAX that allows us to send a request and receive an answer "in the background" - so that first time user changes the select I would fetch data from backend in the background and display it without double-submitting needed.
Please check this thread - I think it is illustrating the same thing;
How to Submit Form on Select Change
It is based on JQuery and I think it is a good start for new developers.
But - if you do not want to use a framework and does not care for older browsers you can just use "vanilla" Javascript with Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and onchange https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Fetch returns the result so then you have to pass it back to the website.
It is very easy to do so with :
1. set a div on your page and add a unique ID to it (like )
2. use document.getElementById("result").innerHTML = resultFromFetch;
So:
listen to onchange on select
fetch from backend when select changes
display fetch result
AJAX is really neat and very good for the user experience as it allows us to get the data asynchronously and in the "back stage" of our application. But then it is a good user experience measure to show also some "please wait" indications and also make sure to show some potential errors (the connection can go "down" when waiting for results and then it is wise to show errors to users instead of them waiting forever).
Hope this helps to point you in a new and exiting direction.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
Inside a PHP/HTML page i'm trying to start a session in php and then set a value to a session variable, and i'm trying that inside a Javascript function, and in this function there is a if statement, but the php code inside the if statement runs automatically when i go to the page immediately, when i want the code to run only when the user accept the terms...
Here is my code :
HTML :
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
</label>
Javascript :
if(document.getElementById("terms-checkbox").checked){
<?php session_start(); $_SESSION["ITA"] = "Yes"; ?>
window.open('DL.php?App=STOPit');
}
So when i open the php page that contains that previous Javascript code, the $_SESSION["ITA"] variable will be equals to "Yes" even that the condition is not met yet.
Hope someone can help me with that.
That's not how PHP and Javascript work.
PHP runs on the server before anything else. JS runs on the client side.
Without further information:
I suppose your JS code is not a file, but a inline script on the same HTML/PHP page. When your user requests the HTML page, PHP parses it, including the tags inside your JS code.
If you want PHP to do something based on a user action on the browser (document.getElementById) you have to take other routes. Maybe using Ajax, for example -- so your PHP code can do something.
For your better understanding php runs on the server side and javascript runs on the client side.
What you are trying to do is possible if you submit the data using a form or you have to make an ajax call using javascript.
Below is one way of doing something similar.
<?php
session_start();
if(isset($_POST['terms'])) {
$_SESSION["ITA"] = "Yes";
header('Location: DL.php?App=STOPit');
}
?>
<form action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
<input type="submit" value="Submit">
</label>
</form>
Always start your PHP session_start() on the top of your PHP script file.
<?php
session_start();
?>
Here you can continue with your HTML/CSS/JavaScript codes
but the above is mandatory in order to start a session within
your PHP project.
Otherwise you'll be sending header information after the output buffering happend, and you'll end up with an error like this:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
When you have properly initialized a session handler as I described, you can use or do:
$_SESSION['item-name'] = 'value'; // to set a value of a specific session item
echo $_SESSION['item-name']; // retrieve it's value and output it
unset($_SESSION['item-name']); // to delete it from the $_SESSION container
i want to capture input variables sent via form from one page to another.html page and obtain these values as JavaScript variables. Can this be done.
This is my form;
<form action='another.html' id='form' data-ajax='false'>
<input id='sent_by' value='tom'/>
<input type='submit' value='Submit'/>
</form>
And in my another.html i tried to get the values as;
var sent_by = $.session.get("sent_by");
But i am not able to get the values. All help is appreciated.
You can use the browser's localStorage to achieve this. Before submitting and going to the other page store all the values of the form in the localStorage and you can access it on the other page:
Page1.html
Field Name = "name" <input type="text" name="name" id="name" />
Read the value and store it to localStorage
localStorage.setItem('name', document.getElementById('name').value);
and so on.
You can make a function in JavaScript that saves all the fields of the form in localStorage on / before submit.
To read these values on the other page:
Page2.html
Value stored for key name can be get using the following JavaScript:
localStorage.getItem("name");
NOTE
the page1.html and page2.html should be in the same domain for you to access the localStorage.
Read more about localstorage at https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Have you tried using Window.localStorage? It's similar to sessionStorage but with no expiration date. So, be sure to clear it once the browsing session ends.
I think the answer provided by #Shakti Phartiyal is probably the most practical and a sweet trick I might add. The main reason I'm writing this post is because I had also taken a long path of using javascript to pass along this kind of information. It resulted in me bewildered at how powerful PHP can be for some tasks that you dedicated javascript to do. (Yea I know some javascript wizards out there can do everything with it, I'm just talking about basic programming tho). So if you wondered what the PHP way of passing this around:
Your modified html form:
<form action='another.html' id='form' data-ajax='false' method='post'>
<input id='sent_by' value='tom' name='uname'/>
<input type='submit' value='Submit'/>
</form>
and then in "another.php" you would have this to retrieve the input from the form:
<?php
$uname= htmlspecialchars($_POST['uname'];
?>
Great. But how to make this php variable into javascript?
Ah, the fun part. You're going to write javascript to your webpage with php - you do something like this:
var uname = "<?php echo $uname; ?>";
So I'm trying to get my webpage to save some text to a server-side file. It's kinda like a guestbook, but I want it in a text file so I can review it before I put it on the site. I've been looking around, and from the looks of it, you can't do it with javascript because of 'security hazards'. I've seen things about php, but php files never seem to work for me. Is there a way to do this in plain .html and if not how do I make a php file do this, and be very specific with the steps required to make said php file. And I'm using apache if that helps at all. Thanks for your help.
This will take one PHP file and is not secure. But, it is what you want. The user can very easily sign the guest book. Additionally, it will display previous guest entries on the page. Yay!
guestBook.php
<?php
session_start();
if (!empty($_POST['name'])) {
if (!isset($_SESSION['posts'])) {
$_SESSION['posts'] = 0;
} else if ($_SESSION['posts'] >= 5) {
echo "<div style='color:red'>Failed to post - max posts exceded</div>";
} else {
$_SESSION['posts'] += 1;
file_put_contents("guest.txt",htmlspecialchars($_POST['name']) . "<br />",FILE_APPEND);
}
}
echo file_get_contents("guest.txt");
?>
<form method="post" action="">
<input name="name" type="text" value="John Kieth" />
<input type="submit" />
</form>
P.S. You literally can't do this through regular HTML/JavaScript.
The thought of making yet another get request and yet another php file is annoying to me... so I've been using this method:
<input class='hidden' id='dataIwant' value=' <?php echo $_SESSION["bigObjectArray"] ?>" />
Is this bad practice? What do you think?
IMHO, session variables might be dangerous to display in the client side. Only part of them such as indexes, strings which the user already knows should be shown to the user. If the session variable contains something like user password, session token etc., it should be hidden.
About your question, it changes when where you want to use this data. If it's only for passing it inside the form to another PHP page, you don't need to do this, as it will still be available in the form processing page.
If you want to use it inside the javascript code in the client side, you can json_encode it and assign it to a javascript variable.
<script type="text/javascript">
var myBigJSON = <?php echo json_encode($_SESSION["bigObjectArray"]);?>;
var myBigArray = $.parseJSON(myBigJSON);
</script>
I think this example speaks for itself:
<?php
session_start();
$_SESSION['bigObjectArray'] = "\" /><script>alert('Hi!')</script><input type=\"hidden";
?>
<input class="hidden" id="dataIwant" value="<?php echo $_SESSION["bigObjectArray"] ?>" />
output:
<input class="hidden" id="dataIwant" value="" /><script>alert('Hi!')</script><input type="hidden" />
Make sure to validate and filter the data you are echoing. Be paranoid, always.
It's a bad pratice if you do not escape it (htmlentities or htmlspecialchars).
It's a bad practice if user have no reason to change this field.
It's a bad practice for multi-tab browsing, since it's SESSION stored (concurrent pages writing/reading that value will fail).
It's a good practice if you html escape the value, if the user can change that field (and if you check it on the treatment page) and if it avoids storing that value in SESSION.