grails remoteField javascript - javascript

I'm having trouble returning a value to the view which then decides if the Submit button should be selectable or not. I'm checking the value of accNbr against an api call that returns JSON. I simple want to not if the user is found or not.
A snippet from within my form on my view - here is the account number input:
<g:remoteField paramName="accNbr" action="validateCustomer" update="[failure: 'error']" bean="${accNbrInstance}" required="" size='40' name="accNbr" value="${accNbr}" data-trigger="change" data-required="true" data-regexp="[0-9]{12}" data-regexp-message="This field requires a valid Account Number of 12 digits"/>
then I have JS (which I think has the errors:
function accountNoError(){
if($('#accountValid').html().value = "Not found"){
$('#submit').attr("disabled", true);
$('#clear_btn').show();
}else{
$('#submit').attr("disabled", true);
}
}
and my controller function:
def validateCustomer() {
def accountNo = params.accNbr
//def accountNo = "621137093178"
def accountValid
if(accountNo.length() == 12){
def http = new HTTPBuilder('https://my.API.call/' + accountNo)
http.auth.basic ('username','password')
http.request(GET, ContentType.JSON) { req ->
response.success = { resp, json ->
assert resp.statusLine.statusCode == 200
accountValid = json
print("JSON is: " + json)
println("Valid Account")
}
}
}else {
accountValid = "Not found"
println("Invalid Account")
}
return accountValid
}

In your jQuery you have an if...else statement.
In your if you disable your submit button:
$('#submit').attr("disabled", true);
and in your else you disable your submit button:
$('#submit').attr("disabled", true);

Related

Challenge with javascript/jquery $.get and python backend

I have an HTML form to enter a username/password to register for a site. I am attempting to implement a javascript/JQuery $.get to send an HTTP GET to check if the username is already in use. On the server side, the "username" value (pulled by request.form.get()) is coming back as None. The javascript source does not seem responsive either on the HTML page.
Javascript as below:
var username = document.getElementById("username");
var inputForm = document.getElementById("form");
document.getElementById("submit").addEventListener("click", function(event) {
event.preventDefault()
});
inputForm.onclick = function(data) {
$.get("/check?username=" + username.value, function() {
alert("CHECKING")
if (data == false) {
inputForm.submit();
}
else {
alert("Sorry - that username is taken!");
}
});
};
Python (Flask) on backend as follows:
#app.route("/check", methods=["GET"])
def check():
"""Return true if username available, else false, in JSON format"""
print("***RUNNING CHECK***")
# get username from web form
username = request.form.get("username")
print(username)
# check that username is longer than 1, then pull list from DB to check against
if len(username) > 1:
usernames = db.execute("SELECT username FROM users")
# return false if username is available
if username in usernames:
return jsonify(False)
# return true if username is NOT available
else:
return jsonify(True)
This is what comes back:
TypeError: object of type 'NoneType' has no len()
INFO:werkzeug:192.168.179.21 - - [22/Aug/2019 16:20:41] "GET /check?username=ajd HTTP/1.0" 500 -
The client side issue that I can see are...
Checking the Javascript console will probably tell you that data is undefined. If should be added as a parameter to the callback function.
You need to escape the get paramters with encodeURIComponenet.
You probably want to run this code when the input is received than when the form is clicked on.
username.oninput = function(data) {
$.get("/check?username=" + encodeURIComponenet(username.value), function(data) {
alert("CHECKING")
if (data == false) {
inputForm.submit();
} else {
alert("Sorry - that username is taken!");
}
});
};

Mousedown still submitting form, when it should not

hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});

How to perform validation for Onclick Javascript Custom button

I have the code below and I would like it to perform multiple field validation and give alert on each field when it is incomplete. Scenario: If I use the code without the validation and associated alerts it works 100%, when I include the validation the code goes through each step and alert and ultimately fails on the last bit to execute and flag a field as 'true' and gives error of 'Invalid or unexpected token'. Any help would be welcome
{
!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")
}
var x;
if ('{!Case.Trigger_Submit_Spark__c}' == true || '{!Case.Spark_Service_Desk_Ref__c}' != "") {
alert('You are unable to submit request, as this request has already been submitted to Spark')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as Spark Service Request Type and Request note are blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' != "") {
alert('You are unable to submit request, as Spark Service Request Type is blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' != "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as the Spark Request Note is blank')
} else {
if ('{!Case.Trigger_Submit_Spark__c}' == false && confirm('Do you want to submit this request?\n\nBy submitting this request the following will occur:\n 1. Case Status changed to Escalated to Tier2\n 2. Escalation Group = Spark\n 3. Email sent to Spark (Remedy)\n 4. Note placed in SalesForce chatter feed\n\nPlease check chatter feed to confirm that request has been sent') == true) {
x = "OK";
var c = new sforce.SObject("Case");
c.id = '{!Case.Id}'
c.Trigger_Submit_Spark__c = true;
result = sforce.connection.update([c]);
if (result[0].success === "true") {
window.location.reload();
} else {
alert("An Error has occured. Error: " + result[0].errors.message);
}
}
}
}
}
}

return false not working in jQuery ajax

I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.

JSP Chat - How I can parse the value from HTML to JSP page?

I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");

Categories