can't get ajax to work with jsp - javascript

Ok, so I'm learning web design as a co-op at a company. However, the department I'm in is lacking in knowledgeable people in web design. So here we go...
Building a site that will allow the department to manage PTO. I want to implement ajax b/c the main page will have a calendar system so the manager can view the PTO week by week. As a precursor to that, I'm attempting to implement ajax with the "add Employee" page for practice.
However, I can't seem to figure out what I'm missing (aka, why it's not doing anything)
This page just needs to add the new employee to the database. No display needed.
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
Simple enough so far.
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
This is the part where I'm assuming it's correct as I'm still learning ajax and how it works. I don't think I need to handle a response as I simply want the called jsp file to automatically do whats needed. (if that's possible).
The jsp file looks like this
<%
ResultSet rsEmpl;
Connection connection1 = getDBConnection();
Statement statment1=connection1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String fName = request.getParameter("firstNameField");
String lName = request.getParameter("lastNameField");
String manager = request.getParameter("managerField");
String networkID = request.getParameter("networkIDField");
Int empId = 0;
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
%>
I have a button on the page that executes the javascript function that contains the ajax info. I'm avoiding jquery atm b/c I'm trying to understand this stuff and how it works before I attempt to use "shortcuts" like jquery. I'm working towards a degree in Software Engineering so understanding this stuff is my priority, not getting it done.(that's just a bonus) If you need anymore information I can provide it. Sorry for my lack of knowledge and if this is completely off base then :(

The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
That gives you whole HTML DOM elements back, not the values of those elements. HTML DOM elements are like Java classes, having properties, methods and so on. Assuming that it are HTML input elements like <input>, then use their value property instead to get the value. So:
var firstName = document.getElementById("firstNameField").value;
var lastName = document.getElementById("lastNameField").value;
var manager = document.getElementById("managerField").value;
var networkID = document.getElementById("networkIDField").value;
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
The escape() is the wrong function. It escapes JS syntax, it does not encode URI components. You should be using encodeURIComponent() function instead.
The jsp file looks like this
...
Int empId = 0;
...
This doesn't compile. It should be int instead.
...
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
...
Unnecessarily overcomplicated. Learn how to use DB builtin sequences/autoincrement IDs. Refer the DB specific manual or ask DB admin for help.
...
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
...
You should put quotes around string values in the SQL query. Assuming that lName, fName and networkID are strings, not numbers, then it should look like this:
statement1.execute("INSERT INTO PTO_employee VALUES (" + empID + ",'" + lName + "','" + fName + "'," + 0 + "," + 2 + ",'" + networkID + "'");
But you have there a huge SQL injection attack hole and you also don't seem to close DB resources at all after use, so they may leak away and cause your webapp to crash sooner or later because the DB runs out of resources. Use PreparedStatement to create a parameterized SQL query and use its setters to set the values. Close the resources in finally block.
After all, reading the server logs should provide you information about compile errors and any server exceptions. Reading the ajax response should provide you information about the response status and body. Your core problem was that you ignored it and thus didn't have any chance to understand what is happening.

Related

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

How to pass the csv file from file cabinet in NetSuite to ftp server using JavaScript?

Could you help me do the task using JavaScript?
I have a task and if i do it manually it looks like this:
i create Saved Search in NetSuite.
Download the result of created saved search in csv.
The i put this file on ftp server, using FileZilla. (i had a connection with server previously: write a domain, username and password - that's all)
Now, a need it solve through sutlet script.
1. Create Saved Search - done
2. Create csv with result of saved search in content and put it in file cabinet in the NetSuite - done
3. Ok, now i have a needs me file but i do not understand how to pass it on ftp.
*i tried to study several articles, but frankly speaking could not to solve my problem. Moreover, their article seems about manually method not automative
this aritcle - https://ursuscode.com/netsuite-tips/suitescript-2-0-sftp-tool/*
var searchResult = Contacts.run().getRange(0,999);
log.debug('Contacts', searchResult);
var Header = 'INTERNAL ID' + ';' + 'FIRST NAME' + ';' + 'LAST NAME';
var Content = "";
for (var i = 0; i < searchResult.length; i++) {
var internalid = searchResult[i].getValue('internalid');
var FirstName = searchResult[i].getValue('firstname');
var LastName = searchResult[i].getValue('lastname');
Content = Content + internalid + ';'
+ FirstName + ';'
+ LastName;
Content = Content + '\n';
}
var fileObj = file.create({
name: 'test.csv',
fileType: file.Type.CSV,
contents: Header + '\n' + Content
});
fileObj.folder = 45434;
var fileId = fileObj.save();
var savedFileObj = file.load({
id: fileId
});
var myPwGuid = '';
var myHostKey = ''
var objConnection = sftp.createConnection({
username: '',
passwordGuid: myPwGuid,
url: 'ftp.expertsender.com',
hostKey: myHostKey
});
NetSuite does not support ftp, it only supports sftp.
NetSuite has the support for SFTP, FTP and SFTP runs in different port numbers, However FTP transfers data in plain text format which will compromise your security, using SFTP is the better option as it will transfer your data in encrypted format and security is assured.
In your example, I believe you're calling FTP request which will not work in this case.
Oki,
Now, the article you did mention is the right one : why ? Because the first required step to be able to use SFTP is to generate a GUID. You are talking about manual methods, well yes, including the one in that Article, but it is not a problem, because once you have generated the GUID, you don't need to change it, so it is a one time action, unless your ftp credential change.
So, first step : use "ursuscode" to create a Suitelet. Deploy that suitelet and use it to generate the GUID (it is a form where you need to set the ftp password, host...). Using the same form, you can then generate the HOST key (check the video).
Second step, use the Generated GUID and HOST Key in your code.
Third step, add the code to upload the file : from netsuite help page, here is an example:
connection.upload({
directory: 'relative/path/to/remote/dir',
filename: 'newFileNameOnServer.js',
file: myFileToUpload,
replaceExisting: true
});
By the way, you can upload the file without the need to Save and Reload it again (https://system.na2.netsuite.com/app/help/helpcenter.nl?fid=section_4617004932.html).
Note: remember that this is an SFTP, so probably support only SFTP not FTP.
Suggestion: About the GUID (and the other data needed for the connection), I suggest that you use a Script Parameter to provide the GUID to your script code, so if your password change, you can regenerate the GUID and update the script parameter value without the need to touch your code.
Hope this helps!

How can i retrive from website with high javascript in Android?

http://www.biletix.com/search/TURKIYE/en#!subcat_interval:12/12/15TO19/12/15
I want to get data from this website. When i use jsoup, it cant execute because of javascript. Despite all my efforts, still couldnot manage.
enter image description here
As you can see, i only want to get name and url. Then i can go to that url and get begin-end time and location.
I dont want to use headless browsers. Do you know any alternatives?
Sometimes javascript and json based web pages are easier to scrape than plain html ones.
If you inspect carefully the network traffic (for example, with browser developer tools) you'll realize that page is making a GET request that returns a json string with all the data you need. You'll be able to parse that json with any json library.
URL is:
http://www.biletix.com/solr/en/select/?start=0&rows=100&fq=end%3A[2015-12-12T00%3A00%3A00Z%20TO%202015-12-19T00%3A00%3A00Z%2B1DAY]&sort=vote%20desc,start%20asc&&wt=json
You can generate this URL in a similar way you are generating the URL you put in your question.
A fragment of the json you'll get is:
....
"id":"SZ683",
"venuecount":"1",
"category":"ART",
"start":"2015-12-12T18:30:00Z",
"subcategory":"tiyatro$ART",
"name":"The Last Couple to Meet Online",
"venuecode":"BT",
.....
There you can see the name and URL is easily generated using id field (SZ683), for example: http://www.biletix.com/etkinlik/SZ683/TURKIYE/en
------- EDIT -------
Get the json data is more difficult than I initially thought. Server requires a cookie in order to return correct data so we need:
To do a first GET, fetch the cookie and do a second GET for obtain the json data. This is easy using Jsoup.
Then we will parse the response using org.json.
This is a working example:
//Only as example please DON'T use in production code without error control and more robust parsing
//note the smaller change in server will break this code!!
public static void main(String[] args) throws IOException {
//We do a initial GET to retrieve the cookie
Document doc = Jsoup.connect("http://www.biletix.com/").get();
Element body = doc.head();
//needs error control
String script = body.select("script").get(0).html();
//Not the more robust way of doing it ...
Pattern p = Pattern.compile("document\\.cookie\\s*=\\s*'(\\w+)=(.*?);");
Matcher m = p.matcher(script);
m.find();
String cookieName = m.group(1);
String cookieValue = m.group(2);
//I'm supposing url is already built
//removing url last part (json.wrf=jsonp1450136314484) result will be parsed more easily
String url = "http://www.biletix.com/solr/tr/select/?start=0&rows=100&q=subcategory:tiyatro$ART&qt=standard&fq=region:%22ISTANBUL%22&fq=end%3A%5B2015-12-15T00%3A00%3A00Z%20TO%202017-12-15T00%3A00%3A00Z%2B1DAY%5D&sort=start%20asc&&wt=json";
Document document = Jsoup.connect(url)
.cookie(cookieName, cookieValue) //introducing the cookie we will get the corect results
.get();
String bodyText = document.body().text();
//We parse the json and extract the data
JSONObject jsonObject = new JSONObject(bodyText);
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("docs");
for (Object object : jsonArray) {
JSONObject item = (JSONObject) object;
System.out.println("name = " + item.getString("name"));
System.out.println("link = " + "http://www.biletix.com/etkinlik/" + item.getString("id") + "/TURKIYE/en");
//similarly you can fetch more info ...
System.out.println();
}
}
I skipped the URL generation as I suppose you know how to generate it.
I hope all the explanation is clear, english isn't my first language so it is difficult for me to explain myself.

javascript active directory user / groups query

Is it possible to query AD from javascript?
I'm working from within SharePoint, and I can get the current SharePoint user's information using some js I found on a blog.
But I'm wondering if I can then query AD to see if the current user is in a specific AD group.
I think you'd be better off writing a quick asp.net page that you could call via AJAX and get some JSON back. .NET directory services class are going to be much better at talking to Active Directory than javascript, unless you can find a js library specifically for this (which I haven't been able to find).
This is a little late, but for future visitors from Google, I had to write something in JavaScript to fix a scheduled task that is run with cscript:
var conn = WScript.CreateObject("ADODB.Connection")
var rootDSE = GetObject("LDAP://RootDSE");
var context = rootDSE.Get("defaultNamingContext");
conn.Provider = "ADsDSOObject";
conn.Open("ADs Provider");
var query = "<LDAP://" + context + ">;(&(objectCategory=person)(objectClass=user));samAccountName;subtree";
var cmd = WScript.CreateObject("ADODB.Command");
cmd.ActiveConnection = conn;
cmd.CommandText = query;
cmd.Properties.Item("SearchScope") = 2;
cmd.Properties.Item("Page Size") = 500;
var r = cmd.Execute();
while(!r.EOF)
{
for (var e=new Enumerator(r.Fields);!e.atEnd();e.moveNext())
{
WScript.Stdout.Write(e.Item().name + "=" + e.Item().value + " ");
}
WScript.Stdout.WriteLine("");
r.MoveNext();
}
There is no way known to me how one could access AD from a client script. I could only think of some kind of an ActiveX control which does the job, however that 1) would work only in IE 2) would also be limited to zone settings in IE.
So, the reason is why you need this. Most probably, to be able to show the user something or hide something from the user. If this is the case, you could think of applying the "target audiences" solution to your page (see here - http://office.microsoft.com/en-us/sharepointserver/HA101690531033.aspx). For instance, add two versions of your webpart to the page, one for users who are in the group and another for users who aren't.
If you really need to have this information on the client side in JS, you can create some "AD helper" web service on your server and call into that service using AJAX, as per #squillman's post.

passing password values using javascript/ajax to php page

iam using a simple insert script function to pass the values from registration html page to register php page.
Here is my script:
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var dispname= encodeURI(document.getElementById('disp_name').value);
var firstname= (document.getElementById('first_name').value);
var lastname= (document.getElementById('last_name').value);
var gender= (document.getElementById('genderreg').value);
var day= (document.getElementById('day').value);
var month= (document.getElementById('month').value);
var year= (document.getElementById('year').value);
var country= (document.getElementById('countryreg').value);
var city= (document.getElementById('cityreg').value);
var suburb= (document.getElementById('suburbreg').value);
var email= (document.getElementById('emailreg').value);
var password= (document.getElementById('regpassword').value);
var code= (document.getElementById('code').value);
var service= (document.getElementById('termservice').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'register_insert.php?site_url='+dispname+'&fname= '+firstname+'&lname= '+lastname+'&gender= '+gender
+'&day= '+day+'&month= '+month+'&year= '+year+'&country= '+country+'&city= '+city+'&suburb= '+suburb
+'&email= '+email+'&password= '+password+'&code= '+code+'&service= '+service+'&nocache= '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
I just have a small question that is it a good pratice of passing the password values like this from html to php page. If it is not good idea then what is the best why to do so.
Thanks in advance for sugesstions.
Yeah, ordinarily I wouldn't immediately suggest that someone go to a javascript library, but I make an exception for AJAX. Getting that sort of thing to work cross-browser is just plain not-worth-it. Go for jQuery and save yourself a heap of stress.
Also take a look at the jQuery Form Plugin - it'll do all this for you in a very easy way. The site is at http://malsup.com/jquery/form/ .
But to answer your question, I'd use POST data. The general rule of thumb is that if you're retrieving something, use GET, but if you're sending or changing something, use POST.
Another quick pointer is that the code could be made a lot more legible by doing something like this:
var fields = {'disp_name', 'first_name', 'last_name', 'genderreg' /* etc ... */ ];
var values = {};
for (var i = 0, l = fields.length; i < l; ++i) {
values[fields[i]] = document.getElementById(fields[i]).value;
}
http.open(
'get',
'register_insert.php'
+ '?site_url=' + values.dispname
+ '&fname=' + values.first_name
+ '&lname=' + values.last_name /* etc */
);
...but it's not really that important I suppose.
Sending The password in this manner is no different from a regular From Submission via GET. Generally however, you would use POST. The downside to using get is that the password will appear in the URL. If you care about security, you should be using SSL.
Consider using a JS library like jQuery... it would make what you are doing above.. very easy.

Categories