Can I query the neo4j database with Javascript? - javascript

I have created a geohash neo4j database for NYC Taxi data.
Now the next step is to visualize it within a map, for that i choosed Leaflet as a Javascript library.
with static data i can plot geohash data in Leaflet:
but now i want to query that data from the neo4j database and render it.
so is it possible to do that or only with a server side scripting language(node.js,php...) ?
Update
i found a simlair question here , the solution is to query the database with ajax however it dosen't work for me and i get "error" in the console:
var body = JSON.stringify({
statements: [{
statement: 'MATCH (n) RETURN count(n)'
}]
});
$.ajax({
url: "http://localhost:7474",
type: "POST",
data: body,
contentType: "application/json"
})
.done(function(result){
console.log(result);
})
.fail(function(error){
console.log(error.statusText);
});

It's possible to query Neo4j from client-side Javascript with Neo4j Driver for JavaScript.
I have used this in a couple of projects.
You can either download the driver and include in your HTML file like:
<script src="lib/browser/neo4j-web.min.js"></script>
Or just use the CDN link like:
<script src="https://unpkg.com/neo4j-driver#X.Y.Z/lib/browser/neo4j-web.min.js"></script>

I find the solution:
first the url for the database is : "http://localhost:7474/db/data/transaction/commit" and not "http://localhost:7474".
then after changing that i got an unauthorized error in console , that means i need to add my user/password to my ajax call, this is done by a function called beforeSend like this:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("neo4j"+ ":" + "your_neo4j_password"));
}}
so the final Ajax Solution is :
$.ajax({
url: "http://localhost:7474/db/data/transaction/commit",
type: "POST",
data: body,
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("neo4j"+ ":" + "password"));
}}
)
.done(function(result){
console.log(result);
})
.fail(function(error){
console.log(error.statusText);
});

Rajendra Kadam's answer is correct.
First you need to install neo4j-driver by:
npm install neo4j-driver
in a directory probably one level higher than the web/ directory of your node.js server.
Then you need to put the neo4j-web.min.js into the web/ directory, where your client-side JavaScript can load.
Then you add the line in your HTML:
<script src="js/neo4j-web.min.js"></script>
The file neo4j-web.min.js is located in node_modules/neo4j-driver/lib/browser/.
Then in your client-side JavaScript, put:
var driver = neo4j.driver(
'neo4j://localhost',
neo4j.auth.basic('neo4j', 'password') );
Then you have successfully opened the driver. (You may need to set your password correctly or you'll get an authentication error.)
Note that you DON'T need this line on your client-side JavaScript:
var neo4j = require('neo4j-driver');
because it is for server-side node.js.

Related

Data is not ready when retrieving session parameter from the server using AJAX

I'm building an application using laravel. I have a controller which returns a session parameter from the server.
I'm retrieving this parameter using an ajax request from a view blade as follow:
var url = CMS_URL + 'GetSystemMode/';
$.ajax({
url: url,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
console.log("data: " + data);
}
});
The code running on the server side is:
Route::get('/GetSystemMode', function () {
return Session::get('systemMode');
});
In localhost, I'm getting the right "data" and the code works as a charm, but in production, "data" is always empty.
It's like the success method is executed before the data is yet retrieved from the server side.
This issue took to much time from me, and I don't have any idea how to fix it.
Thanks.
Our production environment was at the appEngine, so due to the server restirctions, it wasn't allowed to save the sessions on files as was done on localhost. So the problem was actually that the server is not saving the sessions at all and therefor I'm getting empty data.
I solved it by installing redis and saving the sessions over it.

How to get all the repositories for a particular user?

I am trying the extract the various repository names for a particular user and populate a combobox on a html page. I am able to extract only one repository name. How can I get all the names? The code I have so far:
$.ajax({
url:"https://api.bitbucket.org/2.0/repositories/abc",
username: "palld#bdbd.in",
password: "abcdef123456",
success: function(data){
console.log(data);
},
error: function(){
console.log("Connection did not go through");
},
type: 'GET'
});
Writing similar code in Java and python worked and I was able to see all the repository names. Any help would be appreciated.
The result is as below:
Edit:
It appears that Bitbucket will send you some data even when you are not authenticated to their API. I suspect that there is no authentication request sent to you by the API and jQuery simply does not send the username and password when not asked for.
This code explicitly send the authentication data to the API:
var reposUsername = "OWNER_OF_REPOS";
var authUsername = "YOUR_USERNAME";
var authPassword = "YOUR_PASSWORD";
$.ajax({
url:"https://api.bitbucket.org/2.0/repositories/" + reposUsername,
success: function(data){
console.log(data);
},
error: function(){
console.log("Connection did not go through");
},
type: 'GET',
headers: {
'Authorization': "Basic " + btoa(authUsername + ":" + authPassword)
}
});
(I'm 100% sure that this code works as I've tested it a few minutes ago with my own Bitbucket account).
Note: please be aware that storing your credentials in the code is something you should not do, so think twice before you release your code/application the the public.
Obsolete answer:
Just look at the documentation Bitbucket provides to you (although, the example response looks kind of weird).
Assuming your data object is already a JSON parsed object, you should be able to access your respositiories like this (Edit: code adjusted the the provided screenshot):
data.values
Parse the JSON response. If it works from Python or Java then it must be something to do with the way you are handling the response in JavaScript. Perhaps you are not parsing it, which you need to do to convert it into a proper JSON object containing all the elements you want.
success: function(data){
console.log(JSON.parse(data));
},

How to build a file from binary string using javascript

I am trying to use BusinessObject RESTful API to download a generated (pdf or xls) document.
I am using the following request:
$.ajax({
url: server + "/biprws/raylight/v1/documents/" + documentId,
type: "GET",
contentType: "application/xml",
dataType: "text",
headers: {"X-SAP-LogonToken": token, "Accept": "application/pdf" },
success: function(mypdf) {
// some content to execute
}
});
I receive this data as a response:
%PDF-1.7
%äãÏÒ
5 0 obj
<</Length 6 0 R/Filter/FlateDecode>>
//data
//data
//data
%%EOF
I first assumed that it was a base64 content, so in order to allow the users to download the file, I added these lines in the success function:
var uriContent = "data:application/pdf; base64," + encodeURIComponent(mypdf);
var newWindow=window.open(uriContent, 'generated');
But all I have is an ERR_INVALID_URL, or a failure while opening the generated file when I remove "base64" from the uriContent.
Does anyone have any idea how I could use data response? I went here but it wasn't helful.
Thank you!
. bjorge .
Nothing much can be done from client-side i.e. JavaScript.
The server side coding has to be changed so that a url link is generated (pointing to the pdf file) and sent as part of the response. The user can download the pdf from the url link.
You cannot create file using javascript, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
To achieve your functionality, you can implement click event which target to your required file and it will ask about save that file to user.

Passing variables between Python and Javascript

Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.
Depending on which item is selected in the list, some of the checkboxes will become checked/unchecked.
In the back, you have Python code along with some SQLAlchemy.
The Javascript needs to identify the selected item in the list as usual, send it back to the Python module which will then use the variable in some SQLAlchemy to return a list of checkboxes which need to be checked i.e. "User selected 'Ford', so checkboxes 'Focus', 'Mondeo', 'Fiesta' need to be checked"
The issue Im having is that I cant seem to find a way to access the python modules from the Javascript without turning a div into a mini browser page and passing a url containing variables into it!
Does anyone have any ideas on how this should work?
Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy.
What I do is send AJAX request but with JSON request in the body instead of XML. Python CGI modules use standard json module to deserialize JSON into a dictionary.
JavaScript side looks like this:
function on_request_success(response) {
console.debug('response', response);
}
function on_request_error(r, text_status, error_thrown) {
console.debug('error', text_status + ", " + error_thrown + ":\n" + r.responseText);
}
var request = { ... };
jQuery.ajax({
url: 'http://host/whatever.cgi',
type: 'POST',
cache: false,
data: JSON.stringify(request),
contentType: 'application/json',
processData: false,
success: on_request_success,
error: on_request_error
});
And Python like this:
request = json.load(sys.stdin)
response = handle_request(request)
print("Content-Type: application/json", end="\n\n")
json.dump(response, sys.stdout, indent=2)
Note, it doesn't use Python cgi module, since the whole request is passed as JSON in the body.
python has a json module, which is a perfect fit for this scenario.
using a good old AJAX, with json as the data format will allow you to exchange data between javascript and your python module.
(unless your python module is running on the client side, but then i don't see how you could execute it from the browser...)
Ajax is a good way to pass variables between python and javascript.
Javascript:
param = {a:'hello', b: 'world', c: '!'}
$.ajax({
type: "post",
url: "scpi.py",
cache: false,
async: 'asynchronous',
dataType: 'html',
data: param,
success: function(data) {
console.log(data)
},
error: function(request, status, error){
console.log("Error: " + error)
}
})
Server.py: (You will need a three functions for this to work)
def do_POST(self):
if "scpi.py" in self.path:
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST'}
)
a = form['a'].value
b = form['b'].value
c = form['c'].value
content = myfunction(a, b, c)
self.respond(content)
def handle_http(self, data):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
print(data)
return bytes(str(data), 'UTF-8')
def respond(self, data):
response = self.handle_http(data)
print(data)
FYI: "myfunction(a, b, c,)" is a function from another python file, then return the data and passes to self.respond to send back to javascript

Getting "403 forbidden" error for ajax call web service in javascript?

i have a web service in a server, and i could connect web service from any browser in remote machine or host machine. But i couldn't access the web service using ajax call in javascript, showing 403 forbidden error. I ran the script from the server itself. Below is the code i used.
$('div').live('pageshow',function(event, ui){
var username = 'vijay';
var password = 'vijay';
var domain = '';
var windowsuser = false;
// var dataObject = {};
// dataObject = {Username:username,Password:password,Domain:domain,WindowsUser:windowsuser};
$('#login').click(function(){
$.ajax({
type: "POST",
url: "http://xxx.xxx.x.xx/Y_NAME/REST/session.aspx",
data: ({Username:username,Password:password,Domain:domain,WindowsUser:windowsuser}),
// contentType: "application/x-www-form-urlencoded",
cache: false,
dataType: "json",
timeout: 5000,
success: onSuccess
});
});
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
});
function onSuccess(data)
{
//$("#resultLog").html("Result: " + data);
console.log(data[0].Name);
}
Here , after calling web service, it has to return JSON data, but it didn't return anything. In firebug, inside the function onSucess, it shows 'null' for data.
Do i miss anything here? Y does it show '403' forbidden error? Since i'm calling the scripts from the server where the web service located, i think its not cross domain issue. I'm using this in Jquery mobile. Help needed. Thanks in advance.
Your web service is probably not script enabled using the attribute:
[System.Web.Script.Services.ScriptService]
do you build the web-service through wizard? i think the web service url should be "http://xxx.xxx.x.xx/Y_NAME/REST/xxx.asmx"
I figured it.. There was problem with URL.

Categories