displaying results of php quiz without page reload - php

This is a simple one, but I just can't figure it out.
I have a simple form:
<form action='#' method="post">
<label for="question-1">Question One</label>
<input type="radio" name="question-1-answers" value="1" />
<input type="radio" name="question-1-answers" value="2" />
<label for="question-2">Question Two</label>
<input type="radio" name="question-2-answers" value="1" />
<input type="radio" name="question-2-answers" value="2" />
<input type="submit" value="Submit Quiz" class="submit"/>
</form>
Then I have simple php in results.php to calculate the results:
<?php
$answer1 = $_POST['question-1-answers'];
$answer2 = $_POST['question-2-answers'];
$result = 0;
$a =array( 0=> "$answer1", 1=> "$answer2");
$result = array_sum($a)/count(array_filter($a));
echo "Your score is: "; echo round($result, 1);
?>
This all works great, but I want the result to show up on the same page as the quiz when the user presses the submit button, without a page reload. I know I need to use jQuery, but everywhere I look has a different way of doing it, and nothing works.
Edit:
So I added the following:
$function() {
$.get('../results.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
}
and
<div class="result">The results are:</div>
and updated the submit button with <input type="submit" value="Submit Quiz" class="submit" onclick="function()"/>
I'm still not getting anything when I click the submit button, and when I check the console the only error I get is: Uncaught SyntaxError: Unexpected token { but I don't know where I have an extra {.

You'll want to use jQuery to load a PHP quiz result HTML page. You then want to inject it into the dom.
Include jQuery, and then this example should work, assuming quiz result page is at (php/quizResult.php) - you can set this up as you like
jQuery
$.get('php/quizResult.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
HTML
<div class="result"></div>
Put the jQuery in a function in JavaScript, and call it when you want to load the results.

Here is an example as Christian has hinted at:
$.post('/callcenter/admin/postContacts', data, function(returnedData) {
// do something here with the returnedData
console.log(returnedData);
});
Your PHP page would then return JSON.
Ref. Pass data from jQuery to PHP for an ajax post

Related

Post Check Box in PhP

i got this annoying problem i can't figure out how to solve
After a quick research i found those links bellow, which i could partially make work
verifying if checkbox is checked in php
How to read if a checkbox is checked in PHP?
This is my html:
<form method="post">
<!-- CHECK BOX TIPO DE PRODUTO (INTEIRO/PEDAÇO) !-->
<input type="checkbox" name="stipo" id="stipo" value="1" onchange="document.getElementById('tipo').disabled = !this.checked;">Tipo
<select name="tipo" id="tipo" disabled="false">
<option value="Inteiro">Inteiro</option>
<option value="Pedaço">Pedaço</option>
</select><br>
<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">
</form>
and this is my php:
if ($_POST['stipo'] == 1){
echo "123";
} else {
echo "456";
}
Because at the Html code im using form like this:
<form method="post">
</form>
and making the post with a submit button like that:
<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">
It doesn't work due to the Href at the submit button.
However, if i do the Html code like this:
<form action="/consulta/consulta_produto.php" method="post">
<input type="submit" class="loader" value="Consultar">
</form>
It will work. But, the problem of the form above is that my script stop working. I Cant use the method above because i need Href into the submit button, because when i submit the form, im loading the next page inside a Div
Just in case it helps, this is my Javascript and why i need the Href
<script type="text/javascript">
$(function() {
$('.loader').click(function(event) {
event.preventDefault(); // stop the link loading the URL in href
$('#content').load($(this).attr('href'));
});
});
</script>
Anyone got some idea on how to make the POST method works with href instead of action on the form?

PHP/JQuery Redirect

I have a 3 page registration site. When the user selects one of three options on the first page they can submit and move onto the 2nd page. There they fill out information and click submit which should take them to the third page. The problem is the jquery redirect code after clicking submit on the 1st and 2nd page is NOT working. This is the code in the first page:
<?php
session_start();
$errors = false;
$message="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST['Reg_type']) || !preg_match('/^[123]$/', $_POST['Reg_type'])) {
$message = "Please select an option";
$errors = true;
}
if (!$errors) {
$_SESSION["regtype"]=$_POST["Reg_type"];
header("Location: Registration_2.php");
exit;
}
}
?>
<div id="form_page1">
<form id="frmtype1" name="frmtype1" method="post">
<input type="radio" name="Reg_type" value="1"/> option1 <br/>
<input type="radio" name="Reg_type" value="2"/> option2 <br/>
<input type="radio" name="Reg_type" value="3"/> option3 <br/>
<input type="submit" name="Submit" value="Submit" />
<?php
if($errors)
echo $message;
?>
I'm trying to convert that php code into javascript and this is what I have:
<script>
$(document).ready(function(e) {
$("form").submit(function() {
var data= $(this).serialize();
alert(data);
$.post("/Registration_1.php",$("#form_page1").serialize());
window.location.replace("http://www.google.com"); //just for testing purposes
});
});
</script>
But for some reason the jquery stuff just WON'T work, so i have to use the php instead. Can anyone tell me what the problem is? Does the first argument of the post method have to be the page you want to go to (Registration_2.php) or the page you are asking data from? Hopefully if the first page's jquery code is fixed it can fix the 2nd page. I've been working/researching this problem for the past 3 hours to no avail. Please help, thank you.
Why choose such a complicated solution?
Form 1:
<form action="form2.php" method="post">
<input type="submit" >
</form>
Form 2:
<form action="form3.php" method="post">
<input type="submit">
</form>
etc. etc.

Using jQuery AJAX to pass checkbox data

I am trying to pass values of selected checkboxes to a PHP file using jQuery's .getJSON method.
Problem: The values does not seem to be received by the PHP file. I am using print_f to see if the PHP file has received the form data. Looking at the return data, the error PHP throws [Undefined index:] tell me that the 2 arrays $bedroom and $bathroom are not defined. How do I get this to work?
HTML Code
<form action="form_ajax.php" method="post">
<input type="checkbox" name="bedroom[]" value="1">
<input type="checkbox" name="bedroom[]" value="2">
<input type="checkbox" name="bedroom[]" value="3">
<input type="checkbox" name="bathroom[]" value="1">
<input type="checkbox" name="bathroom[]" value="2">
<input type="checkbox" name="bathroom[]" value="3">
<input type="submit" id="button" value="submit!!!">
</form>
jQuery Code
$(function() {
$("#button").click(function(e) {
e.preventDefault();
var other_data = "hello";
$.getJSON("form.php", {some-other-data: other_data, bedroom: bedroom[], bathroom: bathroom[]}, function(data) {
console.log(data);
});
});
});
PHP Code
<?php
$bedroom = $_GET['bedroom'];
$bathroom = $_GET['bathroom'];
print_r($bedroom);
print_r($bathroom);
?>
According to the jQuery documentation of $.getJSON() the data is passed as querystring variables, so I would suggest you try to use $_GET instead:
$bedroom = $_GET['bedroom'];
$bathroom = $_GET['bathroom'];
Edit, how to send all form-data to the php-file:
If you add an id attribute to the form-tag, you can easily use jQuery to serialize the form, like this, and pass that as the data object in $.getJSON():
$.getJSON("form.php", $("#your-form-id").serialize());
Then all your selected checkboxes should be passed along to the PHP-file.

PHP result display in textbox onClick

I need to get result where PHP generated ID for current button click is displayed in html textfield...
Is there any easy way of doing this?
This is the link of what I am trying to do http://dtech.id.lv/lat.php
When user first comes he doesn't have code, so he clicks get code.
I need that php generated code is pasted in textbox after this click...
Could someone help?
Thank you!
Button clicked, something shows in the text field. Sometimes Javascript isn't necessary.
<?php
$code = "";
if (isset($_POST['buttonId']))
{
$code = 'Some code here';
}
?>
<form method="post" >
<input name="textField" id="textField" type="text" value="<?php echo $code; ?>" />
<input name="buttonId" id="buttonId" type="submit" value="Submit" />
</form>
Assuming your html looks like this:
<button id="myPHPid">...</button>
<input type="text" id="idRecipient" />
then
<button id="myPHPid" onclick="document.getElementById('idRecipient').value = this.id">...</button>
try this code
$('button').live('click',function() {
var $butVal= $(this).val();
alert($butVal);
$('input#buttonValue').val($butVal);
return false;
});
live DEMO

jQuery trigger click via $.post

I'm submitting data from pagex.php to pagey.php via jQuery post.
pagex.php contains
$('#btn').click(function(e) {
e.preventDefault();
var x = 'variable1';
var y = 'variable2';
$.post("/pagey.php", { var1: x, var2: y}, function(data) {});
});
pagey.php contains
<form action=....>
<input type="text" name="x" value="<?php echo $_POST['var1'] ?>" />
<input type="text" name="y" value="<?php echo $_POST['var2'] ?>" />
<input id="submit" type="submit" value="submit" />
<script type="text/javascript">$('#submit').trigger('click')</script>
So basically when i post the values from pagex.php to pagey.php, i want to automatically submit the form on pagey.php . The jQuery line at the end of pagey.php will trigger an automatic click to the submit button. However jQuery is not triggering the submit click. it works if i access paygey.php directly (i tried it with pre defined variables) but not by doing $.post from pagex. I was assuming that by using $.post from pagex, pagey should automatically get the values and run the jQuery submit. What is the problem here.
JavaScript (which powers jQuery) is not run on the server, it's run from your users browser. So from my understanding, in order to run that little bit of script you will have to actually send your users to pagey.php
<input type="text" name="x" value="<?php echo $_POST[var1] ?>" />
<input type="text" name="y" value="<?php echo $_POST[var2] ?>" />
should be
<input type="text" name="x" value="<?php echo $_POST['var1'] ?>" />
<input type="text" name="y" value="<?php echo $_POST['var2'] ?>" />
You need to fix your array indices.
you should post directly to the action url on pagey... what is the value of pagey if its a simple form that auto posts.
simple answer is to do a form post on document.ready in pagey...
I think the bigger question is why are you posting data to pagey if you just re-post it to another page using your form action?
Try posting the data directly to the action page and let us know if that works.
I bet this will be useful to some of you. Regards.
<?php
echo
"<script type='text/javascript'>
$(document).ready(function() {
$('#submit').trigger('click');
});
</script>";
?>

Categories