I am having issues with validating some data.
I want to check if someone has reviewed a company before by checking for the company_id and the logged in users account_number in my reviews table.
The code I currently has doesn't ever seem to find anything in the reviews table so doesn't warn people they can't submit another review.
Your help to get this working is much appreciated.
Here is the code I have so far:
Form
<form name="review" id="review" method="post" action="/db_processing/reviews/process-reviews.php">
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
<input type="hidden" value="<?php echo($_SESSION["ID"]) ?>" name="account_number" />
<p class="cs-threequarter">
<b>Comments:</b><br>
<textarea name="comments" style="width:95%; height: 150px"></textarea>
</p>
<p class="cs-quarter">
<b>Rating:</b>
<span class="star-rating">
<input type="radio" name="rating" value="1"><i></i>
<input type="radio" name="rating" value="2"><i></i>
<input type="radio" name="rating" value="3"><i></i>
<input type="radio" name="rating" value="4"><i></i>
<input type="radio" name="rating" value="5"><i></i>
</span>
</p>
<p><input class="cs-btn cs-red" name="submit" type="submit" value="Submit Review!"></p>
<div class="cs-container"></div>
<div class="cs-error-note" id="cs-error-note3"></div>
</form>
<script src="/js/validation/reviewval.js"></script>
jQuery Validation Script
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li",
ignore: "not:hidden",
rules: {
comments: {
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, }
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
Check-account.php
<?php
require('../../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
if(isset($_POST['account_number'])) {
$account_number = $_POST['account_number'];
$compid = $_POST['company_id'];
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number =$account_number && company_id =$compid");
$query->execute();
$rows = $query->fetchAll();
$total_rows = count($rows);
if( $total_rows > 0 ){
echo 'false';
} else {
echo 'true';
}
}
?>
Validation code working fine, there is no problem expect unnecessary comma ,. remove it, Not all browsers are very forgiving.
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li"
ignore: "not:hidden",
rules: {
comments:
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, //<-----Remove this, it's unnecessary
}
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
HTML
The problem is here, because of it validation and query both failing.
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
assign id to this input because you are fetching it's value with id selector in validation script here return $("#company_id").val(); so it will be
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" id="company_id" />
last in PHP
put quotes ' around variables inside query, rest is all good and working.
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number = '$account_number' && company_id = '$compid'");
Related
I recently started learning AJAX for form submitting, but it seems that i'm still missing something essential, because the submitted data won't go to the PHP file like it's suppose to. I don't understand why it won't work.
HTML:
<div class="col-md-6">
<form class="form" action="../wp-content/themes/tempo/cfgs/js/scrollmagic/contact.php">
Eesnimi:
<input name="eesnimi" id="eesnimi" class="required" type="text">
Perekonnanimi:
<input name="pernimi" id="pernimi" class="required" type="text">
E-Post:
<input name="email" id="email" class="required" type="email">
Telefoni number:
<input name="nr" id="nr" class="required" type="text">
Teema:
<input name="teema" id="teema" class="required" type="text">
Sõnumi sisu:
<textarea name="sisu" id="sisu" class="required"></textarea>
<div></div>
<input type="submit" id="sub" value="Edasta">
</form>
</div>
JQUERY/AJAX
$('#sub').click(function(){
$('.form').submit();
var eesnimi = $('#eesnimi').val();
var pernimi = $('#pernimi').val();
var email = $('#email').val();
var nr = $('#nr').val();
var teema = $('#teema').val();
var sisu = $('#sisu').val();
$('.form').validate({
rules:{
eesnimi: {
required: true,
nowhitespace: true,
lettersonly: true
},
pernimi: {
required: true,
nowhitespace: true,
lettersonly: true
},
email: {
required: true,
email: true
},
nr: {
required: false,
integer: true
},
teema: {
required: true
},
sisu: {
required: true
}
},
messages:{
eesnimi: {
required: valituhiErr,
nowhitespace: tuhikErr,
lettersonly: nonumbersErr
},
pernimi: {
required: valituhiErr,
nowhitespace: tuhikErr,
lettersonly: nonumbersErr
},
email: {
required: valituhiErr,
email: emailErr
},
nr: {
required: valituhiErr,
integer: onlynumbersErr
},
teema: {
required: valituhiErr,
},
sisu: {
required: valituhiErr,
}
},
submitHandler: function(){
$.ajax({
type: "POST",
url: "../wp-content/themes/tempo/cfgs/js/scrollmagic/contact.php",
data: $('.form').serialize(),
success: function (o) {
console.log(o);
}
});
}
});
return false;
});
PHP:
<?php
print_r($_POST);
?>
I'm just experimenting, it seems that validation works correctly but the submit function won't, beceause the server won't recieve anything from my ajax request and it won't display anything on console either.
try this : jquery
var data = {
eesnimi = $('#eesnimi').val();
pernimi = $('#pernimi').val();
email = $('#email').val();
nr = $('#nr').val();
teema = $('#teema').val();
sisu = $('#sisu').val();
};
$.ajax({
type : "post",
dataType : "JSON",
url : "register.php",
data : data,
success : function(result)
{
if (result.hasOwnProperty('error') && result.error == '1'){
var html = '';
$.each(result, function(key, item){
if (key != 'error'){
html += '<li>'+item+'</li>';
}
});
//show in html
php
eesnimi = $_POST['eesnimi']
pernimi = ...
email =...
nr = ...
teema = ...
sisu = ...
//connect db
//sqlquery you want validate
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if ($row['eesnimi']==$eesnimi ){
$errors['eesnimi '] = ...;
}
// like this
if (count($errors) > 1){
$errors['error'] = 1;
die (json_encode($errors));
}
//insert into db
}
hope this help
I have seen this example and applied it in my code yet nothing worked, its not working.
Referral ans-1
Referral ans-2
I need to apply jquery validation in ckeditor and I have seen all those past examples even I have mentioned those links above, by doing that step my validation is still not working.
Here is my HTML Code
<div class="elementbox">
<label class="form-label">Content<span class="required">*</span></label>
<div class="controls">
<textarea name="content_body" id="content_body" rows="10" cols="80"><?php echo $content_body; ?></textarea>
</div>
</div>
<script>
var url = "<?php echo base_url(); ?>";
CKEDITOR.replace( 'content_body',{
//extraPlugins: 'imageuploader'
} );
</script>
My Jquery validation code
$("#add_content_pages").validate({
ignore: [],
debug: false,
rules: {
title: {
required: true
},
content_id: {
required: true
},
content_body:{
required: function()
{
CKEDITOR.instances.content_body.updateElement();
}
}
},
messages: {
title: {
required: "Please enter Title"
},
content_id: {
required: "Please Select Content Type"
},
content_body: {
required: "Please enter Content"
}
},
errorPlacement: function (error, element) {
var attr_name = element.attr('name');
if (attr_name == 'type') {
error.appendTo('.type_err');
} else {
error.insertAfter(element);
}
}
});
Any Solution what I am missing?
please check this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
then html form
<form action="" method="post" id="check_form">
<div class="elementbox">
<label class="form-label">Content<span class="required">*</span></label>
<div class="controls">
<textarea name="content_body" id="content_body" rows="10" cols="80"></textarea>
<div id="error_check_editor"></div>
</div>
</div>
<script>
CKEDITOR.replace('content_body');
</script>
<br/>
<input name="submit" type="submit" value="Submit" class="button" id="submit"/>
</form>
then script
<script>
$.validator.addMethod("check_ck_add_method",
function (value, element) {
return check_ck_editor();
});
function check_ck_editor() {
if (CKEDITOR.instances.content_body.getData() == '') {
return false;
}
else {
$("#error_check_editor").empty();
return true;
}
}
$(document).ready(function () {
$("#check_form").validate(
{
ignore: [],
debug: false,
errorPlacement: function (error, element) {
if (element.attr("name") == "content_body") {
error.insertAfter(element);
}
},
rules: {
content_body: {
check_ck_add_method: true
}
},
messages: {
content_body: {}
}
});
});
</script>
I am a bit of a noob with jQuery and am learning for Uni.
I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.
I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.
My form looks like this
<form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
<div>
<label for="name"><b>Name:</b></label><br>
<input type="text" name="name" id="name">
</div>
<div>
<label for="dob"><b>Date of Birth:</b></label><br>
<input type="text" name="dob" id="dob">
</div>
<div>
<label for="visit"><b>Date of Visit:</b></label><br>
<input type="text" name="visit" id="visit">
</div>
<div class="labelBlock">
<b>Favourite Exhibit:</b>
<div class="indent">
<input type="radio" name="fave" id="exhibit1" value="Exhibit1">
<label for="exhibit1">Exhibit 1</label><br>
<input type="radio" name="fave" id="exhibit2" value="Exhibit2">
<label for="exhibit2">Exhibit 2</label><br>
<input type="radio" name="fave" id="exhibit3" value="Exhibit3">
<label for="exhibit3">Exhibit 3</label>
</div>
</div>
<div>
<label for="comment"><b>Comments:</b></label><br>
<textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
</div>
<div id="center-button">
<input name="submit" type="submit" id="submit" value="Submit" class="center-text">
</div>
</form>
My validation script looks like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
var name = $('#name').val();
var dob = $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[name='fave']:radio:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'process-post.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data1){
if (data1 == 'success') {
window.location.href = 'index.html';
}
else {
alert('Oops! It looks like something has gone wrong. Please try again.');
}
}
});
}}); // end ready
I really am struggling with this so would appreciate any help.
My PHP Looks like this
<?php # PROCESS JOURNAL ENTRY.
# Check form submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# Open database connection.
require ( '../connect_db.php' ) ;
# Execute inserting into 'forum' database table.
$q = "INSERT INTO journal(name,dob,visit,fave,comment,date)
VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
$r = mysqli_query ( $dbc, $q ) ;
# Report error on failure.
if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }
# Close database connection.
mysqli_close( $dbc ) ;
}
?>
Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.
You will need jQuery ajax. This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.
EDIT:
Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
}); // end ready
</script>
Here is the part that I add:
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
This will submit a form normally, meaning that it will run the PHP script and then refresh the page.
If you decide you want to use ajax, you can just replace $(form).submit(); with this:
var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'http://myaddress.com/process.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data){
if (data == 'success') {
//do something
}
else {
//do something
}
}
});
The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.
Hello guys I have a little problem. My problem is I want to use jquery form validation plugin together with codeigniter. As of now I can validate my form using jquery validation rules. Like checking the required fields, checking length of input, checking valid email, etc... But for checking the availability of the data in my database I always got an error. I used the remote function but I can't validate my form. Here's my code I hope you can help me.
addNewItem.php
<script type="text/javascript">
(function($,W,D){
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
$("#login-form").validate({
rules: {
name: {
required: true,
remote: {
type: 'post',
url: <?php echo site_url('category_model/checkName'); ?>,
data: {
'name': $('#name').val()
},
datatype: 'json'
}
},
description: {
required: true
}
},
messages: {
username: {
remote: "Category name already taken!"
}
description: "Please provide a description for category!"
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
<div>
<?php $attr = array('class'=>'form-signin','id'=>'login-form','novalidate'=>'novalidate'); ?>
<?php echo form_open('category_controller/insertItem',$attr); ?>
<h2 class="form-signin-heading"></h2>
<h5 style="font-weight: normal;">Category Name:</h5>
<input type="text" class="input-block-level" placeholder="Category Name" name="name" autofocus="autofocus" value="" required="requried" id="name" />
<h5 style="font-weight: normal;">Desciption</h5>
<input type="text" class="input-block-level" placeholder="Description" name="description" value="" required="required" id="description" />
<br />
<div align="right">
<input type="submit" value="OK" class="btn btn-large btn-primary" />
<input type="button" value="CANCEL" class="btn btn-large btn-primary" name='cancel' />
</div>
<?php echo form_close(); ?>
my model (category_model/checkName)
public function checkName(){
$catname = ucwords($this->input->post('name'));
$validate = "SELECT COUNT(*) AS valid FROM sales_category WHERE salescatname = '{$catname}'";
$testvalidate = $this->db->query($validate);
foreach($testvalidate->result_array() as $row){
$is_valid = $row['valid'];
}
if($is_valid > 0){
return TRUE;
}else{
return FALSE;
}
}
Try changing the following
public function checkName()
{
$catname = ucwords($this->input->post('name'));
$validate = "SELECT COUNT(*) AS valid FROM sales_category
WHERE salescatname = '{$catname}'";
$testvalidate = $this->db->query($validate);
foreach($testvalidate->result_array() as $row){
$is_valid = $row['valid'];
}
echo $is_valid;
}
I am trying to use the username taken or not using jquery validate plugin. but dosent seems to work. I would like to know where I went wrong, all other validation works fine. except for this.
jquery validate plugin page: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
javascript
<script type="text/javascript">
$(document).ready(function(){
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 2,
remote: "users.php"
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
},
email: "A valid email will help us get in touch with you.",
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('adduser.php', $("#register").serialize(), function(data) {
$("#register").fadeOut('fast', function(){
$('#results').html(data);
});
});
}
});
});
</script>
users.php
<?php
$request = $_REQUEST['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
register.php
<form name="register" id="register" method="post" action="">
<section>
<label for="username">Username:</label>
<div>
<input type="text" tabindex="1" class="input" id="username" name="username" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="email">email</label>
<div>
<input type="text" tabindex="2" class="input" id="email" name="email" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="password">Password</label>
<div>
<input type="password" tabindex="3" class="input" id="password" name="password" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="confirm_password">Confirm Password</label>
<div>
<input type="password" tabindex="4" class="input" id="confirm_password" name="confirm_password" value=""/>
</div>
</section>
<!--#-->
<br/>
<input type="submit" tabindex="5" id="submit" value="REGISTER" />
</form>
<div id="results"> </div>
thanks in advance.
I have the same but I use their validation and this to check if username exists. It works great.
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'username must have atleast 3 characters';
var checking_html = 'searching...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("checkuser.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html('<span class="is_available"><b>' +username + '</b> is available</span>');
//this is the id of my save button it'll display if available
$('#newacct').css("display", "inline");
}else{
//show that the username is NOT available
$('#username_availability_result').html('<span class="is_not_available"><b>' +username + '</b> is not available</span>');
}
});
}
</script>
First, you have an extra } that is closing your messages option prematurely, leading to the remaining messages being ignored. You should move this } after the confirm_password message block. Second, you should be calling jQuery.validator.format rather than jQuery.format. I believe this is why this particular validation rule doesn't work. Correct these and see if it works for you.
To answer the OP, you might want to use $_GET. Also, mysql_num_rows has been deprecated as of PHP 5.5.0, so you'll probably want to update that. You could just check if the query returns false.
<?php
$request = $_GET['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
?>
Try this......
JS
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 6,
remote: {
url: "Your PHP",
type: "post",
data: {
funct: 'user_check',
username: function() {
return $( "#username" ).val();
}
}
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
}
});
});
PHP
<?php
function user_check(){
$username = $_POST['username'];
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
}
?>
May help..