I am trying to implement an online service called CleanTalk which requires me to deploy scripts on my boss' website pages. CleanTalk prevents spambots from filling out website forms and email signup fields. I followed their instructions carefully but have been unsuccessful in getting it to work.
If I put the script before any HTML code, all the following html on the rest of the page doesn't get displayed. When I put the code at the end of the page, then I can see all the HTML, fill out the form and submit it, but nothing goes through. There are also no spambot blockings recorded in my CleanTalk account, even when I use their spam email tester in the form fields.
Here is the php code provided by CleanTalk:
<!--CLEANTALK SCRIPT-->
<?php
session_start();
require_once (dirname(__FILE__) . '../javajq/cleantalk.class.php');
// Take params from config
$config_url = 'http://moderate.cleantalk.org/api2.0/';
$auth_key = 'nere2usu5ehe'; // Set Cleantalk auth key
if (count($_POST)) {
$sender_nickname = 'John Dow';
if (isset($_POST['login']) && $_POST['login'] != '')
$sender_nickname = $_POST['login'];
$sender_email = 'stop_email#example.com';
if (isset($_POST['email']) && $_POST['email'] != '')
$sender_email = $_POST['email'];
$sender_ip = null;
if (isset($_SERVER['REMOTE_ADDR']))
$sender_ip = $_SERVER['REMOTE_ADDR'];
$js_on = 0;
if (isset($_POST['js_on']) && $_POST['js_on'] == date("Y"))
$js_on = 1;
$message = null;
if (isset($_POST['message']) && $_POST['message'] != '')
$message = $_POST['message'];
// The facility in which to store the query parameters
$ct_request = new CleantalkRequest();
$ct_request->auth_key = $auth_key;
$ct_request->agent = 'php-api';
$ct_request->sender_email = $sender_email;
$ct_request->sender_ip = $sender_ip;
$ct_request->sender_nickname = $sender_nickname;
$ct_request->js_on = $js_on;
$ct_request->message = $message;
$ct_request->submit_time = time() - (int) $_SESSION['ct_submit_time'];
//Additional parameters. You could the description at the bottom of the page.
$ct = new Cleantalk();
$ct->server_url = $config_url;
// Check
$ct_result = $ct->isAllowMessage($ct_request);
if ($ct_result->allow == 1) {
echo 'Message allowed. Reason ' . $ct_result->comment;
} else {
echo 'Message forbidden. Reason ' . $ct_result->comment;
}
echo '<br /><br />';
}
else
{
$_SESSION['ct_submit_time'] = time();
}
?>
<!--CLEANTALK SCRIPT-->
And here is my html form code with the CleanTalk code I am required to add to it:
<!--CONTACT FORM-->
<form action="form.php" method="post" name="contact form" style="padding-bottom: 55px;">
<br>
<input class="formstyle round bgcolor purpleb" style="width: 631px;" type="text" name='name' placeholder="Full Name" required><br>
<!-- ADDED value="" TO THE EMAIL SECTION.-->
<input class="formstyle round bgcolor purpleb" type="email" name='email' required placeholder="Email" value="" style="float: left; width: 295px; margin-right: 15px;">
<input class="formstyle round bgcolor purpleb" type="tel" name='tel' required placeholder="Phone" style="float: left; width: 295px;"> <br>
<textarea class="formstyle round bgcolor purpleb messagebox" type="text" name='message' required style="height: 160px;" placeholder="Message"></textarea><br>
<input type="checkbox" id="spambot" name="spambot" value="Yes" required> <label for='spambot'><span class="parastyle grey">Yes, I'm human</span></label>
<br /><br />
<!--For Cleantalk-->
<input type="hidden" name="js_on" id="js_on" value="0" />
<input type="submit" class="purpleb round formstyle bgcolor sendform" value="SEND" name='submit' style="float:left">
<label for='submit'><a class="reco grey" href="/privacy" target="_blank"><span style="text-decoration: none; display: inline-block;"> </span>PRIVACY POLICY</a></label>
<!--For Cleantalk-->
<script type="text/javascript">
var date = new Date();
document.getElementById("js_on").value = date.getFullYear();
</script>
</form>
<!--CONTACT FORM-->
Here is a link to the CleanTalk API installation instructions. If you need anything else just let me know.
Here are the error message I'm getting:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php:19) in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 72
Warning: require_once(/hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact../javajq/cleantalk.class.php): failed to open stream: No such file or directory in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 73
Fatal error: require_once(): Failed opening required '/hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact../javajq/cleantalk.class.php' (include_path='.:/usr/local/lib/php-5.5.22-amd64/lib/php') in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 73
Related
In a .jsp page I have a form (POST method):
<div class="form-group">
<div class="col-md-3">
<input type="text" list="materials" class="form-control" name="material"/>
<datalist id="materials"></datalist>
</div>
<div class="col-md-3 col-sm-3">
<input type="number" class="form-control" name="quantity" >
</div>
</div>
I delete the html5 element required from the input to see what happens if the user submit the form without filling these inputs. In my servlet, I get this:
String material = request.getParameter("material");
String quantity = request.getParameter("quantity");
System.out.println("material="+ material + "-quantity=" + quantity);
and I get:
material=-quantity=null
The fact that I receive an empty string and a null result is it because of the diferrent type in the input?
<html>
<head>
<title>HTML Checkbox</title>
</head>
<body>
enter code here
<h2> Pick your most favorite fruits: </h2>
<form name="fruitcheckbox" action="fruits.php" method="POST">
<input type="checkbox" name="fruit[]" value="orange"> Orange
<input type="checkbox" name="fruit[]" value="apple"> Apple
<input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
<input type="checkbox" name="fruit[]" value="banana"> Banana
<input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
<br>
<input type="submit" value="Save" name="btnsave">
</form>
Anyone can give me an idea how to validate this checkobox array.
if(isset($_POST['btnsave']))
{ $fruit = $_POST['fruit'];
$values = array();
foreach($chkbox as $selection )
{ if(in_array($selection, $fruit))
{ $values[ $selection ] = 1; }
else
{ $values[ $selection ] = 0; }
}
this is part of my code. I want to limit the checked checkbox to 5. Thanks. I need it badly :|
Try this. You can limit in javascript itself. So you can limit user in client side no need to go server side. It will limit you for 4 items. You can change the number in the script to increase the value
<script type="text/javascript">
function validateitem(){
var items = document.forms['fruitcheckbox'];
var inc = 0;
var i;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
inc++;
}
}
if(inc == 0) {
document.getElementById("limitmsg").innerHTML = 'Select atleast 1 item.';
return false;
} else if(inc>4){
document.getElementById("limitmsg").innerHTML = 'You can select only 4 items.';
return false;
}
}
</script>
<h2>Pick your most favorite fruits:</h2>
<form name="fruitcheckbox" action="fruits.php" method="POST"
onsubmit="return validateitem();">
<input type="checkbox" name="fruit[]" value="orange"> Orange <input
type="checkbox" name="fruit[]" value="apple"> Apple <input
type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit <input
type="checkbox" name="fruit[]" value="banana"> Banana <input
type="checkbox" name="fruit[]" value="watermelon"> Watermelon <br> <span
style="color: red" id="limitmsg"></span><input type="submit"
value="Save" name="btnsave">
</form>
Do you need something like this?
if (isset($_POST['btnsave'])) {
$fruits = $_POST['fruit'];
$count = count($fruits);
if ($count > 5) {
// Error; Only 5 checks allowed
} else {
// Save the data
}
}
When you submit fields with brackets like in your example. name="fruit[]" it will be an array when it is received in the backend in php.
You could then just use this:
if(isset($_POST['fruit']) && count($_POST['fruit']) > 5) {
// add your error message
} else {
// Everything is fine as long as you dont have to select atleast one of them
}
If my understanding is not wrong you have more then 5 checkboxes and you want user to restrict to check only 5 checkboxes.
If this is the case then below code might help you.
$("input[name='fruit[]']").change(function(e) {
if($('input[name="fruit[]"]:checked').length==5) {
$("input[name='fruit[]']:not(:checked)").attr("disabled", true);
} else {
$("input[name='fruit[]']:not(:checked)").attr("disabled", false);
}
});
Above code will allow you to check only 5 check boxes, whenever user check the 5th checkbox it will disable the remaining unchecked checkboxes. whenever user uncheck any of the 5 checkboxes then it will enable all the checkboxes.
I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>
I am trying to submit a form with text fields, text area, file field etc in a JSP form. I am using commons file upload for this form.
Here is my JSP form:
<form name="add_product_form" id="add_product_form" enctype="multipart/form-data" method="post" action="Product.Add">
<div id="form-body">
<div id="lebel">
<font color="red">*</font>Product Name:
</div>
<div id="field">
<input type="text" name="product_name" id="product_name" value="">
</div>
<div id="lebel">
<font color="red">*</font>SKU No:
</div>
<div id="field">
<input type="text" name="sku_no" id="sku_no" value="">
</div>
<div id="lebel">
<font color="red"> </font>In Date:
</div>
<div id="field">
<input type="text" name="in_date" id="in_date" value="">
</div>
<div id="lebel">
<font color="red"> </font>Upload Image:
</div>
<div id="field">
<input type="file" name="upload_image" id="upload_image" value="">
</div>
<div id="lebel">
<font color="red"> </font>Description:
</div>
<div id="field">
<textarea name="description" id="description"></textarea>
</div>
<div id="lebel">
</div>
<div id="button_field">
<input type="submit" name="add_product_button" id="add_product_button" value="Add Product">
</div>
</div>
</form>
I am getting the value of the text fields using following methods.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String value = fi.getString();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 )
{
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}
else
{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
}
else
{
String name = fi.getFieldName();
String value = fi.getString();
if( name.equals("product_name") )
{
productName = value;
}
else if( name.equals("sku_no") )
{
skuNo = value;
}
else if( name.equals("in_date") )
{
newDateString = value;
}
else if( name.equals("description") )
{
productDesc = value;
}
}
}
But I am not getting the value of "TextArea" I have used in my form with name "descripton".
Can anyone help me in getting the value of this text area when submitting the form.
Thanks
there is some problem with it. you can give style to textbox and look it like textarea which will help you out
Could not find the direct solution.
To implement this I used a hidden field and jquery.
On clicking the submit button, I smet the value of teh text area in the hidden field, then submit the form.
Here is the jquery code:
$('#add_product_button').click(function()
{
var description = $("#description").val();
$("#hidden_description").val(description);
$("add_product_form").submit();
});
I have encountered the same problem,and I have solved it!
Just put your 'textarea' tag before the 'input type="file" ....' tag,
and the Servlet can get the textarea value
I am not a English speaker and hope you can understand my solution :-)
I have done the following coding
ContactUs.jsp
<form action="contact1.jsp" method="post" id="contact_form">
<div class="name">
<label for="name"></label> <input type="text" placeholder="My name is" name="name" id="name_input" required>
</div>
<div class="email">
<label for="email"></label> <input type="email"
placeholder="My e-mail is" name="email" id="email_input" required>
</div>
<div class="telephone">
<label for="name"></label>
<input type="text" placeholder="My number is" id="telephone_input" name="telephone" title="lenght of number should be 10 digits for valid number" pattern="[1-9]{1}[0-9]{9}" required/>
</div>
<div class="message">
<label for="message"></label>
<textarea name="message" placeholder="I'd like to chat about"
id="message_input" cols="30" rows="5" required></textarea>
</div>
<div class="submit">
<input type="submit" value="Send Message" id="form_button" />
</div>
</form>
the the code for contact1.jsp is
String name=request.getParameter("name");
String email=request.getParameter("email");
String telephone=request.getParameter("telephone");
String message=request.getParameter("message");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/cinushi_university", "CinthiyaSingh", "Cinthiya#098");
Statement st=con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into contact values('"+ name + "','"+ email + "','"+ telephone + "','"+ message + "');");
if (i > 0) {
request.getSession().setAttribute("Message", "Sent Successfully!");
request.getRequestDispatcher("ContactUs.jsp").forward(request, response);
}
else{
request.getSession().setAttribute("Message", "Incomplete Process!");
request.getRequestDispatcher("ContactUs.jsp").forward(request, response);
}
//close connection
%>
Once I add the data to the form and submit it, this works fine, however post that on the same page when I click refresh it resubmits the data, I want the data from previous submission to clear when I redirect the response even to same ContactUs.jsp , if it is possible please help.
you can use java script History.replaceState() function to fix this issue.
The History.replaceState() method modifies the current history entry, replacing it with the stateObj, title, and URL passed in the method parameters.
Add this script in jsp page-
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Or,
Only insert data in table 'user' if submit data in not there. you have to check with unique column.