jQuery form validation problem - javascript

I'm using the following code (via 'Dark Side of the Carton') to validate a reCAPTCHA field, before submitting the rest of a form that includes the captcha field.
The validation works fine, the 'recaptchavalidate' page is called, returns True or False correctly and the JavaScript picks this all up (I test this via alert(html);).
However, when True, the form doesn't continue to be sumbitted as you would expect. In fact, even worse, the reCAPTCHA refreshes as if the response was wrong.
I think it's my JavaScript at fault rather than the reCAPTCHA ... but where am I going wrong?
<script type="text/javascript">
$(function(){
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
// alert(challengeField);
// alert(responseField);
//return false;
var html = $.ajax({
type: "POST",
url: "recaptchavalidate",
data: "recaptcha_challenge_field="+challengeField+ "&recaptcha_response_field="+responseField,
async: false
}).responseText;
if(html == "True")
{
$("#captchaStatus").html(" ");
alert(html);//test
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
alert(html);//test
Recaptcha.reload();
return false;
}
}
$("#signup").submit(function(){
return validateCaptcha();
});
});
</script>
EDIT: This is used only to check there are no errors before submitting. The reCAPTCHA is checked properly after submitting (via Python, not JS). So is not as big a security hole as some users have pointed out.

It seems that your test of html == "True" isn't passing. Are you sure that that is the exact string you're getting back is "True" with no extra characters/whitespace? If there is whitespace on the beginning or the end of the string, for example, the pass will fail but it will still look like "True" if you show the text via an alert box.
Try trimming whitespace from the end of the string by using this check instead:
if (html.replace(/^\s+|\s+$/, '') == "True")

Instead of alerting "html", hard-code "true" and "false" so you're sure it's getting to the correct spot.
if(html == "True")
{
$("#captchaStatus").html(" ");
alert("true");//test
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
alert("false");//test
Recaptcha.reload();
return false;
}
Then report back with your findings.

I can't wait to encounter this in real world. :)
Then I will hack your javascript and just replace validateCaptcha() with
function validateCaptcha() {
return true;
}

Related

Know the exact path of error

I am working on a site built with Code Igniter. It is showing a script error in the console but not the path.
I am having more than 100 files which consists of small or big scripts. Now how I am able to know from which file the error is coming from?
Anyone aware from any tool or any easy method I can try with my site?
Here is my site for reference.
There is error in your ajax , function name as login , In your success response there is missing closing bracket.
Replace code as following :
function login(){
//alert("hhh");
var name = $('#name').val();
// alert(name);
var password = $('#logpassword').val();
//alert(password);
if(name.trim() == '' ){
$('#errorname').html('<span style="color:red;">Please Enter Your Name.</p>');
$('#inputName').focus();
return false;
}else if(password.trim() == '' ){
$('#errorpassword').html('<span style="color:red;">Please Enter Your Password.</p>');
$('#password').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'http://www.edushikshaguide.com/frontend/system_login',
data:{name:name,password:password},
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(data){
console.log('success');
}
});
}
}
}
In any decent browser you just need to click:
Error here is in line 346, column 9, highlighted for your convenience:
In any case, browser-based JavaScript is a client-side language. Neither PHP nor CodeIgniter have anything to do with it unless you use either to generate JavaScript code dynamically.

Troubles Submitting Form programmatically

I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.

jQuery AJAX Page Redirection Error

$.ajax({
url: "NewUserRegistrationServlet",
type: "post",
cache: false,
data : "username="+username+"&password="+encodeURIComponent(pswd)+"&email="+encodeURIComponent(email),
dataType:"xml",
timeout: 3000,
success: function(data) {
var xml_node = $('ResultSet',data);
var status = xml_node.find('result').text() ;
var result = xml_node.find('status').text() ;
if( (result > 0) && ( status == 'SUCCESS') ) {
alert("This Statement is getting executed");
//window.location.replace("login.jsp"); // Not Working
//window.location.href = 'http://localhost:8080/MyProj/login.jsp'; // Not Working
window.open = ('login.jsp','_top'); // Not Working
}else{
$("#RegisErr").siblings("p").remove();
$("#RegisErr").after("<p>User Registration failed! Please Try Again.</p>");
}
},
error: function(xhr, status, text) {
$("#RegisErr").siblings("p").remove();
$("#RegisErr").after("<p>User Registration failed! Please Try Again.</p>");
}
});
What i am doing wrong
OnSubmit -> Validation of form // Working Fine
If Valid -> Do Ajax Request // Working Fine
On Success of Ajax -> Redirect to other JSP Page // Not Woking
EDIT
Screenshot Chrome Debugger
Solved
windows.location = "login.jsp"
Thanks Everyone for your help.
To make your method work i.e. one of :-
1. window.location.replace("http://stackoverflow.com");
2. window.location.href = "http://stackoverflow.com";
The browser is still submitting the form after your code runs.
Add return false; to the handler to prevent that.
Otherwise, use just window.location = "http://stackoverflow.com";
Refer to this post ( window.location.href not working ) for further clarification. If you still face a problem, tag me again. I will write a detailed answer for you.
This comment is the code for your solution to work - https://stackoverflow.com/a/6094213/1366216
Please trim all white spaces from result. you should write following line before if block.
if(Number(result)>0 && status.trim()==="success")
{
//do anything you want
}

Reading a input email address from html and using in JSP scriplet

Hi I have an html field that takes an email. I would like to take the entered value and ensure it exists in the database before proceeding.
<script>
function updateUserData()
{
document.getElementById(picker_email).value;
alert( "INVALID EMAIL ");
}
</script>
Is there anyway I can pass the picker_email to the JSP...so the outcome would be :
...
value = document.getElementById(picker_email).value;
<%
DatabaseHelper db_h = new DatabaseHelper();
boolean email_exists = db_h.verifyEmail( value );
%>
if( <%email_exists%> )
proceedToServlet();
else
alert( "INVALID EMAIL ");
Any help would be greatly appreciated.
#user2747139 developerwjk is correct. Why don't you try some ajax call to server. Writing scriptlet in jsp (Especially for server oriented purpose) is not a good practice. Here is some snippet. All you need to do is include jquery plugin in your jsp page. You can try like this,
function updateUserData(){
var value = $("#picker_email").val();
$.ajax({
url: "ur_servlet_url&value="+value,
type: "POST",
success: function(data){
//If you want to return anything in jsp.
alert("Invalid Email");
}
});
}
You do your validation in server side. If the validation succeeds/not succeeds return some text like success or failure. Based on this you will get response data in ajax. You can do alert if(data == 'failure') then alert('Invalid Email');. Let me know if this helps.

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories