I am querying a Neo4j database using javascript and the REST API to search for a node by name. Upon submitting the query the firebug console shows an error 400 "Bad Request" with the following:
"message" : "You have to provide the 'query' parameter.",
"exception" : "BadInputException",
Below is the function I am using to submit the query. When alerting on "search_query" the syntax appears to be correct and the stringified "queryObject" is valid JSON. Thank you helping me understand why this is happening and how to fix it.
~~~~
Note: Just got this to work by using:
data:{
"query":"start n = node(*) WHERE n.name =~ '" + search_name + ".*' return n order by n.name asc",
"params":{}
},
~~~~
<script>
function name_search()
{
var queryObject = new Object; //declare object to hold query and parameters
var search_name = document.getElementById("name_search").value; //get node name search term from user input
search_name = "'"+search_name+".*'"; //append ".*" to search on Regular Expression
//alert("search: " + search_name);
search_query = 'start n = node(*) WHERE n.name =~ ' + search_name + ' return n order by n.name asc'; //create query
queryObject.query = search_query; //insert query string in queryObject
queryObject.params = {}; //empty object = no query parameters
alert(JSON.stringify(queryObject));
var restServerURL = "http://localhost:7474/db/data"; //local copy on windows machine
$.ajax({
type:"POST",
url: restServerURL + "/cypher",
accepts: "application/json",
dataType:"json",
data:JSON.stringify(queryObject), //convert queryObject to JSON for inserting into database
success: function(data, xhr, textStatus){
//process query results
$('#query_results').empty(); //clear div that will contain results
var length = data.data.length; //capture number nodes returned
//alert("number of nodes: " + length);
$('#query_results').append($('<p>').html('number of nodes: ' + length + '<br />'));
for (var u = 0; u < length; u++){
var num_props = Object.keys(data.data[u][0].data).length;//get number of node properties from length of data.data.data child property in JSON
var node_num = data.data[u][0].self;//get node number from data.data.self and
node_num = node_num.replace(restServerURL+"/node/","");//strip restServerURL+"/node/" from result
//alert("Node "+ node_num + " has: "+ num_props + " properties");
$('#query_results').append($('<p>').html('Node '+ node_num + ' has: '+ num_props + ' properties' + '<br />'));
for (var v = 0; v < num_props; v++){
var prop = (Object.keys(data.data[u][0].data))[v];//get property name key
var val = data.data[u][0].data[prop]; //use property name to get value
//alert("prop: " + prop +" value: " + val);
$('#query_results').append($('<p style="text-indent: 1em;">').html('prop: ' + prop +' value: ' + val + '<br />'));
}
};
},
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}//end of search for node by name
</script>
datatype json does the conversion itself, so you have to provide the object there. As you noticed as well.
I would strongly recommend that you use a n.name =~{search_name} parameter in your query and then just pass
{query: ...,params: { search_name: search_name+".*"}}
Related
I am using node.js to develop firebase cloud functions. I need to connect to google maps api to get the distance between two Latlng points. I am making an https get request and receiving a response with a JSon object. The problem is that the received object is empty with a status: INVALID_REQUEST in most cases. However, in some rare cases it returns the desired value. I have tried the path and host of my request on the browser and the json object is retrieved successfully there. I do not know exactly where my problem is. Is it in the callback? the path? something else?
I am giving my code and the output of it.
My code is :
function getStatusCode(options, callback) {
https.get(options, function(http_res) {
var data = "";
console.log('inside the https request');
http_res.on("data", function (chunk) {
data += chunk;
console.log("I am reading the data");
console.log(data);
// callback(http_res.statusCode, data)
});
http_res.on("end", function () {
console.log("I am in the ON_END listener");
console.log('data contains: >> ' + data + ' I am in the ONEND listener')
callback(http_res.statusCode, data)
});
});
}
and I am calling it as follows:
console.log('startingPoints ' + startingPoints);
console.log('lat and lng are: '+lat+" , "+lng);
var options = {
host: 'maps.googleapis.com',
path: '/maps/api/distancematrix/json?units=imperial&origins='+startingPoints+'&destinations='+lat+','+lng+'&key=MY_GOOGLEMAPSAPI_KEY',
method: get
};
getStatusCode(options, function(statusCode, data){
console.log('The status code is : '+statusCode);
console.log('and data is : '+data);
// parsing json object:
jData = JSON.parse(data);
rows = jData.rows;
console.log('the length of the rows array is >> ' + rows.length + ', the length of the techs array is >> ' + techs.length);
min = -1;
for(var i = 0; i < rows.length; i++){
console.log('the array of techs + the equivalent values of the array of row >>' + techs[i] + ' and ' + rows[i].elements[0].distance.value);
if( min < 0 || rows[i].elements[0].distance.value < rows[min].elements[0].distance.value)
min = i;
console.log('minimum distance tech in the loop; the id is >> ' + techs[min] + ", and the distance is >> " + rows[min].elements[0].distance.value);
}
console.log('the min value before return is >> ' + min);
and the retrieved json object is:
{
"destination_addresses" : [],
"origin_addresses" : [],
"rows" : [],
"status" : "INVALID_REQUEST"
}
any idea please,,
I have found a solution. precisely, found my problem. The problem was not within google-map-api. It was with assignment of the starting_points variable.
This is my response from AJAX call
{"screen":[{"screen_name":"SCR1","screen_id":"1"},{"screen_name":"SCR2","screen_id":"2"},{"screen_name":"SCR3","screen_id":"3"},{"screen_name":"SCR4","screen_id":"4"},{"screen_name":"SCR5","screen_id":"5"},{"screen_name":"BIGSCR","screen_id":"6"}]}
success: function(response) {
var jsondata = JSON.stringify(response);
console.log(jsondata);
var html = '';
for (var i = 0; i < jsondata.screen.length; i++) {
var screenName = jsondata.screen[i].screen_name;
var screenId = jsondata.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
}
But I keep on getting
Uncaught TypeError: Cannot read property 'length' of undefined at for loop
Try this: It Works. As smooth as silk: (See comment for explanation)
<select id="SCname"></select>
<script>
$.ajax({
dataType: 'json',
//This JSON datatype returns a json encoded response
url:"api/test.php",
//This is the URL From where you fetch the JSON Data
success: function(response){
//Since the response array object has a single array element "screen", we make it myArray
myArray = response["screen"];
console.log(myArray);
//We get six Objects in myArray.
//Thsese are Arrays of your six screens . Now Using Loops
var html = '';
for (var i = 0; i < myArray.length; i++) {
// Each element is inside DOuble Array like: myArray[0]["screen_name"]
var screenName = myArray[i]["screen_name"];
var screenId = myArray[i]["screen_id"];
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
//Check your console ouput
console.log(html);
}
});
</script>
JSON.stringify(object) returns a string. You want a JSON.parse(string) – which returns an object. Alternatively, if your response is already an object, then you don't have to parse it at all:
success: function(jsonData) {
var html = '';
for (var i = 0; i < jsonData.screen.length; i++) {
var screenName = jsonData.screen[i].screen_name;
var screenId = jsonData.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
You don't want to stringifybut to parse. Correct it must be:
var jsondata = JSON.parse(response);
But keep in mind that jQuery possibly is already parsing the JSON for you.
We were provided function getQueryStringVariableByItemID for our project and are using function getData to use a web service for a game's details from a games table. We believe the getData part is working fine since we use a similar POST on another page. Is getQueryStringVariableByItemID not properly grabbing the query string?
We call getData with the body tag of html as onload="getData()". Many thanks in advance!
Code:
<script type="text/javascript">
function getQueryStringVariableByItemID(ItemID) {
//use this function by passing it the name of the variable in the query
//string your are looking for. For example, if I had the query string
//"...?id=1" then I could pass the name "id" to this procedure to retrieve
//the value of the id variable from the querystring, in this case "1".
ItemID = ItemID.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + ItemID + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getData() {
var ItemID = getQueryStringVariableByItemID(ItemID)
$.ajax({
type: "POST",
url: "./WebServiceTry.asmx/GetGameDetails",
data: "{'ItemID': '" + escape(ItemID) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.d;
$('#output').empty();
$.each(data, function (index, item) {
var Title = item.Title
var Price = "$" + item.Price
var Year = "Year: " + item.Year
var Developer = "Developer: " + item.Developer
var Platform = "Platform: " + item.Platform
$('#output').append('<li>' + Title + '</li>');
$('#output').append('<li>' + Price + '</li>');
$('#output').append('<li>' + Year + '</li>');
$('#output').append('<li>' + Developer + '</li>');
$('#output').append('<li>' + Platform + '</li>');
$('#output').listview('refresh');
});
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</script>
The ItemID you are passing in the getData(while calling inside the getData) should be undefined because the function doesnt have that variable.Pass a valid id and it will work fine
I am trying to access the value of IDs[i] correctly within a function inside a loop. I have tried the following.
This method logs IDs as a string I think. I try to access it with index but it comes out undefined. See the console.log inside simpleWithAttrPrice function call.
for(i=0; i<IDs.length; i++)
{
console.log("Outside of function Vendor is " + IDs[i]);//logs correctly
var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
simpleWithAttrPrice(optionSelectionArray, function(data) {
//var vendor = IDs[i];
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + IDs);//"5,3"
console.log("Vendor is " + IDs[i]);//undefined
$j('.details'+IDs[i]+ ' .priceBlock').empty();
$j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}
I also tried passing ID's into the callback function but it logs "success" (literally)
for(i=0; i<IDs.length; i++)
{
//var vendor = IDs[i];
var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
simpleWithAttrPrice(optionSelectionArray, function(data, IDs) {
//var vendor = IDs[i];
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + IDs);//logs ID's as "success" ??
$j('.details'+IDs[i]+ ' .priceBlock').empty();
$j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}
Lastly, I've also tried the following but it appends the price to the same block.
for(i=0; i<IDs.length; i++)
{
var vendor = IDs[i];
var optionSelectionArray = currentlySelectedAttributes(vendor);
simpleWithAttrPrice(optionSelectionArray, function(data) {
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + vendor); //only logs this once.
$j('.details'+vendor+ ' .priceBlock').empty();//If I take this away, appends both prices to same block
$j('.details'+vendor+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}
How do I access the array IDs correctly within the callback function?
#Toby Allen Thanks! Your right about that link. For reference this works:
function sendRequest(i) {
var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
simpleWithAttrPrice(optionSelectionArray, function(data) {
//var vendor = IDs[i];
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + IDs);//"5,3"
console.log("Vendor is " + IDs[i]);//undefined
$j('.details'+IDs[i]+ ' .priceBlock').empty();
$j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}//end sendRequest
for(i=0; i<IDs.length; i++)
{
sendRequest(i);
}
I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}