PHP questionnaire strategy - php

I am designing a questionnaire, the code I've written is a combination of JS and PHP. I have the questions in one page but I want to ask each question on a separate page and the consecutive questions should be asked according to the answer the user select. what is the best strategy to do that? do I need to include SQL as well?
and at the end the answers will be written in a text file
the code I have is:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['name']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
$varName = $_POST['name'];
$varLand1 = $_POST['landscape1']; $varLand2 = $_POST['landscape2'];
$varCom = $_POST['comment'];
$varAppx = $_POST['appx'];
$clim = $_POST['landscape'];
$varMech = $_POST['mechanism'];
$varMechoth = $_POST['mech'];
if(empty($errorMessage))
{
$fs = fopen("$varName.txt" ,"a+");
fwrite($fs,$varName . "\n" . $varLand1 . ' ' .$varLand2 . "\n" . $clim . "\n" . $varAppx . "\n" . $varCom . "\n" . $varMech .$varMechoth);
fclose($fs);
header("Location: t-y.html");
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script scr="jss.js" type="text/javascript"></script>
<title>Questionnaire</title>
</head>
<body>
<FONT FACE="Times New RomanPS">
<H1>Questionnaire</H1>
<P>Please fill out this questionnaire:
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="index.php" method="post">
<p>
Name<br>
<input type="text" name="name" maxlength="50" value="<?=$varName;?>" />
</p>
<ul>
<p> 1 - Q1?
<p><input type="checkbox" name="landscape1" value="urban"> Urban<br>
<p><input type="checkbox" name="landscape2" value="non-urban"> non-Urban<br>
<p> 2 - Q2?<br>
<input type="radio" name="landscape" value="Dry"> Dry<br>
<input type="radio" name="landscape" value="Tropical"> Tropical<br>
<input type="radio" name="landscape" value="Moderate"> Moderate<br>
<input type="radio" name="landscape" value="Continental"> Continental<br>
<input type="radio" name="landscape" value="Polar"> Polar<br>
<p> 3 - Q3? <br>
<input type="radio" id="mecha" name="mechanism" value="sub" onclick="hideTextBox1()"/> Subsidence<br>
<input type="radio" id="mecha" name="mechanism" value="earth" onclick="hideTextBox1()"/> Earthquake<br>
<input type="radio" id="mecha" name="mechanism" value="volc" onclick="hideTextBox1()"/> Volcanic<br>
<input type="radio" id="mecha" name="mechanism" value="<?=$varMech;?>" onclick="displayTextBox1()"/> other<br>
<div id="otherTextBox1" style="display:none;visibility:hidden;">
<input type="text" name="mech" maxlength="20" value="<?=$varMech;?>">
</div>
<p> 4 - Q3?<br>
<input name="choice" id="choice4" type="radio" value="four" onclick="hideTextBox()"/><label for="choice4"> No </label><br>
<input name="choice" id="choice5" type="radio" value="other" onclick="displayTextBox()"/><label for="choice5"> Yes </label>
<br/>
<div id="otherTextBox" style="display:none;visibility:hidden;">
[mm/yr]<br><input type="text" name="appx" maxlength="3" value="<?=$varAppx;?>">
</div>
<br/>
<p> 5 - Q4
<p> 6 - Q5
<p> 7 - Q6
<p>
Comments:<br>
<textarea type="text" name="comment" cols=48 rows=4 maxlength="1000" value=" <?=$varComment;?>"></textarea>
</p>
<p><input type="reset"> <input type="submit" name="formSubmit" value="Submit" />
</ul>
<script>
function displayTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'block';
otherTextBox.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'none';
otherTextBox.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('choice');
var objElement;
var boolContinue = false;
var objOtherText;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'choice5')
{
objOtherText = document.getElementById('othertext');
if(strTrim(objOtherText.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
function displayTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'block';
otherTextBox1.style.visibility = 'visible';
}
function hideTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'none';
otherTextBox1.style.visibility = 'hidden';
}
function validate1()
{
var arrElements1 = document.getElementsByName('mechanism');
var objElement1;
var boolContinue = false;
var objotherText1;
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else<?=$varMech;?>
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* #param: {String} String to trim.
*
* #return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
</script>
</form>
</FONT>
</body>
</html>

I don't think you would NEED to use SQL to do this. You should be able to use the $_SESSION to store the answers to previous questions and adjust the questions on the following pages accordingly.

Related

php input form can only be numbers not words

i made a form where you can put a number and show which one is the highest.
i want to make sure you can put any words in this form.
that there show a notification you cant put words in the form
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="text" name="tweedegetal" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
The following code shows a notification when a letter is typed.
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" id="eerstegetal" name="eerstegetal" oninput="Eerste_check()" placeholder="Eerste getal"><br>
<input type="text" id="tweedegetal" name="tweedegetal" oninput="Tweede_check()" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script>
function Eerste_check(){
var eerstegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(eerstegetal)){
alert('Eerstegetal should contain only numbers.')
}
}
function Tweede_check(){
var tweedegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(tweedegetal)){
alert('Tweedegetal should contain only numbers.')
}
}
</script>
Try the following:
<input type="number" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="number" name="tweedegetal" placeholder="Tweede getal"><br>
I hope it helps

PHP - Can not access the checkbox value that has been checked

For my databases project I am doing this form where a user can select the information he wants and it will be displayed on a html page. For the time being I am implementing only the checkboxes where I am encountering a problem.
The problem is that when I check the checkboxes (for my current implementation I am only interested in the case where the user checks "Location"+ "Pipe-Type" + "Amount") in my action page "fe_page2.php", the if condition that checks to see if the checkboxes are checked is never being reached instead it always goes to the else condition. The code is provided below.
This is my basic html page:
<html>
<head>
<title>Flow Element</title>
</head>
<body>
<h1 style="margin-left: 450px">Retrieve Flow Element Information</h1>
<hr>
<form action="fe_page2.php" method="post">
All Times:
<input type="checkbox" name="alltimes" onchange="changeFields()"><br><br>
Start Date:
<input type="date" name="startdate" id="startdate">
Start Time:
<input type="time" name="starttime" id="starttime"><br><br>
Same Time:
<input type="checkbox" name="sametime" id = "sametime" onchange="sameFields()"><br><br>
End Date:
<input type="date" name="enddate" id="enddate">
End Time:
<input type="time" name="endtime" id="endtime"><br><br>
<h3> Select fields of output</h3>
<hr>
Pipe Key: <input type="text" name="pipepirmary" id="pipekey"><br>
<input type="checkbox" name="pipelocation" id="pipeLocation" value="value1" >
Location<br>
<input type="checkbox" name="Pipe-Type" id="pipetype" value="value2">
Pipe-Type<br>
<input type="checkbox" name="amount" id="amount" value="value3">
Amount<br><br>
Flow Element:<input type="text" name="fepirmarykey" id="fekey"/><br>
<input type="checkbox" name="flow" id="flo">
Flow<br>
<input type="checkbox" name="temperature" id="temp">
Temperature<br>
<input type="checkbox" name="pressure" id="pres">
Pressure<br><br>
<input type="submit">
</form>
<script>
function changeFields() {
if(document.getElementById("startdate").disabled == false){
document.getElementById("startdate").disabled = true;
document.getElementById("starttime").disabled = true;
document.getElementById("enddate").disabled = true;
document.getElementById("endtime").disabled = true;
document.getElementById("sametime").disabled = true;
if(document.getElementById("sametime").checked = true){
document.getElementById("sametime").checked = false;
}
document.getElementById("startdate").value = null;
document.getElementById("starttime").value = null;
document.getElementById("enddate").value = null;
document.getElementById("endtime").value = null;
}
else{
document.getElementById("startdate").disabled = false;
document.getElementById("starttime").disabled = false;
document.getElementById("enddate").disabled = false;
document.getElementById("endtime").disabled = false;
document.getElementById("sametime").disabled = false;
}
}
function sameFields() {
if(document.getElementById("enddate").disabled == false){
document.getElementById("enddate").disabled = true;
document.getElementById("endtime").disabled = true;
document.getElementById("enddate").value = null;
document.getElementById("endtime").value = null;
}
else{
document.getElementById("enddate").disabled = false;
document.getElementById("endtime").disabled = false;
}
}
</script>
</body>
</html>
This is the php page fe_page2.php
<?php
require('dbconf.inc');
db_connect();
print"<pre>";
print_r($_POST);
print"</pre>";
$pipelocation = $_POST[pipelocation];
$pipetype = $_POST[Pipe-Type];
$pipeamount = $_POST[amount];
if($pipelocation=='value1' && $pipetype == 'value2' && $pipeamount == 'value3'){
$qrySel="SELECT `Pipe_ID`, `Location`, `Amount`, `PipeType` FROM pipe order by Pipe_ID desc";
$resSel = mysql_query($qrySel);
if($resSel){
while($rowpipe = mysql_fetch_array($resSel, MYSQL_ASSOC)){
echo "Pipe ID:{$rowpipe['Pipe_ID']} <br> ".
"Location: {$rowpipe['Location']} <br> ".
"Amount: {$rowpipe['Amount']} <br>".
"PipeType: {$rowpipe['PipeType']} <br>".
"--------------------------------<br>";
}
echo "Fetched Data Successfully!\n";
}
}
else{
echo"never went in!";
}
db_close();
?>
I have tried different things such as
if(isset($pipelocation) && isset($pipetype) && isset($pipeamount)){
.....
}
and removing the value from html page and using the following piece of code:
if($pipelocation == 'on' && $pipetype == 'on' && $pipeamount == 'on'){
...
}
But still no luck...
Any help would be appreciated.
The code that is presented is purely my work but does include pieces of code that comes from the provided reference below:
https://www.youtube.com/watch?v=LZtXYa9eGGw
You missed the quotations here:
$pipelocation = $_POST['pipelocation'];
$pipetype = $_POST['Pipe-Type'];
$pipeamount = $_POST['amount'];

HTML form with 2 (hidden) submit buttons and 1 other hidden input

I'm trying to build this application that runs on Android tablets with barcode scanners attached.
The barcode scanners send an Enter after each scanned code.
I need to scan 2 barcodes and submit the form.
I created a form with two sets of input + submit button, the second one hidden. After the first barcode is scanned and the scnner send the Enter key, the hidden elements are revealed and I can scan the second barcode. However, the second time the Enter key doesn't work. It only work if I push the button (after I unhide it).
How can I take care of this so it will not need user input (other than scanning barcodes)?
Here's my code so far:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
</fieldset>
</form>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
</script>
And the barcode.php file:
<?php
ob_start();
mysql_connect ("localhost","root","root") or die (mysql_error());
mysql_select_db ("eficacitate");
$barcode = $_POST["barcode"];
$kos = $_POST["kos"];
$marca = $_COOKIE["marca"];
$operation = $_COOKIE["operation"];
if (substr($barcode,0,1)=="^") {
$j_nou = substr($barcode,1,strpos($barcode, "|")-1);
$parts = explode('|',$barcode);
$of_nou = $parts[1];
$cantitate_nou = $parts[2];
$serie_nou = $parts[3];
$adauga="INSERT INTO master (marca, operation,j,of,cantitate,serie,kos)
VALUES
('$marca','$operation','$j_nou','$of_nou','$cantitate_nou','$serie_nou','$kos')";
mysql_query($adauga);
}
header('Location: /eficacitate/scan.php');
ob_flush();
?>
Please give this a try:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button id='barcodeButton' style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button id='kosButton' type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
document.onkeydown = function(event) {
if (event.keyCode == '13') {
barcodeButton = document.getElementById('barcodeButton');
kosButton = document.getElementById('kosButton');
if (document.getElementById('my_popup').style.display == 'none') {
barcodeButton.click();
show_popup('my_popup');
} else {
kosButton.click();
hide_popup('my_popup');
}
}
}
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
Let me know if this solves what you are trying to achive. Just out of curiosity, why aren't you using jQuery here?

display alert when form is submitted

I need to display the alert saying thanx your msg is received but this doesnot works so please hel me out how to do.Is there coding error or what i coudnt get to it.i would pe pleased if someone helps me out.thankyou
<h4>Send Your Feedback Here.<p>
<form name ="register" action="contact.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="validate()">Send</button>
</p>
</form>
<script type="text/javascript">
function validate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y)
{
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="")
{
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="")
{
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="")
{
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="")
{
alert(msg);
}
else
{
<?php
//Get message data.
$name = $_POST['name'];
$message = $_POST['message'];
$email=$_POST['email'];
$ver = $_POST['ver'];
$rval = $_POST['rval'];
if($ver==$rval)
{
//Email it.
mail(
'example#example.com', //Where to send
"Contact form - $name", //Email subject
$message, //Message body
$email //email address
);
echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>";
}
else
{
echo "<script type=\"text/javascript\">alert('Wrong captcha');</script>";
}
?>
}
}
You can't mix JavaScript and PHP like that. The PHP will be parsed on the served before the page is served up to the user. Including it inside of your JavaScript else block will have no effect, since the code will be run when the page is generated anyway.
You should look into the use of AJAX.
<script type="text/javascript">
function thevalidate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y) {
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="") {
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="") {
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="") {
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="") {
alert(msg);
} else {
<?php
//You need to process data here..
?>
}
}
</script>
<h4>Send Your Feedback Here.<p>
<form name ="register" action="php/process.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="thevalidate()">Send</button>
</p>
</form>

reload only a module in joomla?

I have a module that lets users rate an image. The problem is that when the user hits the submit button to rate, it reloads the entire page instead of just the module. Is it possible to make it so that it reloads just the module, or at least if it has to reload the entire page to make it automatically take the user back to the bottom of the page where the module is?
<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>
<script type="text/javascript">
function getCheckedRadio(radio_group)
{
for (var i = 0; i < radio_group.length; i++)
{
var button = radio_group[i];
if (button.checked)
{
return button;
}
}
return undefined;
}
function trim(s){
var i;
var returnString = "";
for (i = 0; i < s.length; i++){
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (c != " ") returnString += c;
}
return returnString;
}
//check is integer
function isInteger(s){
var i;
if(trim(s)==''){return false;}
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
return true;
}
function xmlhttpPost(strURL) {
var xmlHttpReqs = false;
if (window.XMLHttpRequest) {
xmlHttpReqs = new XMLHttpRequest();
}else if (window.ActiveXObject) {
xmlHttpReqs = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReqs.open('POST', strURL, true);
xmlHttpReqs.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReqs.onreadystatechange = function() {
if (xmlHttpReqs.readyState == 4) {
updatepage(xmlHttpReqs.responseText);
setTimeout("window.location = 'index.php'",2000);
}
}
document.getElementById("load").innerHTML ="Loadding...";
xmlHttpReqs.send(getquerystring());
}
function getquerystring() {
var form = document.forms['rateForm'];
var numbervote = form.numbervote.value ;
var name = form.name.value ;
var folder = form.folder.value ;
qstr = 'w='+escape(numbervote)+'&w1='+escape(name)+'&w2='+escape(folder);
return qstr;
}
function chck(){
xmlhttpPost("<?php echo JURI::root(); ?>modules/mod_image_ratting/saverate.php");
}
function updatepage(str){
document.getElementById("load").innerHTML = str;
document.getElementById("load").style.visibility = "visible";
}
function submitVote()
{
var form = document.rateForm;
var checkedButton = getCheckedRadio(document.rateForm.elements.numbervote);
if (checkedButton)
{
selectedvalue = checkedButton.value;
}
if(selectedvalue=='')
{
document.getElementById('numbervoteErr').style.display='block';
return false;
}else if(!isInteger(selectedvalue)){
document.getElementById('numbervoteErr').style.display='block';
return false;
}else if(selectedvalue > 10){
document.getElementById('numbervoteErr').style.display='block';
return false;
}
else
{
chck();
}
}
</script>
<form action="<?php echo JRoute::_( 'index.php' );?>" method="get" name="rateForm" id="rateForm" class="form-validate" >
<table style="width:100%;border:0px;">
<tr>
<td>
<?php if ($link) : ?>
<a href="<?php echo $link; ?>" target="_self">
<?php endif; ?>
<?php echo JHTML::_('image', $image->folder.'/resize/'.$image->name, $image->name); ?>
<?php if ($link) : ?>
</a>
<?php endif; ?>
</td>
</tr>
<?php
//if($image->rates > 0){
?>
<tr>
<td>
<?php JHTML::_( 'behavior.modal' ); ?>
<?php echo $image->rates;?> people liked this photo <a class="modal" href="index2.php?option=com_imageratting&task=viewrates&file=<?php echo $image->name;?>&f=<?php echo htmlentities(urlencode($image->folder));?>" style="text-decoration:underline;">View Full Size Image</a>
</td>
</tr>
<?php
//}
?>
<tr>
<td>
<span>
<input type="radio" name="numbervote" value="1" checked /> 1<br />
<input type="radio" name="numbervote" value="2" /> 2<br />
<input type="radio" name="numbervote" value="3" /> 3<br />
<input type="radio" name="numbervote" value="4" /> 4<br />
<input type="radio" name="numbervote" value="5" /> 5<br />
</span>
<span>
<input type="button" value="Rate the image!" onclick="submitVote();"/>
</span>
</td>
</tr>
<tr>
<td>
<div id="load" style="color:red;font-size:11px;font-style:italic;"></div>
</td>
</tr>
<tr>
<td>
<span style="display:none;color:red;font-size:11px;font-style:italic;" id="numbervoteErr"><?php echo 'Rating must be a number between 0 and 5';?></span>
</td>
</tr>
</table>
<input type="hidden" name="isSaveRate" value="1" />
<input type="hidden" name="option" value="com_imageratting" />
<input type="hidden" name="name" value="<?php echo $image->name; ?>" />
<input type="hidden" name="folder" value="<?php echo $image->folder; ?>" />
<input type="hidden" name="task" value="rate" />
</form>
You can accomplish this using ajax. I'm using code that I've written as an example to show you how it's done. See below:
First you need the module that displays a form e.g.
<form action="#" method="post" name="signup">
<input type="text" name="address" id="address" value="Enter email address" size="30" />
<input type="submit" name="submit" value="Signup" />
<div id="msg"></div>
</form>
Then in the view for this you also need to define mootools ajax:
$document = &JFactory::getDocument();
$document->addScriptDeclaration("
window.addEvent('domready', function(){
$('signup').addEvent('submit', function(e) {
//Prevent the submit event
new Event(e).stop();
var address = $('address').value;
// check email using regex
var address_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!address_regex.test(address)){ $('msg').innerHTML = 'Please enter a valid email address.'; return; }
new Ajax('index.php?option=com_component&task=adduser&template=raw', {
method: 'get',
data: { 'address' : address },
onRequest: function() { $('msg').innerHTML = 'Please wait...'; },
onComplete: function(response) {
if (response != '') $('msg').innerHTML = response;
else msg.html('Please enter your email address.');
}
}).request();
});
});
");
Now you need to accept this ajax request. To do this you need to create a component (as you can see from the ajax url above).
In the controller of this component you need a function:
function adduser() {
$app = JFactory::getApplication();
$model = $this->getModel('signup');
$data = $model->addUser();
echo $data;
$app->close();
}
And finally in the model of the component you deal with the post request (in your case store the vote) and then return any data should you want to.
function signup() {
$address = JRequest::getVar('address', '');
$msg = 'Thank you for registering!';
if ($address != '') {
$db = &JFactory::getDBO();
$address = $db->getEscaped($address); // escape the email string to prevent sql injection
$db->setQuery("SELECT * FROM `#__users` WHERE `email`='$address'");
$db->Query();
if ($db->getNumRows() != 0) $msg = 'You are already registered, thank you.';
else {
$db->setQuery("INSERT INTO `#__users` (`name`, `username`, `email`, `usertype`, `block`, `gid`, `registerDate`) VALUES ('default', '$address', '$address', 'Registered', 0, 18, '".date('Y-m-d H:i:s')."')");
$db->query();
$user_id = $db->insertid();
$db->setQuery("INSERT INTO `#__core_acl_aro` (`section_value`, `value`, `name`) VALUES ('users', $user_id, '$address')");
$db->query();
$aro_id = $db->insertid();
$db->setQuery("INSERT INTO `#__core_acl_groups_aro_map` (`group_id`, `aro_id`) VALUES (18, $aro_id)");
$db->query();
}
} else {
$msg = 'Please enter an email address.';
}
return $msg;
}

Categories