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

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.

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.

Pass multiple objects from servlet to Javascript file using ajax call

In my login servlet page have some conditions.The user is registered user pass URL to JavaScript using ajax call. If the user is not registered then try to login i need to display error message and redirect to same page URL but here i am unable to pass both URL and message at a time to JavaScript file using ajax call i am able to pass only one object either URL or message anyone please tell me how to pass both objects to JavaScript.
You can concatenate the Strings of URL and MSG and pass in out.println with a delimiter and then split the same at other end in JS.
if
{
data ="Login.jsp$Sorry, you are not a registered user! Please sign up
first";
}
PrintWriter out = response.getWriter();
out.print(data);
This happens Because print(arg) of Class PrintWriter that you referred by out only accepts one single argument. be it of any type. view API here. Assuming that you always get a success callback.
try should work:
code:
String resp= ""; // final response
if(User.isValid())
{
resp="MyList.jsp" ;
}
else
{
Url="Login.jsp";
Msg="Sorry, you are not a registered user! Please sign up first";
resp= Url + "#" + Msg;
}
PrintWriter out = response.getWriter();
out.print(resp); // based upon your condition above.
change your JS:
<script type="text/javascript">
$(document).ready(function() {
$('#btnLogin').click(function ()
{
$.ajax({
type: "post",
url: "Login", //this is my servlet
data: "uname=" +$('#inputUserID').val()+"&pwd="+$('#inputPassword').val(),
success: function(data){
alert(data);
var response = data.split("#");
if(response.length>1){
// if user is a valid user
$(window.location).attr('href', response[0]);
} else {
// if user in invalid
$(window.location).attr('href', response[0]);
$("#message").html(response[1]);
}
}
});
});
});
</script>

jQuery Ajax POST and return data

I have a form with AJAX submit.
This form is working, but I have the impression that the functions are not correct.
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
I think that has a lot of wrong code, for example:
if(dados == "email=") // >>> This field, how to check if the field is blank?
and >>
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
I tried to update but not return any results
Test Code
//if (email.val() == "")
//{
//email.focus();
alert(email.val()); // op1
alert(dados); // op2
alert($.trim($('email').val())); // op3
emailInfo.html("<font color='red'>Required.</font>");
return false;
//}
if insert an email, the only option that returns is op2 email=teste#teste.com
I think your code is trying to validate email by ajax before submitting form. If so this code seems ok to me out of a few points.
return false at the end of submit call may not work on firefox. Use e.preventDefault();. Look at this post. If you try this code on chrome it may fail beacuse you have no return true anywhere.
Your second code block is ok. email.val(data); is equal to $("#email").val(data);. I think you are trying to set the email input value to the result.
if(dados == "email=") can be changed to if (email.val() != ''). So you wont need to dados also.
You don't use myForm variable nowhere. It should be deleted.
If validating the email on server side is not a must think about validating on client side.
The returned data value is echoed from your PHP file. There are two approaches to take to validate your data:
Do it in the frontend with JS prior to sending your form.
Do it with your PHP code in the separate file.
email.val(data); // This field, how to display the data
sent in the email field? not the return of PHP
I am guessing that you want to ensure that the value doesn't get deleted if the user sends an invalid request (thus having to type the value in again).
What you can do is store the values of what the user has entered on form submit but prior to sending the AJAX request: var emailVal = email.val();
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
var emailVal = email.val(); // Assign the entered input to an emailVal variable
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(emailVal); // Store the entered value back into the email input
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
Another Note
I would also like to point out this: if(data == "invalid")
I have found that PHP can send back error messages within the data along with whatever you ask it to return. If you have any error in your PHP code, this will never hit because invalid will never be the only string of characters in the returned data value. To protect yourself, I would do either two things:
Return an HTTP error and do error handling within the error callback of the AJAX function: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Return a unique word and search for that word within the returned data string:
PHP
if(!validEmailCheck($email)){
echo('invalidRAWR');
}
JS
if(data.indexOf('invalidRAWR') != -1) // Built in PHP errors will never return 'invalidRAWR'

How to make javascript work as a response to php events?

I am developing a website for practice, and I would like to know how to use JS to notify the user that the username he picked is already in use, all works fine, if my function(check_username) returns false, the user succesfully registers himself into the site, otherwise the register won't happen.
When the user can't register I would like to know how can I notify the user with a js script.
<?php
//database includes
include_once('../config/init.php');
include_once('../database/users.php');
if(!check_username($_POST['username'])) {
insertUser($_POST['name'], $_POST['username'], $_POST['email'], $_POST['pass']);
}
else header('Location: ../index.php');
?>
One way would be to change your redirect on failure to a javascript message
else
{
echo "<script>alert('Username already exists');</script>";
}
That's a very trivial example to get you started since you mentioned you're learning JS. You can build a lot of improvements on that.
You can set the returns into a javascript variable and use it to display message if the user is not registered.
var x = <?php echo check_username($_POST['username']); ?>;
if(x) {
alert("You are not registered");
}
You can use php ajax for a live notification to users.
<script>
$(document).ready(function() {
$("#InputFieldID").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
//Getting value of input field.
var username = $(this).val();
//Check only if the username characters are above 4
if(username.length >= 4){
$("#IndicatorDivID").html('<p style="color:#ffbf25;">Checking..!</p>');
$.ajax({
type: 'POST',
url: 'check_username.php',
data: {"username": username},
dataType: 'json',
success: function (data) {
if(data.response=='true')
alert("Already Exist");
}
});
}
});
});
//Username Checker
</script>
The result fo check_username.php must be in json format.
eg: {"response":"false"}

jQuery form validation problem

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;
}

Categories