Form not triggering javascript onsubmit event - php

I have created a "signup" page on my site, but the javascript validation function does not seem to call when the "onsubmit" event is fired. I have already read the posts on this site regarding a similar issue, but their problem seems to be that they forgot to return a boolean value indicating to go ahead and perform the action. Note that this page is "included" in another page with the php function "include".
<script type="text/javascript">
function validateForm() {
//alert();
var display = document.getElementById('error');
var usernameValue = document.getElementById('username').value;
var passwordValue = document.getElementById('password').value;
var rptPasswordValue = document.getElementById('rptPassword').value;
var emailValue = document.getElementById('email').value;
var aliasValue = document.getElementById('alias').value;
if (usernameValue != '' && passwordValue != '' && rptPasswordValue != '' && emailValue != '' && aliasValue != '') {
if (passwordValue == rptPasswordValue) {
if (usernameValue.length > 32 || aliasValue.length > 32) {
displayError("Username or password is too long (Both fields must contain 32 characters or less)");
} else {
if (passwordValue.length > 32 || passwordValue.length < 4) {
displayError("Password must be between 4 and 32 characters in length.");
} else {
if (emailValue.indexOf('#') == -1 || emailValue.length > 64 || emailValue.length < 6) {
displayError("Please make sure you have entered a valid email. (Emails must be between 6 and 64 characters in length)");
} else {
if (aliasValue < 3 || aliasValue > 32) {
displayError("Your alias must be between 3 and 32 characters in length.");
} else {
return true;
}
}
}
}
} else {
displayError("Please make sure both passwords match.");
}
} else {
displayError("Please make sure each field contains a value.");
}
return false;
}
function displayError(var msg) {
document.getElementById('error').innerHTML = msg;
}
</script>
<h1>Sign Up</h1>
<p>All fields must be filled out in order for an account to be created.</p>
<form onsubmit="return validateForm();" action="register.php" method="post">
<table>
<tr>
<td>
<p class="txtLabel">Username:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="0" id="username" name='username'>
</td>
<td>
<p class="txtLabel">Email Address:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="1" id="email" name='email'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Password:</p>
</td>
<td>
<input type="password" class="defaultTxt" tabindex="2" id="password" name='password'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Repeat Password:</p>
</td>
<td>
<input type="password" class="defaultTxt" tabindex="2" id="rptPassword" name='rptPassword'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Nickname/Alias:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="4" id="alias" name='alias'>
</td>
</tr>
</table>
<p><b id='error' style='color: red'></b></p><br />
<input type="submit" value='' name='submit' class="submitBtn">
</form>
Note that in the validateForm function the alert was used to test if the function was called at all, it isn't.
Any ideas?

function displayError(var msg) {
document.getElementById('error').innerHTML = msg;
}
Replace it with
function displayError(msg) {
document.getElementById('error').innerHTML = msg;
}
In your java-script function you cant write like function displayError(var msg).
Good luck.

Bug in your JavaScript here:
function displayError(var msg) {
^^^
document.getElementById('error').innerHTML = msg;
}
You do not need the var keyword in a methods parameters.

Related

Using Ajax with PHP to search for duplicate user and send an image to the page

I'm trying to display an error message next to the username input when there is a duplicate username. It will search through the database when user start to key in a string. If there isn't any duplicate username, it will show a tick beside the username input.
Now the problem is it didnt show the image but show this message beside the input 'Champ 'test' inconnu dans where clause'
How can i fix this? Here's my code.
register.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Video Game Rental - Sign up</title>
<link href="css/main.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<SCRIPT type="text/javascript">
pic1 = new Image(16, 16);
pic1.src = "pic/loader.gif";
$(document).ready(function(){
$("#username").change(function() {
var usr = $("#username").val();
if(usr.length >= 1)
{
$("#status").html('<img src="pic/loader.gif" align="absmiddle">');
$.ajax({
type: "POST",
url: "check.php",
data: "username="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img src="pic/tick.gif" align="absmiddle">');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
});
//-->
</SCRIPT>
</head>
<body>
<div id="whitebox">
<form action="record.php" method="post" enctype="multipart/form-data" onSubmit="return myFunction(this);">
<table>
<tr>
<th colspan="3">CREATE AN ACCOUNT</th>
</tr>
<tr>
<td width="200"><div align="right"> </div></td>
<td width="100"><input name="username" type="text" id="username" placeholder="Username" size="20"></td>
<td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td width="200"><div align="right"> </div></td>
<td width="100"><input name="password" type="text" id="password" placeholder="Password" size="20"></td>
<td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td width="200"><div align="right"> </div></td>
<td width="100"><input name="cpassword" type="text" id="cpassword" placeholder="Confirm Password" size="20"></td>
<td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td colspan="3"><br> Profile picture:<br>
<input type="file" name="fileToUpload" id="fileToUpload"> </td>
</tr>
</table>
<script>
function myFunction() {
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("cpassword").value;
var ok = true;
if(pass1 != pass2)
{
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("cpassword").style.borderColor = "#E34234";
ok = false;
}
return ok;
}
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<input name="register" type="submit" class="register" id="register" value="Register">
</form>
<form action="index.php">
<input name="back" type="submit" class="register" id="back" value="Back">
</form>
</div>
</body>
</html>
check.php
<?php
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$conn = mysqli_connect("localhost", "root", "", "videorental");
$query ="SELECT * FROM userinfo WHERE username = $username";
$sql_check = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($conn, $sql_check))
{
echo '<br><font color="red">The nickname <STRONG>'.$username.'</STRONG> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
For me also it looks like you have a syntax error in your query:
$query ="SELECT * FROM userinfo WHERE username = $username";
I guess you are using a string type like CHAR or VARCHAR for your username column in your userinfo table. You need to qoute your strings in SQL queries:
$query ="SELECT * FROM userinfo WHERE username = '$username'";
And as Rasclatt mentioned you should bind your variables in sql because of the risk of sql injection its explained here:
http://php.net/manual/en/security.database.sql-injection.php
i suggest you to use mysqli prepared statements:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

JS Form Validation Fails, Yet Form Still Submits?

It's pretty much as the question suggests, I have a HTML form with JS validation. Now, I'm still debugging fine details with the validation, but the problem is that the onSubmit function fires the errors when they should be, but the form continues to submit - I have no idea why. I've check the million and one similar problems on StackOverflow, but none seem to have the same cause as mine - I've checked and check and checked. If anyone could help, I'd greatly appreciate it.
Also, I know my code can be shortened, but I'll do that when I figure this problem out.
Form:
<form name="registerForm" method="post" action="index.php" onSubmit="return validateForm()">
<table class="formTable" >
<tr>
<td><i class="smallprint">* denotes a required field.</i></td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtUsrName">
</td>
<td>
User Name* <i class="smallprint"> between 6 and 32 characters (letters, numbers and underscores only)</i><br />
<b class="error" id="userNameError">Error: Please enter a user name between 6 and 32 characters, using letters, numbers and underscores</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtFName">
</td>
<td>
First Name*<br />
<b class="error" id="fNameError">Error: Please enter your first name</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtSName">
</td>
<td>
Surname*<br />
<b class="error" id="sNameError">Error: Please enter your surname</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtEmail">
</td>
<td>
Email* <i class="smallprint">Please use a valid email address, it will be used to validate your account</i><br />
<b class="error" id="emailError1">Error: Please enter an email address<br /></b>
<b class="error" id="emailError2">Error: This is not a valid email address</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtEmailConf">
</td>
<td>
Confirm Email*<br />
<b class="error" id="emailConfError">Error: Both email addresses must match</b>
</td>
</tr>
<tr>
<td>
<input type="password" maxlength="32" width="32" name="regTxtPassword">
</td>
<td>
Password* <i class="smallprint">Between 6 and 32 characters, using at least one letter and one number</i><br />
<b class="error" id="passwordError">Error: Please enter a valid password</b>
</td>
</tr>
<tr>
<td>
<input type="password" maxlength="32" width="32" name="regTxtPasswordConf">
</td>
<td>
Confirm Password*<br />
<b class="error" id="passwordConfError">Error: Both email passwords must match</b>
</td>
</tr>
</table>
<br />
<div class="textCenter">
<input type="checkbox" class="center" name="regChkTos"> - Check this box if you agree to the Terms of Service. You must agree in order to regster.
<br />
<br />
<input type="submit" name="regSubmit" value="Register">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm()
{
var noError = true;
if (!validateUserName())
{
noError = false;
}
if (!validateFName())
{
noError = false;
}
if (!validateSName())
{
noError = false;
}
if (!validateEmail())
{
noError = false;
}
if (!validateConfirmEmail())
{
noError = false;
}
if (!validatePassword())
{
noError = false;
}
if (!validateConfirmPassword())
{
noError = false;
}
return noError;
}
function validateUserName()
{
var userName = document.forms["registerForm"]["regTxtUsrName"];
var regex = /^\w+$/;
if (userName.value==null || userName.value=="" || userName.value.length < 6 || !regex.test(userName.value))
{
userName.style.border = "2px solid red";
document.getElementById('userNameError').style.display="inline";
return false;
}
else
{
userName.style.border = "2px solid #0f0";
document.getElementById('userNameError').style.display="none";
return true;
}
}
function validateFName()
{
var name = document.forms['registerForm']['regTxtFName'];
if (name.value == null || name.value == '')
{
name.style.border = "2px solid red";
document.getElementById('fNameError').style.display="inline";
return false;
}
else
{
name.style.border = "2px solid #0f0";
document.getElementById('fNameError').style.display="none";
return true;
}
}
function validateSName()
{
var name = document.forms['registerForm']['regTxtSName'];
if (name.value == null || name.value == '')
{
name.style.border = "2px solid red";
document.getElementById('sNameError').style.display="inline";
return false;
}
else
{
name.style.border = "2px solid #0f0";
document.getElementById('sNameError').style.display="none";
return true;
}
}
function validateEmail()
{
noError = true;
var email = document.forms['registerForm']['regTxtEmail'];
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (email.value == null || email.value == '')
{
email.style.border = '2px solid red';
document.getElementById('emailError1').style.display='inline';
noError = false;
}
else
{
document.getElementById('emailError1').style.display='none';
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.value.length)
{
email.style.border = '2px solid red';
document.getElementById('emailError2').style.display='inline';
noError = false;
}
else
{
email.style.border = '2px solid #0f0';
document.getElementById('emailError2').style.display='none';
}
}
return noError
}
function validateConfirmEmail()
{
var email = document.forms['registerForm']['regTxtEmail'];
var emailConf = document.forms['registerForm']['regTxtEmailConf'];
if (email.value != emailConf.value)
{
emailConf.style.border = '2px solid red';
document.getElementById('emailConfError').style.display = 'inline';
return false
}
else
{
emailConf.style.border = '2px solid 0f0';
document.getElementById('emailConfError').style.display = 'none';
return true
}
}
function validatePassword()
{
var password = document.forms['registerForm']['regTxtPassword'];
if (password.value == null || password.value == '' || password.value.length < 6 || password.value.search(/\d/) == -1 || password.value.search(/[A-z]/) == -1)
{
password.style.border = '2px solid red';
document.getElementById('passwordError').style.display = 'inline';
return false;
}
else
{
password.style.border = '2px solid 0f0';
document.getElementById('passwordError').style.display = 'none';
return true;
}
}
function validatePasswordConf()
{
var password = document.forms['registerForm']['regTxtPassword'];
var passwordConf = document.forms['registerForm']['regTxtPasswordConf'];
if (password.value != passwordConf.value)
{
passwordConf.style.border = '2px solid red';
document.getElementById('passwordConfError').style.display = 'inline';
return false;
}
else
{
passwordConf.style.border = '2px solid 0f0';
document.getElementById('passwordConfError').style.display = 'none';
return true;
}
}
</script>
Yes, this script is on the HTML page where the form is located. I've left every field blank, clicked submit, the errors pop up temporarily, then action="index.php" is invoked anyway.
Thanks for any help at all.
first you need to know where the bug is.
For that, use console.log on each function.
After, your code can be optimized with a better algorithm and regex.
To know where the problem is check each return of each function.
For the main function I will do somthing like that :
function validateForm(){
if (validateUserName() && validateFName() && validateSName() && validateEmail() && validateConfirmEmail() && validatePassword() && validateConfirmPassword()){
return true;
}
return false;
}
edit : check the value of your main function too.
do you have a link for this page directly ?

add recaptcha to a php mail form in joomla 2.5

I am trying to add ReCaptcha into a mail form that I created which is intended for sharing content,
but for some reason the captcha is not being validated when I hit "submit", meaning that even if you enter a wrong text in the captcha, the form will still send the email.
I am using joomla 2.5.8, the recaptcha plugin is enabled (although I don't think it is being intialized since I added the recaptchalib.php myself and I am including the ref to the publickey and privatekey inside the mail form code).
Any help would be very much appreciated!
Thank you!!
here is the code:
<?php require_once('recaptchalib.php'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function validateEmail($email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) )
{
return false;
}
else
{
return true;
}
}
function validateForm()
{
var form = document.mailForm;
if (form.recipient.value == "" || validateEmail(form.recipient.value)==false)
{
alert("bad email");
return false;
}
if (form.subject.value == "")
{
alert("please enter subject");
return false;
}
if (form.content.value == "")
{
alert("please enter massage");
return false;
}
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
if (!$resp->is_valid)
{
alert("try again");
return false;
}
return true;
}
</script>
<?php
if($this->success=='1')
{
echo JText::_('MAIL_SEND_SUCCESSFULLY');
}
elseif($this->success=='0')
{
echo JText::_('MAIL_SEND_FAILED');
}
?>
<div id="SendMail">
<h2>send mail</h2>
<form action="index.php" name="mailForm" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td><label><?php echo JText::_('MAIL_SEND_TO'); ?>:</label></td>
<td><input type="text" name="recipient" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_SUBJECT'); ?>:</label></td>
<td><input type="text" name="subject" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_MESSAGE'); ?>:</label></td>
<td>
<textarea name="content" rows="10" cols="40"></textarea>
<br/><?php echo JText::_('MAIL_DESC'); ?>
</td>
<tr>
<td><?php $publickey = "public key"; ?></td>
<td><?php echo recaptcha_get_html($publickey);?></td>
</tr>
</table>
<p>
<input type="hidden" name="controller" value="mail" />
<input type="hidden" name="task" value="sendMail" />
<div class="button-mail">
<input style="width: 50px;height: 25px;" type="submit" name="submit" value="<?php echo JText::_('SEND'); ?>"/>
<a href="javascript: void window.close()" title="Close Window"><span style="color: #444;
border: #D5D5D5 1px solid; padding: 4px; width: 50px;height: 25px;"><?php echo JText::_('CLOSE'); ?></span></a>
</div>
</p>
</form>
</div>
You have error in the code. Please look this lne
if (!$resp->is_valid)
{
alert("try again");
return false;
}
Where $resp->is_valid is the PHP but executed as JS.
Correct code would be
if (!<php (int)$resp->is_valid;?>)
{
alert("try again");
return false;
}
But it will not work anyway because of 2.
You cannot check recaptcha code in Javascript validation. It should be checked server side. Or if you want to check with javascript it should be checked with AJAX request to server. That is because you code
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
is executed on form load before even user eneter captcha.

validate update form

I am creating a page in which I am fetching data from table and showing data in textbox to allow user to update record. I also validate the user input to textbox. But the problem is when the user does not change any field and click on submit, it validates username field i.e. it always wants to change (or edit textbox) the value of textboxes.
Here is my code:
<?php
include("conn.php");
$id=$_GET['id'];
$sql="SELECT * FROM test WHERE id='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
?>
<script type='text/javascript'>
function formValidator()
{
// Make quick references to our fields
alert("hiiiiiii");
var name = document.getElementById('name').value;
var email = document.getElementById('emailid').value;
var ph = document.getElementById('ph').value;
if( name=="" || name==null)
{
alert("Please Enter user name");
return false;
}
var alphaExp = /^[a-zA-Z]+$/;
if(!name.match(alphaExp))
{
alert("please Enter only Alphabates for Name");
return false;
}
if(email=="" || email=="null")
{
alert("Please Enter Email Address");
return false;
}
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(!email.match(emailExp))
{
alert("please Enter valide email address");
return false;
}
if(ph=="" || ph=="null")
{
alert("Please Enter Phone Number");
return false;
}
var numericExpression = /^[0-9]+$/;
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
}
</script>
<form name="updateform" method="POST" action="update_ind_new.php" onsubmit='return formValidator()'>
<table width="200" border="0">
<tr>
<td>User Name</td>
<td>E-Mail</td>
<td>phno</td>
</tr>
<tr>
<td><label>
<input name="name" type="text" id="name" value=" <?php echo $row['name']; ?>" >
</label></td>
<td><label>
<input name="email" type="text" id="emailid" value=" <?php echo $row['emailid']; ?>" >
</label></td>
<td><label>
<input name="ph" type="text" id="ph" value=" <?php echo $row['phno']; ?>" >
</label></td>
</tr>
<tr>
<td> <input name="id" type="hidden" id="id" value=" <?php echo $row['id']; ?>"></td>
<td><label>
<input type="submit" name="Submit" value="Submit">
</label></td>
<td> </td>
</tr>
</table>
</form>
write return true; at the end of this line
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
return true;
Put return true; at the end of all the conditions in the validation function
or put a validations in "if else if else" conditions

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