Pulling a radio button's value to display from a PHP file - javascript

This is my first time posting so I apologize if I've missed something or if I get something wrong. I've also looked at other posts and although some are very similar, I don't think it's quite getting to the answer I'm seeking. I am also very new to AJAX (although this code doesn't really utilize a lot of AJAX I think) so any helpful insight into this problem would be greatly appreciated.
I'm trying to create a quiz template that calls on the data from a PHP file using AJAX after selecting a radio button and clicking the "Answer" button.
The general idea is that after the user reads the question, they select a radio button and clicks on the "Answer" button, the bottom part of the page gets populated with either the correct or incorrect string. It's easy to populate it with text and css, but my issue lies in pulling the right text.
Here is the HTML code block that sets up the form submission:
<form action="data.php" method="post" id="q1">
<input type="radio" name="answer1" value="1a" id="1q"> A.
<br>
<input type="radio" name="answer1" value="1b" id="1q"> B.
<br>
<input type="radio" name="answer1" value="1c" id="1q"> C.
<br>
<input type="radio" name="answer1" value="1d" id="1q"> D.
<br>
<input name="submit1" id="answer" type="button" title="abutton" value="ANSWER">
</form>
Here I've set up four radio buttons that each correspond to a letter and the form is linked to data.php, the file I'm pulling the correct/incorrect text from in this case.
I had an earlier version of the code that would follow the logic I had set out to do but would populate the correct text in another page. My goal is populate the a grey "Answer" box in the same page that appears after clicking the "Answer" button with text. The appended text is defined as a variable in the code as $correct or $incorrect, based on the user's selection.
The JS code block that calls the PHP file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#answer").click(function()
{
var test1 = $.post("data.php",
{answer1:'1d'},
function(data)
{
$("#text1").empty();
$("#text1").append(data);
$("#panel").fadeDown("slow");
});
});
});
</script>
I had help constructing this JS code but I understand enough of it. The goal here is that the "Answer" button, after being clicked, appends the text below the form element. This shows up as a small, grey "Answer" box from where users can read whether they got the right answer or not.
This particular line of code is what's bugging me:
{answer1:'1d'},
1d contains the right answer and when you pick any radio button and press "Answer", it still shows the correct text.
But when I try to do something like this:
{answer1:'1d',answer1:'1a',answer1:'1b',answer1'1c'},
The incorrect text, which is supposed to populate after choosing the radio buttons 1a, 1b, or 1c, overrides the text that's supposed to populate, even if the radio button 1d is chosen.
The PHP code that the JS code is calling from:
<?php
$correct = "Correct";
$incorrect = "Incorrect";
if (isset($_POST['answer1']))
{
if ($_POST['answer1'] === '1d')
{
print $correct1;
}
elseif ($_POST['answer1'] === '1b')
{
print $incorrect1;
}
elseif ($_POST['answer1'] ==='1c')
{
print $incorrect1;
}
elseif ($_POST['answer1'] === '1a')
{
print $incorrect1;
}
};
?>
Again, any insight on this problem would be greatly appreciated! Let me know if I need to clarify anything. Thanks!

First, id should always be unique. So remove or change the id of your inputs radio.
Then, you need to change your ajax request to send the selected input radio like this :
$(document).ready(function() {
$("#answer").click(function() {
var answer = $("input[name=answer1]:checked").val();
$.post("data.php", {answer1: answer}, function(data){
$("#text1").empty();
$("#text1").append(data);
$("#panel").fadeIn("slow");
});
});
});
Because in your code you never send the selected radio to your php page. And if you only send "1d" in this line {answer1:'1d'} your php page will always return the "correct" text even if you check another radio button.
I don't know the jQuery fadeDown() method. Only fadeIn() or fadeOut().
Also, in your data.php $correct1 and $incorrect1 are undefined. So echo $correct or $incorrect.

Related

Append input field value to url on button click

I'm very new to coding, so please forgive me if this is a dumb question.
I'm working on an assignment where I have to add functionality and styles to an existing bootstrap HTML doc. The purpose is to allow people to enter a dollar amount into an input field either by typing in an amount or by clicking buttons that populate the field with set amounts. One of my instructions was to update the donate submit button so that it appends the chosen donation amount to the "/thank-you" URL.
This is what I have for the input field:
<form id="amountSend">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount"/>
</form>
This is what I have for the button:
<button id="donateBtn" type="submit" action="/thank-you"
method="get">DONATE<span class="metric-amount"></span></button>
And I was thinking that the jQuery would look something like this, though the submit function is not currently giving me any visible results.
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit(function() {
var url = "/thank-you";
$(".metric-amount").appendTo("url");
});
}
})
I also got some decent results using a PHP method:
<form id="amountSend" method="post" action="/thank-you.php">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount" name="donation"></input>
</form>
<button id="donateBtn" type="submit">DONATE<span class="metric-amount"></span></button>
<script>
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit();
}
});
</script>
This one will open the PHP file I set up (/thank-you.php, which i have stored just in the same root folder as my main HTML doc), but all the browser gives me is the raw HTML code of the PHP file. Here's the code I have in the PHP file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
Thank you for your donation of
<?php echo $_POST["donation"]; ?><br>
</body>
</html>
Anyway, I guess I'm wondering if I'm on the right track? Should I pursue the jQuery or PHP method? Can I even do this using only jQuery? I've seen a few posts on this subject already, but I thought I'd make a new one since the ones I've seen are all fairly vague, I haven't seen the same answer twice, and I'm not sure I fully understand exactly what I'm trying to accomplish, in terms of a visual confirmation of results.
Thanks!
First of all, you have several issues with your code.
Number one: The formulary you have there is bad coded, the form tag needs to have the action and method attributes, not the submit button.
And in top of that, the submit button needs to be inside the form tag, if is not in there, it will not have and kind of effect.
Number two: If you are gonna submit the formulary to a php file and handle the request there ,you need the file to be running on a server (local or whatever). PHP is a server language, if you open the file directly in a browser, it will show you the code it has inside and will not work.
Hope it helps!

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Saving the form data and using said form data to redirect to a proper URL

thanks to the help and valuable insight from Stack Overflow members, I am very close to finishing my quiz project. I do, however, have a few more questions in regards to the finishing touches of the project. Before I start, I want to give a brief background on my quiz project.
The quiz consists of 10 questions. Each question is either a multiple choice or Y/N that simply uses radio buttons and an answer button that submits the information. The code incorporates both JavaScript and PHP, and maybe some Ajax later on. What it can do so far (if followed precisely) is that when the user enters the first page to answer the first question, selects a radio button and hits the answer button, it submits the form and prints the appropriate text depending on whether it was correct or incorrect. This part works well, at least for me at the moment.
What doesn't work well are two things. I'm able to increment and even show the incremented value on the page (though it won't show up in the final iteration) but when the page is refreshed, you can go through the same process again in the first page and increment the total correct variable. This means that, as the user, you can increment the total correct variable without even leaving the first question (not at all good).
This is my code here:
foreach ($correctAns as $key => $answer)
{
if (!empty($_POST[$key]))
{
if ($_POST[$key] == $answer)
{
print $correct[$index];
$_SESSION["totalCorrect"]++;
print $_SESSION["totalCorrect"];
}
else if($_POST[$key] != $answer)
{
print $incorrect[$index];
print "0";
}
}
$index++;
};
The goal is to increment the total correct variable from each page and based on how many were correct, take them to one of two pages. For example, if their total correct variable was less than 7, then they are redirect to a retake page. If it was equal to or more than 7, then they are taken to the success page.
Here is an example of the form submission:
<form>
<fieldset>
<legend>Question 1</legend>
<input type="radio" name="answer1" value="a" id="1a"><label for="1a" > A.</label>
<br>
<input type="radio" name="answer1" value="b" id="1b"><label for="1b"> B.</label>
<br>
<input type="radio" name="answer1" value="c" id="1c"><label for="1c"> C.</label>
<br>
<input type="radio" name="answer1" value="d" id="1d"><label for="1d"> D.</label>
</fieldset>
<input type="button" id="answer" class="" value="ANSWER">
</form>
The main thing I want to lock down is that when the user has selected a radio button and clicked on the answer button, that value is stored on my PHP file. If the user has 3 correct answers so far, it should keep those 3 correct answers. It will all be evaluated when the user answers all 10 questions after clicking on the submit button on the question 10.
I've looked into destroying form data for a session and using another PHP file to redirect, but I'm still confused on some areas. For example, if the user is on question 4 and decides for whatever reason to refresh the page, does the form data from questions 1-3 get destroyed as well?
Let me know if there's anything else I can provide or clarify.
I see that you are using a session, simly use a session variable to save the reached question, and another session to save the counter of correct answer.
Then in the header of each page, check by PHP script which question does the user reached.
<?php
session_start();
if(!$_SESSION['question_id']){
$_SESSION['question_id'] = 1;
$_SESSION['correct_answers'] = 0;
}
$question_id = $_SESSION['question_id'];
// select question where question_id = $question_id
// select all choices and correct answer ($correct_answer)
// print the question with the choices
if(isset $_post['submit']){
if($correct_answer == $_POST['choice']){
$_SESSION['correct_answers']+=1;
$_SESSION['question_id']+=1;
}
}

Jquery change <p> text programmatically

EDIT: The solution was to add this to the profile page instead of the gender page.
$('#profile').live( 'pageinit',function(event){
$('p#pTest').text(localStorage.getItem('gender'));
});
I have a paragraph with som text in a listview that I want to change programatically from another page after clikcing save.
EDIT: This is my listview in profile.html. When you click on the item you get to another page where you can save your gender. I want to change the paragraph in this listview to the gender that was changed from the other page.
<ul data-role="listview" >
<li><a href="gender.html">
<img src="images/gender2.jpg" />
<h3>Gender</h3>
<p id="pTest">Male</p>
</a></li> </ul>
The gender html page is just basic stuff with two radio buttons and a save button.
Here is my javascript code(in a seperate file):
$('#gender').live('pageinit', function(event) {
var gender = localStorage.getItem('gender');
var boolMale = true;
if (gender == "female") boolMale = false;
$('#radio-choice-male').attr("checked",boolMale).checkboxradio("refresh");
$('#radio-choice-female').attr("checked",!boolMale).checkboxradio("refresh");
$('#saveGenderButton').click(function() {
if ($('#radio-choice-male').is(':checked'))
localStorage.setItem('gender', "male");
else localStorage.setItem('gender', "female");
$('#pTest').html('test'); //does not work
//$('p#pTest').text('test'); //does not work
//$('#pTest').text('test'); //does not work
$.mobile.changePage("profile.html");
});
});
I have tried this with javascript: $('p#pTest').text('test');
The text does not change however. (I know that the save button works). Is this possible?
Try the following, note that when the user refreshes the page, the value is "Male" again, data should be stored on a database.
$('button').click(function(){
$('#pTest').text('test')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<p id="pTest">Male</p>
<button>change</button>
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
Inserting Data Into a MySQL Database using PHP
It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?
something like this:
$("#gender").trigger("pageinit");

Changes made to HTML output (ASP.Net) using JavaScript immediately undone

I have a page on which a list of properties is displayed (i.e houses). This list is made up using CSS. So I've built a second CSS class, which makes the properties/houses align properly in 2 columns. Until now I did this by pressing a button, posting back, and outputting different html (basicly the same, but with other Css class references).
Now I found this question on SO and I implemented a basic scenario. A div with the class "yellow" is written to the html page, and a button changes this class to "red". This happens, but the div immediately changes back to class "yellow".
I'm a very very beginner in JS but not a beginning programmer. This would be a great addition to my site, but I can't find a proper answer. I apologize if this question is redundant.
<script type="text/javascript">
function changeView() {
document.getElementById("box").className = " red";
}
Grtz, thanks in advance, Christophe,
By default a button element is of type 'submit' - which will cause your browser to post back to the server.
Try changing the type to button instead.
<input type="button" ....
More info on the difference here... Difference between <input type='button' /> and <input type='submit' />
If your button causes a postback (possibly a server control with an asp: tag), the javascript changes you made will be lost as by default an asp button submits a page to the server as a result of which your page reloads.
If all you need to change the class of a div make it a simple html button like
<input type="button" onclick="changeView()" value="Change" />

Categories

Resources