JQuery and calling PHP using AJAX using POST - php

I'm trying to make a Final Exam Review guide for my Physics Class, but I want to be able to view my (and others') previous scores in a text file log. What I have is a pre-made text file called "scorelog.txt", my javascript file is called "phpjs.js", HTML file called "physics-with-php.hmtl" and my PHP file is called "submitlog.php". My question is:
When I press the 'next' button in my html for the last time, it gives the alert box, but it seems that it isn't sending data to PHP or it could be the PHP isn't writing to the text file. I am pretty sure it isn't the latter, as I have checked my PHP time and again.
Javascript
$(window).load(function() {
$(document).ready(function() {
var totalQuestions = $('.questions').size();
var currentQuestion = 0;
$questions = $('.questions');
$submitBtn = $('.subBtn');
$questions.hide();
$submitBtn.hide();
$($questions.get(currentQuestion)).fadeIn();
$('#next').click(function() {
$($questions.get(currentQuestion)).fadeOut(function() {
currentQuestion = currentQuestion + 1;
if (currentQuestion == totalQuestions) {
var score = 0;
score = parseInt($("input:radio[name='1']:checked").val()) + parseInt($("input:radio[name='2']:checked").val()) + parseInt($("input:radio[name='3']:checked").val()) + parseInt($("input:radio[name='4']:checked").val()) + parseInt($("input:radio[name='5']:checked").val());
alert("Your score: " + score + " / 5");
var fullname = $('$.FullName').val();
$.ajax({
type: "POST",
url: "submitlog.php",
data: {"finalscore: score, name: fullname"},
success: function(data) {
alert("Your score of " + data + " has been logged");
}
});
} else {
$($questions.get(currentQuestion)).fadeIn();
}
});
});
});
});
HTML
<html>
<head>
<title>Cumulative Practice</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/libs/jquery-1.9.0/jquery.min.js"></script>
<script type='text/javascript' src='phpjs.js'></script>
</head>
<body>
<div>
<h1>Cumulative Test</h1>
Full Name: <input type="text" id="FullName" name="Fullname" class="FullName"/>
<p class="instructions">
Select the best answer for each question, then press next.
</p>
</div>
<div class="questions">
<p>1. Two vertical walls are separated by a distance of 1.5 m, as the
drawing shows. Wall 1 is smooth, while wall 2 is not smooth. A uniform
board is propped between them. The coefficient of static friction
between the board and wall 2 is 0.98. What is the length of the longest
board that can be propped between the walls?</p>
<form class="options">
<input class="option" type="radio" name="1" value=0> 43 meters<br>
<input class="option" type="radio" name="1" value=1> 67 meters<br>
<input class="option" type="radio" name="1" value=0> 63.5 meters<br>
<input class="option" type="radio" name="1" value=0> 57 meters<br>
</form>
</div>
<div class="questions">
<p>2. Two submarines are under water and approaching each
other head-on. Sub A has a speed of 12 m/s and sub B has a speed
of 8 m/s. Sub A sends out a 1550-Hz sonar wave that travels at a
speed of 1522 m/s. What is the frequency detected by sub B?</p>
<form class="options">
<input class="option" type="radio" name="2" value=0> 1495 Hz<br>
<input class="option" type="radio" name="2" value=0> 1625 Hz<br>
<input class="option" type="radio" name="2" value=1> 1570 Hz<br>
<input class="option" type="radio" name="2" value=0> 1590 Hz<br>
</form>
</div>
<div class="questions">
<p>3. Two converging lenses are separated by 24.00 cm. The focal
length of each lens is 12.00 cm. An object is placed 36.00 cm to the
left of the lens that is on the left. Determine the final image distance
relative to the lens on the right. Hint: Try drawing a ray diagram.</p>
<form class="options">
<input class="option" type="radio" name="3" value=0> 12 cm<br>
<input class="option" type="radio" name="3" value=0> -10 cm<br>
<input class="option" type="radio" name="3" value=0> 13 cm<br>
<input class="option" type="radio" name="3" value=0> -24 cm<br>
<input class="option" type="radio" name="3" value=1> -12 cm<br>
</form>
</div>
<div class="questions">
<p>4. A mirror produces an image that is located 34.0 cm behind the
mirror when the object is located 7.50 cm in front of the mirror. What
is the focal length of the mirror, and is the mirror concave or convex? </p>
<form class="options">
<input class="option" type="radio" name="4" value=0> 9.62 cm; Concave<br>
<input class="option" type="radio" name="4" value=1> 9.62 cm; Convex<br>
<input class="option" type="radio" name="4" value=0> 0.104 cm; Concave<br>
<input class="option" type="radio" name="4" value=0> 8.104 cm; Convex<br>
</form>
</div>
<div class="questions">
<p>5. An object is located 14.0 cm in front of a convex mirror, the
image being 7.00 cm behind the mirror. A second object, twice as tall
as the first one, is placed in front of the mirror, but at a different location.
The image of this second object has the same height as the other
image. How far in front of the mirror is the second object located?</p>
<form class="options">
<input class="option" type="radio" name="5" value=0> 21 cm<br>
<input class="option" type="radio" name="5" value=0> 28 cm<br>
<input class="option" type="radio" name="5" value=1> 42 cm<br>
<input class="option" type="radio" name="5" value=0> 7 cm<br>
</form>
</div>
<br>
<input type="button" id='next' value="Next" />
</body>
</html>
PHP
<?php
$logfile = "scorelog.txt";
$fh = fopen($logfile, 'a') or die("can't open file");
$score = $_POST['finalscore'];
$fullname = $_POST['name'];
$stringdata = "$fullname scored $score points\n";
fwrite($fh, $stringdata);
fclose($fh);
?>
Thanks in advance.

Your data parameter looks bad:
data: {"finalscore: score, name: fullname"},
Should probably be:
data: { "finalscore": score, "name": fullname },
data has to be a key value pair.
Your PHP script probably also isn't very robust, it should throw an error if it gets input it doesn't expect. It's a bit more advanced but you want your scripts to behave like that. Validate your input and crashing early will save you a lot of time in the long run :) Then you don't have to say things like "I think it's fine", because you'll know.

your data parameter should be like below
data: {finalscore: score, name: fullname},

Related

how-to submit form with multiple groups of radio buttons?

goal: post several groups of radio buttons to array (as a message, to database, etc.)
Hi there,
I was wondering how i can post my selections of several groups of radio buttons.
Here is the code:
<body>
<form action="" method="post">
<select name="module 1">
<input type="radio" name="radioA" value="Radio 1">Radio 1
<input type="radio" name="radioA" value="Radio 2">Radio 2
<input type="radio" name="radioA" value="Radio 3">Radio 3
<input type="submit" name="submit" value="Get Selected Values" />
</select>
<br>
<select name="module 2">
<input type="radio" name="radioB" value="Radio 21">Radio 21
<input type="radio" name="radioB" value="Radio 22">Radio 22
<input type="radio" name="radioB" value="Radio 23">Radio 23
<input type="submit" name="submit" value="Get Selected Values" />
</select>
<br>
<select name="module 3">
<input type="radio" name="radioC" value="Radio 31">Radio 31
<input type="radio" name="radioC" value="Radio 32">Radio 32
<input type="radio" name="radioC" value="Radio 33">Radio 33
<input type="submit" name="submitC" value="Get Selected Values" />
</select>
<br>
</form>
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['radioA']))
{
echo "You have selected :".$_POST['radioA']; // Displaying Selected Value
}
}
?>
</body>
...But I can't make it display the list of my selections, but only one instructions, instead of 3x (one for each).
Long story short... How can I treat this as a 1 global set of 3 groups, having only 1 "submit" button to process all 3 groups at once?
Txs a lot, and have a nice weekend.
You just need to remove the other two submit buttons and only display one. As long as it is inside the <form> it will submit all the radio button "groups" to the $_POST.
Also, remove the select tags as you are using them incorrectly. Only an option or optgroup should be nested inside a select element.
You will need to reference each one individually to see the selected response:
echo $_POST['radioA'];
echo $_POST['radioB'];
echo $_POST['radioC'];

Star Rating System With Checkboxes and PHP backend

I want to make a star rating system in html with checkboxes. When a checkbox is checked, the previous are checked and the others are unchecked.
The result will be POSTed to my php code backend.
Here's my current html:
<span class="star-rating">
<!--RADIO 1-->
<input type='checkbox' class="radio_item" value="1" name="item" id="radio1">
<label class="label_item" for="radio1"> <img src="label.png" style="width:30px;height:28px"> </label>
<!--RADIO 2-->
<input type='checkbox' class="radio_item" value="2" name="item2" id="radio2">
<label class="label_item" for="radio2"> <img src="label.png" style="width:30px;height:28px"> </label>
<!--RADIO 3-->
<input type='checkbox' class="radio_item" value="3" name="item3" id="radio3">
<label class="label_item" for="radio3"> <img src="label.png" style="width:30px;height:28px"> </label>
<!--RADIO 4-->
<input type='checkbox' class="radio_item" value="4" name="item4" id="radio4">
<label class="label_item" for="radio4"> <img src="label.png" style="width:30px;height:28px"> </label>
<!--RADIO 5-->
<input type='checkbox' class="radio_item" value="5" name="item5" id="radio5">
<label class="label_item" for="radio5"> <img src="label.png" style="width:30px;height:28px"> </label>
</span>
Include Jquery in your html and this simple javascript code might do just what you want.
$('.star-rating input').click( function(){
starvalue = $(this).attr('value');
// iterate through the checkboxes and check those with values lower than or equal to the one you selected. Uncheck any other.
for(i=0; i<=5; i++){
if (i <= starvalue){
$("#radio" + i).prop('checked', true);
} else {
$("#radio" + i).prop('checked', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star-rating">
<!--RADIO 1-->
<input type='checkbox' class="radio_item" value="1" name="item" id="radio1">
<label class="label_item" for="radio1"> &#9734 </label>
<!--RADIO 2-->
<input type='checkbox' class="radio_item" value="2" name="item2" id="radio2">
<label class="label_item" for="radio2"> &#9734 </label>
<!--RADIO 3-->
<input type='checkbox' class="radio_item" value="3" name="item3" id="radio3">
<label class="label_item" for="radio3"> &#9734 </label>
<!--RADIO 4-->
<input type='checkbox' class="radio_item" value="4" name="item4" id="radio4">
<label class="label_item" for="radio4"> &#9734 </label>
<!--RADIO 5-->
<input type='checkbox' class="radio_item" value="5" name="item5" id="radio5">
<label class="label_item" for="radio5"> &#9734 </label>
</span>
Obs: The html code is the same as yours. I've just replaced the images by stars as the links were broken.
Obs2: When you post this to your php, you will receive all checked inputs. Your php code will have to be smart and take the highest value it receives. This should not be difficult.
Obs3: The stars should behave as radio-buttons and not checkboxes. The workaround from Obs2 means that your backend code has too much knowledge of what is happening on the interface. This is a more advanced tip, but take that in consideration in the future.
EXTRA
To include this code in your app, you have some options:
OPTION 1 (jQuery from google CDN and javascript code on script tag)
Put this in your html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$('.star-rating input').click( function(){
starvalue = $(this).attr('value');
// iterate through the checkboxes and check those with values lower than or equal to the one you selected. Uncheck any other.
for(i=0; i<=5; i++){
if (i <= starvalue){
$("#radio" + i).prop('checked', true);
} else {
$("#radio" + i).prop('checked', false);
}
}
});
</script>
OPTION 2 (better: jQuery from CDN and javascript file included with php):
Include jQuery as above and put the javascript code in a file: star_rating.js, then include that file with php include command.

separate radio group zf2

Within my application I have a 3 steps registration form. In part one someone has
to select a package (member ship).
Here I need one group of radio buttons but because I am handeling 3 packages with each
2 options, with a lot of html between each 2 radio buttons I need to separate the
radio buttons and getting them one by one. the separate option for this is probably not
enough because it's not consistent with html and there can be a lot of html between.
Thanks! =)
You can do this using js hide-show
<script>
$(function(){
$("#package1").on(click,function(){
$("#p1").show();
});
$("#package2").on(click,function(){
$("#p2").show();
});
$("#package3").on(click,function(){
$("#p3").show();
});
});
</script>
<style>
.hidden {
display: none;
}
</style>
<input type="radio" name="package" id="package1" value="Package1">
<input type="radio" name="package" id="package2" value="Package2">
<input type="radio" name="package" id="package3" value="Package3">
<input class="hidden" type="radio" id="p1" name="p1option" value="P1 Option1">
<input class="hidden" type="radio" id="p1" name="p1option" value="P1 Option2">
<input class="hidden" type="radio" id="p2" name="p3option" value="P2 Option1">
<input class="hidden" type="radio" id="p2" name="p2option" value="P2 Option2">
<input class="hidden" type="radio" id="p3" name="p1option" value="P2 Option1">
<input class="hidden" type="radio" id="p3" name="p3option" value="P2 Option2">

Displaying form results with jquery

I got a form, with 4 questions (1 question has 4 radio buttons), each question is stored inside a div.
With jquery i first show the 1st div, when i press the next button i show the 2nd, and so on.
Heres the entire code for it:
<form style="position:absolute; margin-left:140px;" method="post">
<div id="question1">
Q1
<br/>
<input name="q1" type="radio" value="q1a1">
A1
<br/>
<input name="q1" type="radio" value="q1a2">
A2
<br/>
<input name="q1" type="radio" value="q1a3">
A3
<br/>
<input name="q1" type="radio" value="q1a4">
A4
<br/>
</div>
<div id="question2">
Q2
<br/>
<input name="q2" type="radio" value="q2a1">
A1
<br/>
<input name="q2" type="radio" value="q2a2">
A2
<br/>
<input name="q2" type="radio" value="q2a3">
A3
<br/>
<input name="q2" type="radio" value="q2a4">
A4
<br/>
</div>
<div id="question3">
Q3
<br/>
<input name="q3" type="radio" value="q3a1">
A1
<br/>
<input name="q3" type="radio" value="q3a2">
A2
<br/>
<input name="q3" type="radio" value="q3a3">
A3
<br/>
<input name="q3" type="radio" value="q3a4">
A4
<br/>
</div>
<div id="question4">
Q4
<br/>
<input name="q4" type="radio" value="q4a1">
A1
<br/>
<input name="q4" type="radio" value="q4a2">
A2
<br/>
<input name="q4" type="radio" value="q4a3">
A3
<br/>
<input name="q4" type="radio" value="q4a4">
A4
<br/>
</div>
<br/><br/><br/><br/>
<input type="button" id="submit" name="Submit" />
</form>
<button id="next">Next question</button>
<script>
$('#submit').hide();
$('div[id^="question"]').hide().first().show();
$("#next").click(function (e) {
event.preventDefault();
$('div[id^="question"]:visible').hide().next().show();
});
</script>
This is what i want - when the last (4th) question loads, i want my next button to change into submit button. When i press the submit button it would show witch radio buttons were selected. Any suggestions on how can i do this?
Try something like this:
var currentQuestion = 1;
$(document).ready(function() {
$('.next').click(function(e) {
e.preventDefault();
if(currentQuestion < 4) {
$('#question' + (currentQuestion).toString()).hide();
$('#question' + (currentQuestion + 1).toString()).show();
currentQuestion++;
}
else { // On question four, process the form
// Not sure what you want to do with the data, but
// you can parse them like this:
var selections = {};
for(var i=1;i<=4;i++) {
selections[i] = $('input[name="q' + i.toString() + '"]:checked').val()
}
// Then you have a JS object with your questions and
// corresponding choices, so you can do what you want.
}
});
});

checkbox in groups?

i need to make "groups" or something with my checkboxes. i want to click on a checkbox and only those checkboxes are active which available then. Like in the car configuration. If you buy the electric mirror you cant chose the manual one.In my case i have Product 1A 1B 1C and 2A 2B 2C and if i chose product one i can only choose product 1A,1B,1C.
<input type="checkbox" value="">1A</label>
<input type="checkbox" value="">1B</label>
<input type="checkbox" value="">1C</label>
<input type="checkbox" value="">2A</label>
<input type="checkbox" value="">2B</label>
<input type="checkbox" value="">2C</label>
HTML
<input type="checkbox" class='product' value=""/>1A
<input type="checkbox" class='product' value=""/>1B
<input type="checkbox" class='product' value=""/>1C
<input type="checkbox" class='product' value=""/>2A
<input type="checkbox" class='product' value=""/>2B
<input type="checkbox"class='product' value=""/>2C
jQuery
$(function(){
var $product = $('input.product');
$product.click(function() {
$product.filter(':checked').not(this).removeAttr('checked');
});
})
FIDDLE
Added after comment from OP
This is the code after the comment that if i chose 1A, i can also click on 1B and 1C but not on 2A,2B,2C*
HTML
<input type="checkbox" class='one' value=""/>1A
<input type="checkbox" class='one' value=""/>1B
<input type="checkbox" class='one' value=""/>1C<br/>
<input type="checkbox" class='two' value=""/>2A
<input type="checkbox" class='two' value=""/>2B
<input type="checkbox" class='two' value=""/>2C
jQuery
$(function(){
var $one= $('input.one');
$one.click(function() {
$one.filter(':checked').not(this).removeAttr('checked');
if($one.filter(':checked').length>0) {
$two.attr("disabled","disabled");
}
else {
$two.removeAttr("disabled");
}
});
var $two= $('input.two');
$two.click(function() {
$two.filter(':checked').not(this).removeAttr('checked');
if($two.filter(':checked').length>0) {
$one.attr("disabled","disabled");
}
else {
$one.removeAttr("disabled");
}
});
});
Fiddle
I think you may want to look at radio button types rather
If you are using checkboxes, you should address them as an array in your PHP code as well as giving them a name attribute (which is how PHP sees them):
<input type="checkbox" name ="checkbox1" value="">1A</label>
In your PHP code:
$checkArray=$_REQUEST['checkbox1'];
foreach($checkArray as $val)
{
echo $val;// Value is echo'ed.
}
html
<input type="checkbox" class='group1' value=""/>1A
<input type="checkbox" class='group1' value=""/>1B
<input type="checkbox" class='group1' value=""/>1C
<input type="checkbox" class='group2' value=""/>2A
<input type="checkbox" class='group2' value=""/>2B
<input type="checkbox" class='group2' value=""/>2C
<br/>
jquery
<br />
<script>
$(function(){
var $product=$('input:checkbox');
$product.click(function() {
$product.attr('checked',false);
var classname=$(this).attr('class');
$('.'+classname).attr('checked','checked');
});
});
</script>

Categories