I keep getting results as false when running my POST & PUT & DELETE methods.
When I used POSTMAN I get 200 OK but my response returns as false?
Here's what I get when i use POST:
https://i.stack.imgur.com/fytB1.png
Here's what I get when i use UPDATE:
https://i.stack.imgur.com/y3vdv.png
Here's what I get when i use DELETE:
https://i.stack.imgur.com/hSNjy.png
Here is my controller code:
[HttpPost("AddNewOwner")]
public Boolean AddNewOwner(Owner theOwner)
{
DBConnect objDB = new DBConnect();
string strSQL = "INSERT INTO HomeOwnership_T (HomeOwnerID, FirstName, LastName, Address, City, State, ZipCode, TelNo, Email, BlockNo, LotNo, SaleDate, SalePrice, IsSold) " +
"VALUES ('" + theOwner.HomeOwnerID + "', '" + theOwner.FirstName + "', '" +
theOwner.LastName + "', '" + theOwner.Address + "', '" + theOwner.City +
"', '" + theOwner.State + "', '" + theOwner.ZipCode + "', '" + theOwner.TelNo + "', '"
+ theOwner.Email + "', '" + theOwner.BlockNo + "', '" + theOwner.LotNo + "', '"
+ theOwner.SaleDate + "', '" + theOwner.SalePrice + "', '" + theOwner.IsSold + "')";
//Execute the INSERT statement in the database
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
string command = "SELECT TOP 1 HomeOwnerID FROM HomeOwnership_T ORDER BY DESC";
DataSet ds = objDB.GetDataSet(command);
Tax taxInfo;
foreach (DataRow record in ds.Tables[0].Rows)
{
taxInfo = new Tax();
taxInfo.HomeOwnerID = int.Parse(record["HomeOwnerID"].ToString());
string strSQL2 = "INSERT INTO TaxInfo_T (AccessedVal, LandVal, AdditionalVal, TaxRate, TaxPerYear, RealEstateTax, HomeOwnerID)"
+ "VALUES (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '" + taxInfo.HomeOwnerID + "')";
objDB.DoUpdate(strSQL2);
}
return true;
}
else
{
return false;
}
}
[HttpPut]
public Boolean Update(Owner theOwner)
{
DBConnect objDB = new DBConnect();
HomeTax owner = new HomeTax();
string strSQL = "UPDATE HomeOwnership_T SET HomeOwnerID = " + theOwner.HomeOwnerID +
", FirstName = '" + theOwner.FirstName + "', LastName: '" + theOwner.LastName +
"', Address = '" + theOwner.Address + "', City = '" + theOwner.City +
"', City = '" + theOwner.City + "', State = '" + theOwner.State +
"', ZipCode = '" + theOwner.ZipCode + "', TelNo = '" + theOwner.TelNo +
"', Email = '" + theOwner.Email + "', BlockNo = " + theOwner.BlockNo +
", LotNo = " + theOwner.LotNo + "', SaleDate = '" + theOwner.SaleDate +
"', SalePrice = " + theOwner.SalePrice + ", IsSold = '" + theOwner.IsSold +
" WHERE HomeOwnerID = " + theOwner.HomeOwnerID;
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
return true;
}
else
{
return false;
}
}
[HttpDelete("{id}")]
public Boolean Delete(int id)
{
DBConnect objDB = new DBConnect();
string strSQL = "DELETE * FROM HomeOwnership_T INNER JOIN TaxInfo_T " +
"ON HomeOwnership_T.HomeOwnerID = TaxInfo_T.HomeOwnerID WHERE HomeOwnerID = " + id;
int result = objDB.DoUpdate(strSQL);
if(result > 0)
{
return true;
}
else
{
return false;
}
}
Here are my ajax calls:
$(document).on("click", "#btnAddHomeOwner", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/AddNewOwner";
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("btnAddHomeOwner selected");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
// Make an AJAX request to get a home and store the response in the appropriate div.
$.ajax({
type: "POST",
url: strURL,
contentType: "application/json", // set the data type sent to the Web Service.
dataType: "json", // set the data type expected from the Web Service.
data: strInput, // send an empty JSON object (no input required).
success: function (data) { // set callback function used to update the page/
console.log(data);
var result = data;
if (result == true)
$("#msg").text("The record was successfully added to the database.");
else
$("#msg").text("The record was not added to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnStoreHomeOwner click event
$(document).on("click", "#btnDelete", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/";
var param = $("#txtHomeOwnerID").val();
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Delete button selected.");
$.ajax({
type: "DELETE",
url: strURL + param,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{5}",
success: function (data) {
console.log(data);
var result = data;
if (result == true) {
$("#msg").text("The record with HomeOwnerID: " + param + " was deleted.");
alert("Deleted!");
}
else {
$("#msg").text("The record with HomeOwnerID: " + param + " was not deleted.");
alert("Not Deleted");
}
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnDelete click event
$(document).on("click", "#btnUpdateAll", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/Update";
// Clear the divs contents.
//$("#display").html("");
//$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Update home owner button selected.");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
//Make an AJAX request to get a home owner and display the response in the appropriate div
$.ajax({
type: "PUT",
url: strURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: strInput,
success: function (data) {
console.log(data);
var owner = data;
$("#display").html("<hr><p>".concat("HomeOwnerID: ", owner.HomeOwnerID,
"<br>FirstName: ", owner.FirstName, "<br>LastName: ", owner.LastName,
"<br>Address: ", owner.Address, "<br>City: ", owner.City,
"<br>State: ", owner.State, "<br>ZipCode: ", owner.ZipCode,
"<br>Telephone Number: ", owner.TelNo, "<br>Email: ", owner.Email,
"<br>Block Number: ", owner.BlockNo, "<br>Lot Number: ", owner.LotNo,
"<br>Date of Sale: ", owner.SaleDate, "<br>Sale Price: $", owner.SalePrice,
"<br>Sold Status: ", owner.IsSold, "<br>Accessed Value: $", owner.AccessedVal,
"<br>Land Value: $", owner.LandVal, "<br>Additional Value: $", owner.AdditionalVal,
"<br>Tax Rate: $", owner.TaxRate, "<br>Tax Per Year: $", owner.TaxPerYear,
"<br>Real Estate Tax: $", owner.RealEstateTax, "</p >"));
if (owner == true)
$("#updateResult").text("The record was successfully updated to the database.");
else
$("#updateResult").text("The record was not updated to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); //end of btnUpdate
check your sql string when you set the homeownerid is it suppose to be "SET hoID = '" + theOwner.HomeOwnerID + "', ownerName = '" + theOwner.ownerName + "'....etc
Here is my code:
$.ajax({
type: "POST",
url: "localhost/api.php",
data: {id:user_id},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
if (obj.msg == "1")
{
$.each(obj.userList, function(i,value) {
var jArray = <?php echo json_encode($groupData ); ?>;
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + '>' + jArray[i].Group_Name + '</option>');
}
var html ="<tr>"+
"<td>"+value['id']+"</td>"+
"<td>"+value['groupID']+"</td>"+
"<td><select name='Group[]''>"+list+ "</select></td>";
$('table#List tbody').append(html);
});
}
},
alert('Error');
});
I'm dynamically constructing the html based on the ajax response.
In the code snippet >
var jArray = <?php echo json_encode($groupData ); ?>;
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + '>' + jArray[i].Group_Name + '</option>');
}
$groupData is a PHP array. So I'm converting it into a Javascript array and using this jArray to generate the "option" and push the resulting list array. I'm appending this list array into the html and this much is working perfectly. Now there are 6 groups and one of them is already set for a particular user in the database. So currently none of the "option" has selected attribute. I'm having trouble in comparing jArray[i].Group_Id with value['groupID']. What I want to achieve is I want to compare jArray[i].Group_Id with value['groupID'] and if they are equal then set a selected attribute to that particular . How do I write an if statement for the comparison inside the "option" ?
Here's some example code showing this working:
const jArray = [{Group_Id: 1, Group_Name: 'One'}, {Group_Id: 2, Group_Name: 'Two'}];
const userList = [{id: 'user1', groupID: 2}, {id: 'user2', groupID: 2}, {id: 'user3', groupID: 1}];
$.each(userList, function(x,value) {
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + (jArray[i].Group_Id == value.groupID ? ' selected ' : '') + '>' + jArray[i].Group_Name + '</option>');
}
var html ="<tr>"+
"<td>"+value.id+"</td>"+
"<td>"+value.groupID+"</td>"+
"<td><select name='Group[]''>"+list+ "</select></td>";
$('table#List tbody').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="List">
<tbody></tbody>
</table>
The important piece missing from your code being:
(jArray[i].Group_Id == value.groupID ? ' selected ' : '')
alert(name);
The output should be 'pikkertonnode_1334187978'
The 2nd ' is to far away from the end of the text.
This is my code:
var name;
var namehelp;
// For individually tab
function refresher() {
var url = 'output.php?string=' + choice[0].innerText;
var split = url.split("[new]");
var series = "[" ;
for (var i = 1; i < split.length; i++)
{
namehelp = split[i];
var splithelp = namehelp.split(")");
namehelp = splithelp[1];
alert(namehelp);
name = "'" + namehelp + "'";
alert(name);
series = series + "{ name : " + name + " , data : data[" + (i-1) + "] }," ;
}
var url is like:
http://172.23.133.61:60080/pages/select-multiple-start/output.php?string=[new]frequency%20(Monitor%201)pikkertonnode_1334156507[new]loadvalue%20(Monitor%201)pikkertonnode_1334156507
May be your variable contains unwanted spaces.Use the following to remove the spaces
alert(name.replace(/\s/g, ""));
Is this the optimal way to load form data into a string and then to localStorage ?
I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code?
<script>
var sg = document.getElementById("selectedGateway");
var sd = document.getElementById("selectedDestination");
var dm = document.getElementById("departureMonth");
var dd = document.getElementById("departureDay");
var dy = document.getElementById("departureYear");
var rm = document.getElementById("returnMonth");
var rd = document.getElementById("returnDay");
var ry = document.getElementById("returnYear");
var ad = document.getElementById("adults");
var ch = document.getElementById("option2");
$("#searchRequestForm").submit(function() {
var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
localStorage.setItem("string", string);
});
</script>
I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript.
Demo: http://jsfiddle.net/grTWc/1/
var data = {
sg: $("#selectedGateway").val(),
sd: $("#selectedDestination").val()
// items here
};
localStorage.setItem("mykey", JSON.stringify(data));
To retrieve the data:
var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);
See Also:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
http://api.jquery.com/jQuery.parseJSON/
I prefer a table driven approach so there is no repeated code (DRY):
var ids = [
"selectedGateway", "From: ",
"selectedDestination", "\nTo :",
"departureMonth", "\nDeparture: ",
"departureDay", "/",
"departureYear", "/",
"returnMonth", " \nReturn: ",
"returnDay", "/",
"returnYear", "/",
"adults", " \nNumber of adults: ",
"option2", " \nNumber of children: "];
var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);
You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string.
function form(id) {
return document.getElementById(id).value;
}
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+".*"}}