compare input value with value in database coldfusion - javascript

I have 5 textboxes(cfinput) on my form to enter organisation code. What I want to do is, As the user types the Org code, there should be an onkeyup function that will validate the value with all the values in database and if its invalid it should show "Invalid Code."
I have got all the Org codes in an array called OrgIndexArray. I am not getting, how would I do this for all the 5 textboxes (some sort of cfloop?)
<cfquery name="getOrgCodes" datasource="#sqlDS#">
select distinct OrgCode From #SAUserIndex#
</cfquery>
<cfset IndexCodesList = ValueList(getOrgCodes.OrgCode)>
<cfset IndexCodesArray = #ListToArray(IndexCodesList)#>
<script>
var IndexArray=<cfoutput>#SerializeJSON(getOrgCodes,true)# </cfoutput>
$(document).ready(fucntion() {
$('.IndexCodes').on('keyup',function(){
if(!!~jQuery.inArray($this.val(),IndexArray)) {
document.getElementById("message").innerHTML="Invalid Index";
}
});
});
</script>

The issue at the moment is that all your "validation" data is only available serverside. Ideally you want to use javascript for the validation on the form fields as the user types. This way you can do the validation client side without having to make additional calls to the server.
There are few ways to achieve what you want to do:
One (possibly a bit hacky) way to do this is to use Coldfusion to populate a javascript array in your page:
<script>
var myArray = <cfoutput>#serializeJson(OrgIndexArray)#</cfoutput>;
//use javascript to validate the input by checking the cfinput value with the array.
//assuming you have jquery:
$(document).ready(function(){
$('.classOfYourInputHere').on('keyup',function(){
if ($.inArray( $this.val(), arr ))
{
//do something
}
});
});
</script>
Alternatively you can create an API of sorts, that will allow you to do an ajax request to a coldfusion .cfc to retrieve the array data in javascript and then you would proceed similar to the above.
Please note that this is not tested in anyway, but it hopefully should help you in the right direction.

Related

Jquery $.getJSON User Input

I am trying to add an html input box to allow users to set a value which adjusts the result returned from a sql request. My request currently contains a parameters to which a variable is supplied and sent as a request.
I am new to jquery and uncertain as to how to fetch the user inputted value as previously done with the simple getElementById in JavaScript.
My jquery is:
var schema = 'sewer_pipelines';
$.getJSON("sql_query.php", // The server URL
{ parameter: schema },
saveToArray
);
Is there a method which will allow for user input in this approach?
You have to use a selector like this :
var schema = $('#sewer_piplines').val();
More on jquery selectors : https://api.jquery.com/category/selectors/
Thanks for the help, problem is now sorted.
Working code is:
var schema = $('#attribute_parameter').val();
$.getJSON("sql_query.php", // The server URL
{ parameter: schema },
saveToArray
);
var value= $('#inputid').val();

SQL request process with JS

I would like to add in a with JS from a JSP variable that contains the result of a SQL query.
This is my two inputs :
<tr>
<td><label>Code postal* :</label></td>
<td><input type="number" name="cp" placeholder="CP du lieu de résidence" required /></td>
<td><label>Ville* :</label></td>
<td><select name="ville" required disabled/></select></td>
</tr>
And ths is my JS and JSTL query:
<sql:query dataSource="jdbc/Referentiel" var="communeCp" >
SELECT code_postal, nom_commune_min, insee_commune FROM commune
</sql:query>
<script>
$('input[name=cp]').keyup(function(){
if ($(this).val().length == 5)
{
$('select[name=ville]').prop('disabled', false);
var communeListe = "${communeCp}";
for (var i in communeListe)
{
var currentCp = communeListe[i][code_postal];
var currentVille = communeListe[i][nom_commune_min];
if($('input[name=cp]').val() == currentCp)
{
$('select[name=ville]').append('<option value="'+ currentVille +'">'+ currentVille +'</option>');
}
}
}
else
{
$('select[name=ville]').prop('disabled', true);
}
});
</script>
My navigator say "code_postal is not defined".
I am forced to use ajax to do this ? I really don't know ajax. :/
"code_postal is not defined" happens because of this line of javascript:
var currentCp = communeListe[i][code_postal];
Javascript thinks code_postal is the name of a variable, but there's no "var codePostal = ..." anywhere in your javascript.
Here's what's going on with your JSP page:
First, your JSP is rendered. JSP invokes the SQL query and stores the result in the communeCp variable (an object of type javax.servlet.jsp.jstl.sql.Result).
JSP then replaces this line:
var communeListe = "${communeCp}";
with the result of evaluating "communeCp.toString()". I don't know what that is, but it might be something as simple as the default Object.toString implementation, so this is the actual javascript that would be rendered to the page:
var communeListe = "javax.servlet.jsp.jstl.sql.Result#123456".
Now that the JSP has been rendered, the browser executes the javascript. It fails to even evaluate because you have the undefined code_postal reference, but if for some reason that wasn't a problem, it would fail because you are trying to do a for each loop over the communeListe, but javascript sees that communeListe is just a simple string, so it doesn't make sense to do a for loop over that.
Now, with that understood, I'll try to explain how you could achieve the behavior you want without AJAX.
From your code, it looks like you want the following behavior: A user needs to enter a postal code and select a ville in that postal code. After they've entered 5 characters of their postal code, enable the "ville" dropdown and populate it with the possible villa choices for that postal code.
You have the basic idea for one way to achieve this: Do a query in JSP that gets all postal codes and all villes, then, when the postal code is entered, look through this data somehow in javascript and populate the ville dropdown with the villes that are in that postal code.
The problem is in making the data from the SQL query available to the javascript. Here's how you might do that without AJAX. The basic idea is to initialize a javascript array of objects using a literal which is generated by rendering your JSP:
<sql:query dataSource="jdbc/Referentiel" var="communeCp" >
SELECT code_postal, nom_commune_min, insee_commune FROM commune
</sql:query>
<script>
var communeListe= [];
<c:forEach var="row" items="${communeCp.rows}">
communeListe.push({
code_postal: '${row.code_postal}',
nom_commune_min: '${row.nom_commune_min}',
insee_commune: '${row.insee_commune}'
});
</c:forEach>
$('input[name=cp]').keyup(function(){
if ($(this).val().length == 5)
{
$('select[name=ville]').prop('disabled', false);
$.each(communeListe, function(index, currentRow) {
var currentCp = currentRow.code_postal;
var currentVille = currentRow.nom_commune_min;
if($('input[name=cp]').val() == currentCp)
{
$('select[name=ville]').append('<option value="'+ currentVille +'">'+ currentVille +'</option>');
}
});
}
else
{
$('select[name=ville]').prop('disabled', true);
}
});
</script>
Be warned! This has the potential to make the page very slow to load if you have a lot of rows in the commune table, because you are sending the text of every single row to the user's browser.
For you use case, it would almost certainly be a better overall design to use AJAX. The way this would improve load speeds is that it would only query for the villes that it needs and it would only need to send back a small subset of all possible villes to the user's browser. I can provide a bit of guidance on that:
Basically, you will first need to develop a server-side webservice. You can probably just make this using a Java servlet since you are already using JSP. This servlet will need to accept a postal code as a request parameter and will do a query to the commune database on that postal code (so it should only get rows where postal_code == the postal code request parameter value). It will then return JSON containing an array of objects representing those rows from the commune database, so something like this:
//assume this is the request coming to your webservice
/get_villes?postalCode=12345
//This would be the JSON response returned by your webservice
[
{
'nom_commune_min': 'ville name 1',
'insee_commune': 'insee_commune 1'
},
{
'nom_commune_min': 'ville name 2',
'insee_commune': 'insee_commune 3'
},
... and so on depending on how many villes have that postal code
]
To implement this webservice you could make a simple java object called something like Commune and give it nom_commune_min and insee_commune as fields. Then you could use a simple JSON serialization library like Jackson to serialize that object to a string and return that from your servlet as the body of your HTTP response.
On the frontend side, you'll need to change your javascript so that, when the postal code is entered, it uses $.ajax({ ... }) and invokes that webservice, you made passing it the value of the postal code to lookup.
The call to $.ajax might look something like this (I would probably use $.get just because it's a simpler version of $.ajax):
$.get({
url: "/get_villes?postalCode=" + postalCode,
success: function(communeCp){
$.forEach(communeCp,function(index,currentRow){
//put code here to populate the dropdown list using
//currentRow.postal_code, just like the previous code I provided
});
},
});
Another thing to consider is that, since this is asynchronous, when the browser performs this query, the dropdown is going to be blank for a small time while that query runs (but the user will still be free to interact with the page and might be confused by the blank enabled ville dropdown). So, you need to communicate to the user that you are waiting for results from the webservice when that javascript ajax query runs. So, you could do something like show a "Loading..." text somewhere when they enter the 5 digits of their postal code, and then hide that text in the success function of that $.get (after the dropdown is populated).
Other than that, I would suggest you take some time to wrap your mind around how AJAX and webservices work and look at some tutorials and examples. Webservices, ajax, and everything related to building dynamic websites are a vital part of modern web development.

HTML form with intermediate web service service call before submit

I have an HTML form to update the address in the account that submits to a Java servlet.
The problem is that, the form should not accept free flowing address text. Instead the user should enter the zip code/house number/street name, and hit a search button.
This search needs to go to a webservice, perform authentication and get a list of valid addresses that match the search criteria.
This list of addresses should be displayed to the user in the same form (either unhide a hidden element or use a modal dialog), so the user can pick his address.
Only after the valid address is picked, the user should be able to hit the form submit button which sends the data back to the servlet.
I am not sure how to have these 2 buttons do different actions in the form. I am very new to JavaScript and any pointers or examples are much appreciated.
For your webservice build an output of the values based on a search result (a basic string). Put this data in a JSON statement or just a javascript array.
Return something that looks like this.
['SearchResult1', 'SearchResult2', 'SearchREsult3']
On your search box. Bind a function on change or blur.
$('#SearchBox').bind('change', function(){
var val = $(this).val();
//Please reference the Jquery Ajax function as im typing this from memory and i always mix one or two things up :).
$.ajax({
"type" : "post",
"url" : "yoururlhere",
"data" : { "search":val },
success : function(dataset){
//When it comes back here check to see if its valid data etc etc
//After you validate you can populate a picklist on the page with the values. Or do anything you want with the values like this
for(x in dataset){
$('#DocumentElement').append('<p>'+ dataset[x] +'</p>');
}
}
});
});
This should start you out. After that you can just do more things on the callback, or modify the dom in a way which suits you better :).

asp.net - client-side control changes not seen server-side

I have two list boxes. One is populated on Page_Load and the other remains empty.
The user has buttons for adding users from the first list to the second list and back.
When the form is submitted, the second list is empty, like it was when it was sent to the client. Here is the JS code:
function add() {
$('#AvailableUsers option:selected').appendTo('#SelectedUsers');
}
function addall() {
$('#AvailableUsers option').appendTo('#SelectedUsers');
}
function remove() {
$('#SelectedUsers option:selected').appendTo('#AvailableUsers');
}
function removeall() {
$('#SelectedUsers option').appendTo('#AvailableUsers');
}
How do I bring the client-side changes back to the server side?
Edit: Code for server-side:
bool canDismiss = chkCanDismiss.Checked;
string messageText = tbMessageText.Text;
PaymentsDataContext db = new PaymentsDataContext();
foreach (ListItem li in SelectedUsers.Items)
{
UserMessages newMessage = new UserMessages();
newMessage.userName = li.Text;
newMessage.messageText = messageText;
newMessage.dismissed = false;
newMessage.canDismiss = canDismiss;
db.UserMessages.InsertOnSubmit(newMessage);
}
db.SubmitChanges();
You have to append/store those items in the hidden field as well, then you can get the items from the hidden field on the server side.
This is because the changes you made at client side are not available on the server side.
If I read correctly you are trying to use the Users in "Selected Users" Server side. I would have an on form submit client side event that selects all the users in the SelectedUsers list. This eliminates the need for a hidden variable. NOTE use the following in conjunction with your existing jQuery
$(document).ready(function(){
$(form).submit(function(){
$('#SelectedUsers option').attr("selected","selected");
return true;
});
});
EDIT In response to comment: When the selected users control is originally loaded on the page there are no items and nothing selected. With your current code, options are added to the selected users list, on the client side. Currently when the form is submitted these values are not selected and therefore not posted back to the server. To post the values back to the server they need to be selected first. What the above code should do is select the users options in the SelectedUsers list and post the selected values, with the rest of the form, back to the server when the form is submitted.
Edit 2, Server Side Code: You may need to access the values via the Request.Form object. With multiple controls like multiple select boxes, multiple values are passed as a comma separated string.
string rawSelUsers = Request.Form[SelectedUsers.ClientID];
You can the perform a split on this string to break it into an array if needed.

Stuck trying to display information from JavaScript form

Just working on a class project and I can't figure out what to do next.
I've got a form that is being validated with JavaScript. It's the usual information, name, cc# email, etc.
Well the only tuts I can find relate to how to get the form to validate in the first place, which I've already accomplished.
Now all I need to do is figure out how to get the information that I've captured to display in the confirmation page. I don't need any server side validation if that helps.
Here's a link to the page so far (http://sulley.dm.ucf.edu/~ph652925/dig3716c/assignment4/dinner.html)
Any pointers or references?
<?php
print_r($_REQUEST);
?>
will print whatever value the PHP callback is getting from your form.
=H=
You could try to use the GET parameters to forward the info:
link.to.new.page.html?param=value&param2=value2
etc...
It looks like you're using PHP. If you're sure you don't want any validation, of any kind, then the simplest way to output what was on the form (with some degree of control over what it looks like) is by using the POST global variable in PHP:
<?php
$firstname = $_POST['firstName'];
// etc etc for the other fields
?>
You can then output whatever you want by using those variables. The 'name' property for the HTML fields corresponds to what goes inside the square brackets in the PHP code above.
First, I would like to note that if you are using any server side application, you should absolutely validate the input on the server script before doing anything with it. The client side validation is really intended to make it easier for the user to enter the correct information and can be easily hacked or irrelevant if javascript is off... This said, on the client side, you could intercept the submit event, check the different field values. If you have errors, you display error messages, otherwise, you submit the form. example:
if we have this form:
<form action"myActionscript.php" method="GET" id="#myForm">
// form items here
</form>
and then this script (Beware, code not tested)
<script type="text/javascript">
var f = document.getElementById('myForm');
if (f.addEventListener) { // addEventListener doesn't work in ie prior ie9
f.addEventListener('submit', checkForm);
}else{
f.attachEvent('submit', checkForm);
}
function checkForm() {
// Check all input fields logic,
// you could have an errors array and add an error message for each
// error found. Then you would check the length of the error array,
// submit the form is the length is 0 or not submit the form
// and display errors if the length is > 0.
if (errors.length > 0)
{
// iterate through the array, create final error message
// and display it through an alert or by inserting a new
// DOM element with the error message in it.
// [...]
}else{
f.submit();
}
}
</script>
I have to say that the whole thing would be much easier and certainly more cross-platformed if you used a javascript library like jQuery... ;)

Categories