Insert Record in Database Using Textboxes in JavaScript - javascript

I'm trying to in Insert Record in Database Using Textboxes in JavaScript. I'm referring this link http://www.c-sharpcorner.com/UploadFile/5089e0/insert-record-in-database-using-textboxes-in-javascript/
This solution is working only on internet explorer but I want to use this program for all browser.
Here is my piece of code:
function InsertRecord()
{
var txtid = document.getElementById('txtid').value;
var txtname = document.getElementById('txtname').value;
var txtsalary = document.getElementById('txtsalary').value;
var txtcity = document.getElementById('txtcity').value;
if (txtid.length != 0 || txtname.length !=0 || txtsalary.length !=0|| txtcity.length !=0)
{
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Data Source=.;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=****;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("insert into Emp_Info values('" + txtid + "','" + txtname + "','" + txtsalary + "','" + txtcity + "')", connection);
alert("Insert Record Successfuly");
txtid.value = " ";
connection.close();
}
else
{
alert("Please Enter Employee \n Id \n Name \n Salary \n City ");
}
}
If anyone know then let me know that how will be execute this code for all browser.

There is no way to achieve this on other browsers.
The code is instantiating an ActiveX control that connects to the database and that technology is not supported on any browser but Internet Explorer. Actually, the new Microsoft Edge browser doesn't support it either.
So:
Only IE supports it
Future browsers from Microsoft will not support it
The code above contains the username and password to a database which could be a huge security risk.
Don't do that, use another technology (like AJAX) to send the info to a backend and write it from there to a database.

Related

Acrobat JavaScript mailDoc operation failing

Goal: I have a fillable PDF form that collects data required to send an email. In the PDF, I have a button to send the PDF, using the mailDoc function on mouse up.
if(app.viewerVersion < 11 )
app.alert("Please download the latest version of Reader",1);
var cToAddr = "email#yahoo.com";
var cBCCAddr = "email#yahoo.com";
var cCCAddr = this.getField("ClientEmail").value;
var cBenAddr = this.getField("BennyEmail").value;
if(cBenAddr != "") {
cCCAddr += ";" + cBenAddr;
}
var cSubLine = "Service Proposal " + this.getField("ServiceAddress").value + " " + this.getField("Text1").value;
var cBody = "Thank you for the opportunity. Please see attached proposal.\n" + "Save the filled form attachment for your own records";
this.mailDoc({
bUI: true,
cTo: cToAddr,
cCc: cCCAddr,
cBcc: cBCCAddr,
cSubject: cSubLine,
cMsg: cBody
});
Error Message:
GeneralError: Operation failed.
Doc.mailDoc:22:AcroForm:Email Quote:Annot1:MouseUp:Action1
I've followed this guide and added a cBcc as they did in this community post, but it had no impact.
The fields are accurately named, and it prompts me to sign into my email account when I press the button, so I'm not sure what is causing the issue, and can't find documentation for mailDoc to help.
Your code is correct. This seems to be a bug when using Yahoo! to send the email. When I try to send it via Outlook or Gmail it works for me (and fails on Yahoo!).
You can find the javascript documentation here: http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/js_api_reference.pdf#G5.2237013

change the connector type from javascript to Database Reader in javascript mode mirth?

When change the connector type from javascript to Database Reader in javascript mode, I recivied an error
Received invalid list entry in channel expected Map
how to use List<Map<String, Object>> or ResultSet instead of java.util.ArrayList() .
var dbConn = globalMap.get('tes55');
if (dbConn == null || !dbConn.getConnection().isValid(1))
{
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('oracle.jdbc.driver.OracleDriver','jdbc:oracle:thin:#10.123.117.203:1521/UAT','intg','intg');
dbConn.getConnection().setNetworkTimeout(java.util.concurrent.Executors.newFixedThreadPool(1), 30000);
globalMap.put('tes55',dbConn);
}
dbConn.setAutoCommit(false);
try{
var x="select IH_HL7_OUM_ID, MESSAGE_ID, frame_text from ideal.EHS_Acks_MESSAGES s WHERE (message_type = 'S12' or message_type = 'S15' or message_type = 'A04' or message_type = 'A11') and rownum<=2";
var rs=dbConn.getConnection().createStatement().executeQuery(x);
var msgs=new java.util.ArrayList();
while(rs.next()){
var IH_HL7_OUM_ID=rs.getString("IH_HL7_OUM_ID");
var MESSAGE_ID =rs.getString("MESSAGE_ID");
var frame_text =rs.getString("frame_text");
// logger.info(MESSAGE_ID);
//logger.info(IH_HL7_OUM_ID);
// logger.info(frame_text);
msgs.add(frame_text);
//map.set(frame_text);
var query="update ih_hl7_outbound_messages set IS_SENT= 2 where MESSAGE_ID ="+MESSAGE_ID+" and id<="+IH_HL7_OUM_ID;
var update=dbConn.executeUpdate(query);
//logger.info(update);
dbConn.commit();
//logger.info(query);
}
rs.close();
return msgs;
}
catch(exp)
{
returned_response = ResponseFactory.getQueuedResponse("Failed to execute the query " + "\nReason: " + exp.message);
logger.error(exp.message);
alerts.sendAlert("\n\nMessage ID: " +$('msgID') + "\nMessage type: " +$('msgtype')+"\nException: "+exp.message +"\nMessage :\n"+msgs.add(frame_text));
try{dbConn.close();}catch(ignore){logger.info("Close Connection: "+ignore.message);}
}
finally
{
try{rs.close();}catch(ignore){logger.info("Close Cursor: "+ignore.message);}
}
return returned_response;
Mirth Database Reader will ease you data fetching process. We need not write many codes and complicate in the source listener
You can see URL specified you can select the DB type you want, in your case it's oracle, automatically the URL will be filled. provide your username and password to access the DB.
click on "select" button over the SQL text area this will open a pop-up displaying all the tables to be selected. once you click tick on the tables you want. The code will be generated automatically.
If you want to do join or perform any query operation you can do that there in the generated code on the text area content.

Catching SQL errors and preventing a form from being submitted

I have a little application that allows users to search for locations on a mac submit comments to a CartoDB SQL database (PostgreSQL) http://docs.cartodb.com/cartodb-platform/sql-api.html using an HMTL form, JavaScript and SQL (and a little PHP to make the API connection to CartoDB). It works great for vast majority of users, but some submissions are not coming through.
I have no idea why the SQL submissions are working sometimes and not others, works perfectly every time for me. Although I have tracked one issue down to Safari 5.1, but I think it must be happening in other browsers too. The main problem is I can't see any errors ANYWHERE, so it's impossible to track down.
So here are my questions:
1. Is there any way of catching SQL errors and preventing the form from being submitted?
2. Is there any way of seeing SQL errors so I can track down the problem?
Below is a snippet of the code I am using to submit the comments:
var tblName = "comment_collection"
var usrName = "***dney"
// FORM
$("#allSubmitBtn").click(function (e) {
//CHECK IF has a comment
if (!notEmpty(document.getElementById('description1'))) {
alert('Please enter a comment.');
return false;
}
if (!notEmpty(document.getElementById('latlongit1'))) {
alert('Sorry, there has been an error, please search for a location again.');
return false;
} else {
currentNeighborhood = $('#neighborhoodName1').val();
parcel = $('#parcel_id1').val();
address = $('#pre_address1').val();
userAddress = $('#UserAddress1').val();
phoneNum = $('#phone1').val();
emailAdd = $('#emailAddress1').val();
userType = $('#userType1').val();
otherUser = $('#otherUserType1').val();
currentDescription = $('#description1').val();
latlongy = $("input[name='latlongit1']").val();
explainType = $('#explainType').val();
currentProject = selectedCity.name;
commentType = new Array();
$("input:checkbox[name=commentType]:checked").each(function () {
commentType.push($(this).val());
});
var sql = "INSERT INTO " + tblName + " (the_geom, project, description, name,comment_address,parcel_id,phone_number,email_address,comment_type,comment_type_other,user_type,user_type_other,profile_address,flag,loved) VALUES (ST_SetSRID(ST_GeomFromGeoJSON('";
// var a = layer.getLatLng();
// console.log(a);
var sql2 = '{"type":"Point","coordinates":[' + latlongy + "]}'),4326),'" + currentProject + "','" + (currentDescription.replace(/'/g, "''")).replace(/"/g, "''") + "','" + (currentNeighborhood.replace(/'/g, "''")).replace(/"/g, "''") + "','" + address + "','" + parcel + "','" + phoneNum + "','" + emailAdd + "','" + commentType + "','" + explainType + "','" + userType + "','" + otherUser + "','" + userAddress + "','false','0')";
var pURL = sql + sql2;
console.log(pURL);
submitToProxy(pURL);
alert("Your Comments have been submitted");
return true;
}
});
here is the Github repo the tutorial is based off. Security is a MAJOR issue and is mentioned right off the bat with this tutorial. It is more of an illustration than anything, anyone implementing it should modify the scripts to be more secure.
Check out this pull request and try to create a solution from it. It addresses the issue to a degree. It moves more of the query into the PHP scripts and only allows field names in from the browser.
https://github.com/enam/neighborhoods/pull/4
This is incredibly dangerous/bad code. You're building sql on the client and sending it to the server to be executed. What's to stop someone from popping up their js console and doing submitToProxy('DROP DATABASE DATABASE()')?
Boom goes your site, boo hoo, too bad.
And even if you DON'T nuke this code from orbit, just to be sure it's really dead, and keep using it, you can't trap SQL exceptions, because they occur on the server, not in your client. At best your SERVER has to check for errors, and send back an appropriate message, e.g.
result = run_query(dangerous ql from user);
if (error occured) {
return json_encode('error' => true, 'reason' => 'someone set us up the bomb'));
} else {
return json_encode('error' => false, 'data' => query results);
}
and then your client-side ajax has to do
$.ajax(....
success: function (data) {
if (data.error) { alert('boom!'); }
else {... do stuff with data ...}

how to trap an error and save error detail in database and redirect to custom error page in classic asp?

how to trap an error and save error detail in database and redirect to custom error page in classic asp?
I want that I should include a asp page in all page of my website and if any error occur it get that error detail, saved it to database or mail it to mail id and redirect to custom error page.
Please if you have any idea then please help me.
Classic ASP has no try/catch.
It also uses VBscript by default and the answer above is, I'm guessing, C#?
Here is VBscript ASP for what you are trying to do:
<%
Set conn = Server.CreateObject("ADODB.Connection")
SQL_server_string = "Provider=SQLOLEDB; Data Source=myMachine; Initial Catalog=pubs; User ID=sa; Password=pw"
ConnectionString = SQL_server_string
conn.Open ConnectionString
s = "INSERT INTO"
s = s & " tablename "
s = s & "("
s = s & " fieldname1 "
s = s & ",fieldname2 "
s = s & ") "
s = s & "VALUES"
s = s & "( "
s = s & "'" & stringvalue1 & "'"
s = s & ",'" & stringvalue2 & "'"
s = s & ") "
conn.execute(s)
if (err.number<>0) then
m = "error on page ___ line ____<br>"
m = m & "error number: " & err.number & "<br>"
m = m & "error description: " & err.description & "<br>"
m = m 7 "sql: " & s & "<br>"
session("msg") = m
set conn=nothing
response.redirect("error_report.asp")
end if
'got past error checking... do stuff...
%>
use try catch methods in javascript to catch the errors. Within the catch block post the data to the server. In server have an aspx page or php page which one you are familiar. Get the data to be inserted as parameters from this post back in that aspx/php file and from that file insert into DB.
<script>
var txt="";
function ProcessData()
{
try
{
....
}
catch(err)
{
var message = err.message;
$ajax({
type:"POST",
url:"Errorhandler.aspx/InsertErrordetails",
data:"{error: '" + message + "'}",
clientType:"application/json; charset=utf-8",
datatype:"json",
async: false,
success: function () { alert("success"); },
error: function(){alert("error");}
});
}
}
</script>
The server side code appears like this.
public static void InsertErrordetails(string error)
{
SqlConnection Con = new SqlConnection(#"Server=db;Integrated Security=True;" + "Database=userdb");
string query = "INSERT INTO [LogTable]([Message])" +
"VALUES (#error)";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Message", error);
try
{
Con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
Con.Close();
}
}

Google Apps Script: Workflow approval Selecting approval broken

I'm working to expand on the workflow script posted here...
James Ferreira Workflow video.
I've expanded the script and all is working fine regarding email, but I'm running into an issue with the doGet() function not working corretly.
Here is the code from the video: (mycode for the sendEmail is different and works fine, as it uses and document template.
function sendEmail(e) {
var email = e.values[1];
var Item = e.values[2];
var cost = e.values[3];
var url = '<ENTER YOUR PUBLISHED URL>';
var approve = url + '&approval=true'+'&reply='+email;
var reject = url + '&approval=false'+'&reply='+email;
var html = "<body>"+
"<h2>Please review</h2><br />"+
Item +": " + cost+ "<br />"+
"Approve<br />"+
"Reject<br />"+
"</body>";
MailApp.sendEmail("jjones#beaconcloudsolutions.com", "Approval Request",
"What no html?", {htmlBody: html});
}
function doGet(e){
var answer = (e.parameter.approval == 'true') ? 'Buy it!' : 'Not this time, Keep saving';
MailApp.sendEmail(e.parameter.reply, "Purchase Request",
"Your manager said: "+ answer);
var app = UiApp.createApplication();
app.add(app.createHTML('<h2>An email was sent to '+ e.parameter.reply + ' saying: '+ answer + '</h2>'))
return app
}
So when the script runs, i get the email that shows the links for approval / rejected, but when I select the link for approval or / rejected i get
"Sorry, the page (or document) you have requested does not exist." " Please check the address and try again."
This link should be redirect to the published webapp, noted in the var URL and append either the var approve or reject to it and then just display a basic HTML page.
Any suggestions on what is wrong? the script is authorized..
What does the address bar say when you click on the link from the email? Perhaps something is malformed or not properly encoded.
My gut feeling right now is that there is a missing '?' before you append any params.
Perhaps try this -
//note the ? instead of &
var approve = url + '?approval=true'+'&reply='+email;
var reject = url + '?approval=false'+'&reply='+email;

Categories

Resources