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;
}
Related
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'];
I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})
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?
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>
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.