Encode a string to pass as a parameter - javascript

I have this function:
function eLookup(type, long, lat, distance) {
//var sFilter = getCompanyProductFamilies();
distance = distance * 1000;
$.ajax({
url: O.GenURL('xtmp_Maps/Get' + type + '.asp', 'long=' + long + '&lat=' + lat + '&distance=' + distance),
success: eval('plotEntity' + type)
});
}
I have another function called getCompanyProductFamilies which I have commented out the call for in the above function as there is something wrong and this is partly where I'm stuck.
function getCompanyProductFamilies()
{
var cb = document.getElementsByClassName("PRODFAM");
var sAnd = "";
for(var i = 0; i < cb.length; i++)
{
sAnd += "comp_c_productfamily like '%," + cb[i].id.replace("pdfam_", "") + ",%' or ")
}
if(cb.length > 0)
{
sAnd = sAnd.slice(0, -4);
sAnd = " and (" + sAnd + ")";
}
return sAnd;
}
The above function should get all checkboxes with the class name of PRODFAM, and for each one that is checked, it should slowly generate part of a where clause for a SQL statement. I am aware of the implications of SQL injections, but this is not something on the open internet, so ignore that. I tried several ways of getting the checked ones using jQuery but nothing I did worked.
An example of the HTML it is working on is here:
<input type="checkbox" id="pdfam_711121" class="PRODFAM"/>
<label for="pdfam_711121" class="VIEWBOX">Local Wage Rate</label><br />
<input type="checkbox" id="pdfam_711131" class="PRODFAM"/>
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label><br />
<input type="checkbox" id="pdfam_711341" class="PRODFAM"/>
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label><br />
There are about 25 of the above categories, and this is just 3 as an example. The number of categories could change as well. What I need my my function(s) to do is:
Get a list of checkbox IDs that are checked and construct a string that can be passed as a parameter to the ajax call in the top function. When the parameter is received by the target of the ajax call, I can put a function in that page that creates the where clause for the SQL call.
Any help would be most appreciated. The top function called eLookup can't change too much but I can add querystring parameters, which is what I want to do. The other function it doesn't matter about that.

This is the code that works.
function getCompanyProductFamilies()
{
var cb = document.getElementsByClassName("PRODFAM");
var sAnd = "";
var bChecked = false;
for(var i = 0; i < cb.length; i++)
{
if(cb[i].checked == true)
{
sAnd += "comp_c_productfamily like '%," + cb[i].id.replace("pdfam_", "") + ",%' or ";
bChecked = true;
}
}
if(bChecked)
{
sAnd = sAnd.slice(0, -4);
sAnd = " and (" + sAnd + ")";
}
return sAnd;
}
As this returns a plain text string that is passed directly to an ASP page on the querystring, I may encrypt it. If I use encodeURIComponent, that makes it safe to pass onto the querystring, but still it can be altered. It isn't critical because of where the system is running, but I may look into something to safeguard the string.

Related

How to make a break line in JavaScript

In java I send 30 frames (30 Strings) using:
for(Frame frame : frames) {
response.getWriter().write(frame.toString());
}
And I fetch it in my Ajax Post request as:
success: function (result) {
console.log(result);
document.getElementById('logs').innerHTML = '<br>' + result ;
}
HTML:
<div id="logs" class="text-center" style="margin-top: 25px;">
</div>
But I get all the lines mixed into 18 lines. Seems like the <br> doesn't work.
How can I exactly print each String in each line of the HTML?
There are 2 alternatives. First, you can add the line breaks when you build the response in your Java method...
response.getWriter().write("<br />" + frame.toString());
or (depending on whether you need to prepend or append the line breaks)
response.getWriter().write(frame.toString() + "<br />");
Secondly, you could split the response (assuming their are line breaks) and rejoin with Html line breaks, using Javascript...
document.getElementById('logs').innerHTML = '<br>' + result.split("\n").join("<br/>");
The second option depends on the format of the response data, so the first option is probably your best bet.
As "Nick A" mentioned in his comment, you should append new result to the contents of your <div> element instead of replacing it. So your Ajax function should be something like this (= replaced with +=):
success: function (result) {
console.log(result);
document.getElementById('logs').innerHTML += '<br/>' + result ;
}
Edit:
The main issue is that you're appending all data to the result on your server without putting any delimiter so that you could separate them on the client. You can also try adding the <br/> on your server side code as below:
for(Frame frame : frames) {
response.getWriter().write(frame.toString() + "<br/>");
}
and then use your original ajax function on the client side.
Assuming that result is just one big string that contains the string representation of any given frame, you just missed adding a new line here:
for(Frame frame : frames) {
response.getWriter().write(frame.toString() + '<br/>');
}
I prepared two short examples for you:
What you currently do:
var p = document.getElementById('myP');
var frames = new Array('FrameA', 'FrameB', 'FrameC');
var result = '';
// append each frames without adding a new line
for (var i = 0; i < frames.length; i++) {
result += frames[i];
}
p.innerHTML = result;
<p id="myP"></p>
What you want to do:
var p = document.getElementById('myP');
var frames = new Array('FrameA', 'FrameB', 'FrameC');
var result = '';
// appending the frames with adding newlines
for (var i = 0; i < frames.length; i++) {
result += frames[i] + '<br/>';
}
p.innerHTML = result;
<p id="myP"></p>

Advancing numeric string in localstorage

Working on a little task tracker applet that uses localstorage to both store tasks and keep a running tab of how many tasks have been created to date. The later is my issue.
Here's what I'm running, the issue is contained to variables "taskTracker" and "advanceTask".
function saveTask() {
var task = $("#task").val();
var taskDate = $("#taskDate").val();
if (newUser == null) {
var taskNumber = 0;
localStorage.setItem("taskTracker", "0");
localStorage.setItem("newUser", "no");
}
else {
var taskNumber = localStorage.getItem("taskTracker");
}
var advanceTask = taskNumber + 1;
localStorage.setItem('task' + taskNumber, task);
localStorage.setItem('task' + taskNumber + 'date', taskDate);
localStorage.setItem("taskTracker", advanceTask);
console.log(advanceTask);
displayTasks();
}
If you take a look at the "advanceTask" variable, my intention is to advance the numerical value stored in "taskTracker" each time this function is invoked. However, all I'm getting is an additional "1" appended to the value each time.
Thoughts? <3
There is a difference between string + number and number + number. Your current solution is like the stringPlusOne function below. You need to convert the string to a number (using parseInt is one way) and then do the math, like the stringPlusOne2 function below
function stringPlusOne(str) {
console.log(str + 1);
}
function stringPlusOne2(str) {
console.log(parseInt(str, 10) + 1);
}
stringPlusOne("2");
stringPlusOne2("2");

Issue with passing property through function

First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}
Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.

regexp looping and logic in javascript

Not certain if this can be done in regexp under javascript, but thought it would be interesting to see if it is possible.
So thought I would clean up a piece of html to remove most tags, literally just dropping them, so <H1><img><a href ....>. And that would be relatively simple (well, stole the basis from another post, thanks karim79 Remove HTML Tags in Javascript with Regex).
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex = /(<([^>]+)>)/ig
var outString = inString.replace(regex, "");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But then I started thinking, is there a way where I can control regex execution. So lets say that I want to keep certain tabs, like b,br,i and maybe change H1-6 to b. So in pseudo code, something like:
for ( var i in inString.regex.hits ) {
if ( hits[i] == H1 ) {
hits[i] = b;
}
}
The issue is that I want the text thats not HTML tags to stay as it is, and I want it to just cut out by default. One option would of course be to change the ones I want to keep. Say change <b> to [[b]], once that is done to all the ones of interest. Then put them back to <b> once all unknown have been removed. So like this (only for b, and not certain the code below would work):
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex-remHTML = /(<([^>]+)>)/ig
var regex-hideB = /(<b>)/ig
var regex-showB = /([b])/ig
var outString = inString.replace(regex-hideB, "[b]");
outString = outString.replace(regex-remHTML, "");
outString = outString.replace(regex-showB, "<b>");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But would it be possible to be smarter, writing cod ethat says here is a peice of HTML tag, run this code against the match.
As Tim Biegeleisen sai in its comment, maybe a better solution could be using a parser instead of a Regex...
By the way, if you want to control what is going to be changed by the regex you can pass a callback to the String.prototype.replace:
var input = "<div><h1>CIAO Bello</h1></div>";
var output = input.replace(/(<([^>]+)>)/gi, (val) => {
if(val.indexOf("div") > -1) {
return "";
}
return val;
})
;
console.log("output", output);

Javascript assignment for school involving objects and Validation not working correctly

the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.

Categories

Resources