Displaying form results with jquery - php

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.
}
});
});

Related

checkbox with ordered selection array for php

<form method='post' action=''>
<label for="x1">X1</label>
<input id="x1" name="checkbox[]" type="checkbox" value="x1" />
<label for="x2">X2</label>
<input id="x2" name="checkbox[]" type="checkbox" value="x2" />
<label for="x3">X3</label>
<input id="x3" name="checkbox[]" type="checkbox" value="x3" />
<label for="x4">X4</label>
<input id="x4" name="checkbox[]" type="checkbox" value="x4" />
<button type='submit' name='submit'>Submit</button>
</form>
In this form How can i get the selection order of the checkboxes inside the php array
Just if i submitted the form after clicking x4 > x2 > x3 > x1
i want to get ordered in the array as it is selected checkbox[x4, x2, x3, x1]
The normal array i get is as it is ordered checkbox[x1, x2, x3, x4].
Check the clicked order using jquery
push the value to array on change event.if is checked push to the array.is unchecked value remove from array
Join the array with , add the value to hidden input .you could post this value to server
var arr=[]
$('input[type=checkbox]').on('change', function() {
if ($(this).is(':checked')) {
arr.push($(this).val())
} else {
var r =arr.indexOf($(this).val())
arr.splice(r, 1)
}
$('input[type=hidden]').val(arr.join(',')) //for server use
console.log(arr)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='post' action=''>
<label for="x1">X1</label>
<input id="x1" name="checkbox[]" type="checkbox" value="x1" />
<label for="x2">X2</label>
<input id="x2" name="checkbox[]" type="checkbox" value="x2" />
<label for="x3">X3</label>
<input id="x3" name="checkbox[]" type="checkbox" value="x3" />
<label for="x4">X4</label>
<input id="x4" name="checkbox[]" type="checkbox" value="x4" />
<input type="hidden" name="clickedorder" >
<button type='submit' name='submit'>Submit</button>
</form>
Updated
change the label value depend on clicking order
var arr=[]
$('input[type=checkbox]').on('change', function() {
if ($(this).is(':checked')) {
arr.push($(this).val())
} else {
var r =arr.indexOf($(this).val())
arr.splice(r, 1)
}
$('input[type=checkbox]').each(function(a){
//console.log(arr.indexOf($(this).val()))
if(arr.indexOf($(this).val())>-1){
$(this).prev('label').text($(this).val().toUpperCase()+'-'+(arr.indexOf($(this).val())+1))
}else{
$(this).prev('label').text($(this).val().toUpperCase())
}
})
$('input[type=hidden]').val(arr.join(',')) //for server use
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='post' action=''>
<label for="x1">X1</label>
<input id="x1" name="checkbox[]" type="checkbox" value="x1" />
<label for="x2">X2</label>
<input id="x2" name="checkbox[]" type="checkbox" value="x2" />
<label for="x3">X3</label>
<input id="x3" name="checkbox[]" type="checkbox" value="x3" />
<label for="x4">X4</label>
<input id="x4" name="checkbox[]" type="checkbox" value="x4" />
<input type="hidden" name="clickedorder" >
<button type='submit' name='submit'>Submit</button>
</form>
You need to write a jquery function like this:
Add a common class to all checkboxes like class="ckbox"
then,
$(document).ready(function(){
var selected_boxes = [];
$('.ckbox').change(function() {
if($(this).is(':checked')) {
selected_boxes.push($(this).val());
$(this).prev().attr('for',$(this).val());
}
else{ // When uncheck the checkbox.
selected_boxes.splice( $.inArray($(this).val(), selected_boxes), 1 );
}
});
});
Then post this JS variable to your php code. It will give all the values in sequence in which you had selected.

HTML and PHP posting in file error

I am making a poll with HTML and PHP and I want to post the poll answers in a text file. I have 6 things to choose from.
The name is answer and the values are a1, a2, a3, a4, a6. How to post a1 or a2 or a3... in the file.
You know when you click on the answer with id a1 to post in a new line a1 in the file.
HTML:
<form action="php/vote.php">
<b><strong>Vote:</strong></b> <br>
<input type="radio" name="answer" value="a1" id="a1">a<br>
<input type="radio" name="answer" value="a2" id="a2">b<br>
<input type="radio" name="answer" value="a3" id="a3">c<br>
<input type="radio" name="answer" value="a4" id="a4">d<br>
<input type="radio" name="answer" value="a5" id="a5">e
<br>
<input type="submit" name="submit" id="submit" value="Vote">
</form>
This should do what you are asking:
<?php
if(isset($_POST['answer'])){
file_put_contents("filename.txt", $_POST['answer']."\n");
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<b><strong>Vote:</strong></b> <br>
<input type="radio" name="answer" value="a1" id="a1">a<br>
<input type="radio" name="answer" value="a2" id="a2">b<br>
<input type="radio" name="answer" value="a3" id="a3">c<br>
<input type="radio" name="answer" value="a4" id="a4">d<br>
<input type="radio" name="answer" value="a5" id="a5">e
<br>
<input type="submit" name="submit" id="submit" value="Vote">
</body>
</form>
</html>
I have added method="POST" to your original HTML so that the receiving PHP can inspect the $_POST variable to see what was sent through from the form. $_POST['answer'] contains the value of the "value" field corresponding to the selected radio button. Once you know this, it is easy to call file_put_contents to write that value to your file. Append a newline "\n" to ensure that each call writes to a separate line of the file.

form submit with two actions

I am trying to create a page where the form submit will execute two actions. In index.php,First action is it will use ajax to send data to be saved in the database. Second action is it will change page to index1.php. The code I created successfully saves data to the database but it does not change to index1.php. What is the problem with my code?
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var radio1 = $("input[name=group1]:checked").val();
var radio2 = $("input[name=group2]:checked").val();
var radio3 = $("input[name=group3]:checked").val();
var radio4 = $("input[name=group4]:checked").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = '&submit1='+ radio1 + '&submit2='+ radio2 + '&submit3='+ radio3 + '&submit4='+ radio4;
if(radio1==''||radio2==''||radio3==''||radio4=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
</script>
<form action="index1.php" method="post">
<hr>
<label>Alignment: </label>
<input type="radio" name="group1" value="5"> 5
<input type="radio" name="group1" value="4"> 4
<input type="radio" name="group1" value="3"> 3
<input type="radio" name="group1" value="2"> 2
<input type="radio" name="group1" value="1"> 1
<hr>
<label>Blend: </label>
<input type="radio" name="group2" value="5"> 5
<input type="radio" name="group2" value="4"> 4
<input type="radio" name="group2" value="3"> 3
<input type="radio" name="group2" value="2"> 2
<input type="radio" name="group2" value="1"> 1
<hr>
<label>Warp: </label>
<input type="radio" name="group3" value="5"> 5
<input type="radio" name="group3" value="4"> 4
<input type="radio" name="group3" value="3"> 3
<input type="radio" name="group3" value="2"> 2
<input type="radio" name="group3" value="1"> 1
<hr>
<label>Overall: </label>
<input type="radio" name="group4" value="5"> 5
<input type="radio" name="group4" value="4"> 4
<input type="radio" name="group4" value="3"> 3
<input type="radio" name="group4" value="2"> 2
<input type="radio" name="group4" value="1"> 1
<hr>
<input type="submit" id="submit" name="submit" value="Submit" class="button">
</form>
You need to change location after ajax success:
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
window.location = '/index1.php';
}
});

JQuery and calling PHP using AJAX using POST

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},

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