I'm creating a filter page in springboot that works fine. When I add my javascript to the html page to make a query using an .change event listener, I want to use this query to live show available results before submitting the form. It looks like this (shorter version, otherwise its just var declaration that's not part of the problem)
$("#leadsForm").change(function () {
//revenue
var revMin = document.getElementById("revenueMin").value
var revMax = document.getElementById("revenueMax").value
//reg date
var regDateMin = document.getElementById("regDateMin").value
var regDateMax = document.getElementById("regDateMax").value
var mainBranch = $('#mainBranch').val();
var specificBranch = $('#specificBranch').val();
var county = $('#county').val();
var tel = document.getElementById("containsTel").value
var contactPerson = document.getElementById("containsContactPerson").checked
var location = document.getElementById("containsLocation").checked
var employed = document.getElementById("containsEmployed").checked
var keyValues = document.getElementById("containsKeyValues").checked
var email = document.getElementById("containsEmail").checked
var website = document.getElementById("containsWebsite").checked
var wholeQuery = "SELECT "+selectedColumns + " from company" + " WHERE " + revenueSelector +
regDateSelector + branchSelector +
countySelector + telSelector + keyValuesSelector + contactPersonSelector + emailSelector +
websiteSelector + locationSelector + employedSelector;
console.log(wholeQuery)
I want to find a way to use this query, JAVASCRIPT SIDE to make the available result change on the .change eventlistener based on userinput, variables above in my variable "wholeQuery".
I use the code
const mysql = require((["mysql"]))
const db = mysql.createConnection({
host : "localhost",
user : "*****",
password: "*****",
database: "mydb"
})
console.log(db)
but get the Error:
Uncaught Error: Script error for "mysql"
https://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:5)
at HTMLScriptElement.onScriptError (require.js:5)
The problem is that I can't connect to my SQL database through Javascript, is there any other way than the one above? I'm doing the solution most other threads recommend but its not working in my case because my project is not a node.js project.
I am a little confused, why connect directly to MySQL in the javascript? Wouldn't it make more sense to have a API call in Springboot that the js side talks to to get this? Judging by your code fragment you have a node.js project of some sort like this one?
If you are using Springboot, I think you need to create a API that talks to MySQL, so your javascript will call the API (using something like Axios maybe?)
Related
Can someone provide a simple complete example of loading an existing sqlite database not using node.js.
Assume that the sql db is sitting in same location as index.html
example:
I tried this example but "contents" is undefined. Also, I would not know how to access the data in "contents"? I could really use a complete example.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/database.sqlite', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
var db = new SQL.Database(uInt8Array);
var contents = db.exec("SELECT * FROM my_table");
// contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
xhr.send();
I know this is old, but here you go my friend. You were right there, just a bit of tweaking. I am not sure if you are using the SQL.js library from GitHub but please do as it solves a lot of the browser security issues and makes the SQL side of things much easier on the brain.
If you didn't create the source or have some UTF issues the exceptions will be thrown. I wrote this in a night so I haven't run more than a few functions but I am assuming callbacks will be required to prevent SQLite issues during async processes. This is my first time using SQLite or the SQL.js library so I just don't know yet.
IMPORTANT!
This is a LOCAL solution only, it has more blatant vulnerabilities than a high school locker room. In no way should this ever be used on anything that is exposed to the internet.
This is all declared at the top of my class, not within a function. This is purposeful as I run multiple queries and didn't want the overhead of loading/unloading the object if it got too large.
Notice the fully qualified path on the source...relative paths didn't work for me.
var xhrLocal = new XMLHttpRequest();
xhrLocal.open('GET', 'http://localhost/mp3/data/media.sqlite', true);
xhrLocal.responseType = 'arraybuffer';
var localData;
xhrLocal.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
localData = new SQL.Database(uInt8Array);
};
xhrLocal.send();
At this point you have the database loaded into an object called localData and you can query it from anywhere. Here is a query I wrote to get Genre info.
function FillGenreLists() {
var sqlSel = 'SELECT * FROM GenreData';
var data = localData.exec(sqlSel);
var output = [];
$.each(data[0].values, function(key, value)
{
output.push('<option value="'+ value[0] +'">'+ value[1] +'</option>');
});
$('#selGenres').html(output.join(''));
}
The output from the SQL call is generally an array of arrays, don't worry about changing that, just output the result of your SQL call to the console and note the return fields and values, from there just use $.each to your hearts content.
Here is another query, same premise but with the goal of creating a SQL statement to push into MS SQL server and get FreeDB data about artists that are in my local collection.
Note: This could all be done in a single call by querying my local sqlite table, generating the sql and pushing it to the MS SQL using a different conn or even better by utilizing a generic proc but let's keep it simple for now.
function PrepareMSSQLFilteredFreeDBTables(StartLetter, EndLetter, TempTableName) {
var sqlSel = "SELECT * FROM ArtistData WHERE ArtistText BETWEEN '" + StartLetter + "' AND '" + EndLetter + "' ORDER BY ArtistText";
var data = localData.exec(sqlSel);
$('.array-cols').append('SELECT * INTO ' + TempTableName + ' FROM FreeDB WHERE DARTIST IN (');
var iLen = (data[0].values.length - 1);
$.each(data[0].values, function(a, b) {
var sRes;
if (a === iLen) { sRes = "'" + b[1].replace("'", "''") + "')"; }
else { sRes = "'" + b[1].replace("'", "''") + "', "; }
$('.array-cols').append(sRes);
});
}
I am trying to use the python suds module to send requests to a soap service and retrieve results, but am unsure of how to enter in the parameters for the method I want to call. I have been successul in accessing the service and retrieving the methods which show the paramaters and data types, but I haven't had luck in getting a response which I try to send a request. I'm new with this so am unsure of what I am doing wrong. I'm getting this error: suds.WebFault: Server raised fault: 'java.rmi.RemoteException' on the line that initiates the response. I suspect I am not inputting the parameters correctly for the method, but it's not clear to me how to revise it. I want to call the getPostmileForPoint method. This is what I have so far:
import suds
from suds.client import Client
url = 'http://geo.dot.ca.gov/services/PostmileWebService?wsdl'
client = Client(url)
response = client.service.getPostmileForPoint(inputPoint=[None,None,-119.509444,36,None],options=None,routeAlignment='R',routeNumber=43,routeSuffixCode=None)
print response
I used this code below to find the methods in the service along with the parameters they require:
for service in client.wsdl.services:
for port in service.ports:
methods = port.methods.values()
for method in methods:
print(method.name)
for part in method.soap.input.body.parts:
part_type = part.type
if(not part_type):
part_type = part.element[0]
print(' ' + str(part.name) + ': ' + str(part_type))
o = client.factory.create(part_type)
print(' ' + str(o))
And I used this code to get more details on the paramters for the method I am trying to call:
method = client.wsdl.services[0].ports[0].methods["getPostmileForPoint"]
params = method.binding.input.param_defs(method)
print params
UPDATE:
I found a javascript function used on a webpage that calls the web service with the input parameters for the method I want to use. I am now wondering how I can translate this into python using suds (I only included the code from the function that I think is needed, the rest of it does stuff with adding the results to the webpage):
function getPostmile()
{
var outputDiv = document.getElementById('latLongResult');
var popupHtml = null;
var req = new revPMRequest();
var pt = new lrspoint();
pt.x = parseFloat(document.InputCoordinates.InputX.value);
pt.y = parseFloat(document.InputCoordinates.InputY.value);
pt.spatialReferenceID=4269;//NAD83
var opt = new revPMOptions();
opt.toleranceDegrees=0.01703; //~1 mile
req.inputPoint = pt;
req.options = opt;
var ws = new GISWebServiceSoapImp();
var res = ws.getPostmileForPoint(req);
var pm = res.outputPostmile;
I'm stuck having to use a legacy web service that takes a username and password and returns xml indicating if the credentials are valid. The legacy service requires me to pass an http header with the request that contains the user's password. So, to get it to work, I had to hard code the password (actualUserPassword) in the header as follows:
var urlToCall = "https://ourlegacyauthserver/auth?uid=" + username);
var result = HTTP.call("GET", urlToCall, {headers:{"token:appname:127.0.0.1:actualUserPassword":""}});
This works when I hard code the proper password for the user on the server, but what I really need to do is build that header dynamically using the password variable, like this:
var urlToCall = "https://ourlegacyauthserver/auth?uid=" + username);
var headerString = "token:appname:127.0.0.1:" + password;
var result = HTTP.call("GET", urlToCall, {headers: {headerString: ""}});
When I do this, the auth server does not see the header coming in. What is wrong? I'm just trying to replace the hard coded string: "token:appname:127.0.0.1:actualUserPassword" with a string variable I built using the actual password passed in.
It's a javascript Object key problem. Try this instead:
var urlToCall = "https://ourlegacyauthserver/auth?uid=" + username);
var headerString = "token:appname:127.0.0.1:" + password;
var headerObject = {};
headerObject[headerString] = "";
var result = HTTP.call("GET", urlToCall, {headers: headerObject});
I am currently working on some javascript that can be included in the header of surveys that use TrueSample, and will dynamically generate and fire Webservice calls for the survey. One of the requirements of Truesample is that after every page, it is sent the amount of time spend on that page, as well as some other arbitrary information generated in the beginning of the survey. I am trying to automate the every page web service call, so that I don't have to have hundreds of web services in every survey.
I am pretty far along, and have found some cool tricks to make this all work, but I am struggling with firing the webservice using javascript.
Here is what I have so far:
Qualtrics.SurveyEngine.addOnload(function()
{
var pageStart = new Date();
var beginning = pageStart.getTime();
// Necessary Variables
var account-id = parseInt("${e://Field/account-id}");
var passcode = parseInt("${e://Field/passcode}");
var survey-country = parseInt("${e://Field/survey-country}");
var end-client-id = parseInt("${e://Field/end-client-id}");
var page-exposure-duration;
var page-id = parseInt("${e://Field/pageID}");
var platform-id = parseInt("${e://Field/platform-id}");
var respondent-id = parseInt("${e://Field/respondent-id}");
var response-id = parseInt("${e://Field/response-id}");
var source-id = parseInt("${e://Field/source-id}");
var survey-id = parseInt("${e://Field/survey-id}");
var api-version = parseInt("${e://Field/api-version}");
//End Variables
var that = this;
that.hideNextButton();
var para = document.createElement("footnote");
var test = document.getElementById("Buttons");
var node = document.createElement('input');
var next = document.getElementById("NextButton");
node.id = "tsButton";
node.type = "button";
node.name = "tsButton";
node.value = " >> ";
node.onclick = function trueSample(){
var pageEnd = new Date();
var end = pageEnd.getTime();
var time = end - beginning;
window.alert(pageID + ", time spent on page = " + time);
Qualtrics.SurveyEngine.setEmbeddedData("pageID", pageID + 1);
new Ajax.Request('webserviceURL', {
parameters: {
account-id: account-id,
passcode: passcode,
survey-country: surveycountry,
end-client-id: end-client-id,
page-exposure-duration: time,
page-id: page-id,
platform-id: platform-id,
respondent-id: respondent-id,
response-id: response-id,
source-id: source-id,
survey-id: survey-id,
api-version: api-version}
});
that.clickNextButton();
};
para.appendChild(node);
test.insertBefore(para, next);
});
Does anyone have experience with firing webservice calls out of Javascript? And if so, do you have any ideas on how to finalize the ajax request and make it work? Or is there another(potentially better) method that I could use for these calls that would work? I understand that there is information on this on Stack Overflow, but I am having a hard time understanding how specific use cases apply to mine.
Also, please note that, while I would love to use JQuery, I am limited to vanilla Javascript, and Prototype.JS.
Using Traditional javascript XmlHttpRequest you can make an AJAX call. For a Webservice, we need couple of HTTP Headers. Like: SOAPAction, Content-Type, Accept. The values for these headers MUST be like below:
SOAPAction:""
Content-Type:text/xml
Accept:text/xml
So, additionally, your code should look something like this for making an AJAX call to the Webservice:
//Get XML Request Object
var request = new XMLHttpRequest();
// Define the URL
var url="http://your.end.point.url?wsdl";
//Define HTTP Method. Always POST for a Webservice
request.open("POST", url, true); // Remember that all the Webservice calls should be POST
//Setting Request Headers
request.setRequestHeader("SOAPAction", "\"\"");//Not sure of the escape sequence. The value should be "".
request.setRequestHeader("Accept","text/xml");
request.setRequestHeader("Content-Type","text/xml");
//Make your AJAX call
request.send(soap); // where soap is you SOAP Request Payload.
Parsing the response:
request.onreadystatechange=stateChanged;
function stateChanged()
{
if (request.status==200)
{
// Success. Parse the SOAP Response
}
if(request.status==500)
{
//Failure. Handle the SOAP Fault
}
}
I'm trying to use VersionOne JS SDK in Node.js (https://github.com/versionone/VersionOne.SDK.JavaScript). I'm simply downloading whole library, placing it alongside with my js file:
var v1 = require('./v1sdk/v1sdk.js');
var V1Server = v1.V1Server;
console.log(v1);
console.log(V1Server);
Unfortunately something seems wrong, the output I get after calling
node app.js
is:
{}
undefined
Can somebody point me what I'm doing wrong or check whether the sdk is valid.
Thanks!
You can see in the source where V1Server is defined, that it's a class with a constructor. So you need to use the new keyword and pass the arguments for your environment.
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/client.coffee#L37
var server = new V1Server('cloud'); //and more if you need
Can you try the sample.js script that I just updated from here:
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/sample.js
It pulls in the two modules like this:
var V1Meta = require('./v1meta').V1Meta;
var V1Server = require('./client').V1Server;
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new V1Server(hostname, instance, username, password, port, protocol);
var v1 = new V1Meta(server);
v1.query({
from: "Member",
where: {
IsSelf: 'true'
},
select: ['Email', 'Username', 'ID'],
success: function(result) {
console.log(result.Email);
console.log(result.Username);
console.log(result.ID);
},
error: function(err) { // NOTE: this is not working correctly yet, not called...
console.log(err);
}
});
You might have to get the latest and build the JS from CoffeeScript.
I think I was trying out "browserify" last year and that's how the "v1sdk.js" file got generated. But I'm not sure if that's the best approach if you're using node. It's probably better just to do it the way the sample.js file is doing it.
However, I did also check in a change to v1sdk.coffee which property exports the two other modules, just as a convenience. With that, you can look at sample2.js. The only different part there is this, which is more like you were trying to do with your example:
var v1sdk = require('./v1sdk');
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new v1sdk.V1Server(hostname, instance, username, password, port, protocol);
var v1 = new v1sdk.V1Meta(server);