Implement Search Functionality Node JS/MySQL - javascript

Having some trouble properly implementing a search filter by the Pokemon Name on my Node JS/MySQL DB. When I search I am getting "search/?key=undefined 404 (Not Found)" Any ideas? Here is my search route
router.get('/search', function(req, res){
var mysql = req.app.get('mysql');
var sql='SELECT pokemonname FROM pokemon WHERE pokemonname LIKE "%' + req.key.query + '%';
sql = mysql.pool.query(sql, function(error, results, fields) {
if(error) {
res.write(JSON.stringify(error));
res.end();
} else {
res.status(200);
res.end();
}
});
});
Here is my handlebars file to render the search bar/search button
<table id="table">
<thead>
<th>Pokemon Name </th>
<th>Evolution Level </th>
<th>Move Name </th>
</thead>
<input type="text" class="search form-control" id="searchinput" placeholder="Pokemon Name">
<input type="button" class="btn btn-primary" value="Search" onclick="getUsers({{id}})"/>
<br>
<tbody>
{{#each pokemon}}
<tr>
<td>{{pokemonname}}</td>
<td>{{evolutionlevel}}</td>
<td>{{movename}}</td>
<td><button onclick="deletePokemon({{id}})">Delete</td>
<td>Update</td>
</tr>
{{/each}}
</tbody>
And finally my search.js function in JQuery
function getUsers(searchinput){
$.ajax({
type: 'GET',
url: '/search/?key=' + searchinput,
success: function(result){
window.location.reload(true);
}
})
};
Thanks for the help

Most occurences of {{id}} are used inside #each loop suggesting id is property of pokemon object. Meanwhile your getUser({{id}}) is used outside of this loop leading to undefined passed to binding variable id. I think that you want to pass value of text input to your getUser function instead, hence your name of formal parameter e.g. searchinput. You could use {{input value=searchinput}} from Ember helper and then getUser({{searchinput}}) in your button. Also pay attenttion to encoding query params passed to called AJAX service.

Related

NodeJS Pass data from current page to another

I want to make a User management system in Node. I have a page where all users are listed in a table. After I press the edit button, it should go to the user page with all the information of that user. But I don't know how to pass the username into my Node function.
This is my table for the users. the Benutzerverwaltung_Mitareiter is the page where the information from the user is getting shown
<tbody>
<%for (var i = 0; i < users.length; i++) { %>
<tr>
<td><%=users[i].username%></td>
<td><%=users[i].admin%></td>
<td>
<form action="/users/Benutzerverwaltung_Mitarbeiter">
<button id="buttonAnzeigen"
type="submit"
name="username"
href=""
value="<%users[i].username%>"
data-toggle="tooltip"
title="Anzeigen">
<i class="fas fa-search"></i>
</button>
</form>
</td>
</tr>
<%}%>
</tbody>
I passed the username of the user into the value of the button.
And this is how I get the data for the table
router.route ('/Benutzerverwaltung_Mitarbeiter').get(function (req, res) {
const username = req.body;
User.find(function (err, users) {
if (err)
return res.send(err);
res.render('Benutzerverwaltung_Mitarbeiter',{
users: users || [],
});
});
});
If someone can help me to get the function, I would be very thankful!
I suggest you to use some template engine, like ejs or jade. This form, you can use res.render and send json information for view. For more details consult the engine docs and res.render doc too.

Angular it taking the old parameter when clicking button

I am trying to add a button which when clicked, calls a function which takes a parameter and sends it to my server. So far it looks like this:
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="interview in $ctrl.pendingInterviews">
<td>{{ interview.id }}</td>
<td><input type="submit" name="Submit" id="submit" ng-click="$ctrl.addParticipant();"></td>
</tr>
</tbody>
</table>
What I have in my angular component:
var participant={
username:"mama",
interviewId:$routeParams.interviewId
};
console.log(participant);
console.log(JSON.stringify(participant));
this.addParticipant = function saveParticipant() {
console.log("in partikip")
Interview.addParticipant(JSON.stringify(participant))
.then(
function (errResponse) {
console.error('Error while fetching pending interviews');
}
);
}
And what I have in my angular service:
function addParticipant(participant) {
console.log("Im here too");
console.log(participant + "asdasdsda");
var deferred = $q.defer();
$http.post('http://localhost:8080/interviewsupdateparticipant', participant)
.then(
function (response) {
deferred.resolve(response.data);
},
function (errResponse) {
console.error('Error while adding participant');
console.error(''+ participant.username + participant.interviewId)
deferred.reject(errResponse);
}
);
return deferred.promise;
}
The problem is that first when I go to my page, participant from the controller has the username set to mama and the interviewId set to undefined. When I click the submit button, instead of sending the id and the hardcoded username, it sends undefined and the hardcoded username. Why? Why doesn't it automatically get the interviewId?
The moment I click Submit, the id stays undefined for some reason and it only changes if I click again. Any ideas what the problem could be?
Many things that could solve this:
Try using ngHref instead of just href when you have variable part of your url
Try passing the interview.id as a parameter to your addParticipant() method instead of getting it via the $routeParams variable
You have an input type="submit" outside any form, and inside an <a> link, try changing that

How to populate table in Angular with JSON data from a web Service?

I have a link that displays JSON data when first name is found.
http://localhost:8080/application/names/find?firstname=f_name&LastName&Address&Status=
For Example: If I replace f_name with Tim I get this JSON response.
[{"f_name": "Tim","address": "Road","phone": "1234","status": "busy"}]
If I replace f_name with Sue I get this JSON response.
[{"f_name": "Sue","address": "Street","phone": "4321", "status": "available"}]
I want to be able to type Tim or Sue and get corresponding data. Here is what I have.
$http.get('http://localhost:8080/application/names/find?firstname=f_name&LastName&Address&Status=').
success(function(data) {
$scope.jsonData = data;
alert("Success");
}).
error(function(data) {
alert("Invalid URL");
});
$scope.results = [];
$scope.clickButton = function(enteredValue) {
$scope.items = $scope.jsonData;
angular.forEach($scope.items, function (item) {
if(item.f_name === enteredValue){
$scope.results.push({
name: enteredValue,
address: item.address,
number: item.phone,
status: item.status
});
}
})};
jsp
<table>
<tr>
<td><label>Name:</label></td>
<td>
<input id="fName" type="text" data-ng-model="enteredValue" />
<button data-ng-click='clickButton(enteredValue)'>Search</button>
</td>
</tr>
</table>
<table>
<tr data-ng-repeat="result in results" >
<td data-title="'ID'" >{{result.name}}</td>
<td data-title="'Name'">{{result.status}}</td>
<td data-title="'Status'">{{result.number}}</td>
<td data-title="'Start Date'" >{{result.date}} </td>
</tr>
</table>
I have been able to populate the dropdown successfully using then such as below.
$http.get('http://localhost:8080/application/countries').then(function(cdata)
{
$scope.countryData = cdata.data;
})
How do I initiate this search? Am I doing this the right way? Do I have to have a service for this?
looks like your server side function already been able to handle the query and return filtered result, if that's the case, what you need to do is just to cope with the request url when you send the search result. so, your clickButton function should be something like this:
$scope.clickButton = function(enteredValue){
//you may want to change logic here if you got other parameter need to be handled
var url = 'http://localhost:8080/application/names/find?firstname='+enteredValue+'&LastName&Address&Status=';
$http.get(url).success(function(data){
$scope.results = data;
});
}

Retrieving the id from Model to Controller in Angular JS

i have a table which is having the data retrieved from an api call from my memberController which is displayed inside ng-repeat and its working fine.
I need each Business Name of the member list to link to a separate page(edit_form.html) and display the id value, so that i can pass this along with the api call to get only this particular member detail. So i have added ng-init in my edit form page which calls the function test_funct when the page loads and retrieve each persons id there. unfortunately i am unable to retrieve the id value inside the function.
HTML Template
<div class="page" data-ng-controller="memberController">
<table>
<thead >
<tr>
<th>Business Name</th>
<th>Contact Name</th>
<th>Trade Balance</th>
<th>Cash Balance</th>
<th>Telephone</th>
<th>Account Number </th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="member in details | filter:search">
<td>{{member.businessname}}</td>
<td>{{member.person}}</td>
<td>{{member.balance_trade}}</td>
<td>{{member.balance_cash}}</td>
<td>{{member.telephone}}</td>
<td>{{member.accountnumber}}</td>
</tr>
</tbody>
</table>
</div>
I have the following controller
function memberController($scope, $http, $cookieStore) {
var token = $cookieStore.get('token');
var conId = $cookieStore.get('Cont_Id');
var exId = $cookieStore.get('ex_Id');
var member_list = "http://www.vb.com/functions/member_list.html?exchangeid=" + exId +
"&contactid=" + conId + "&token=" + token;
$http.get(member_list)
.success(function(response) {
$scope.details = response;
});
$scope.test_funct = function(id) {
$scope.myid = id;
alert($scope.myid); // getting undefined in alert, i expect the id(eg:1123)
}
}
edit_form.html
<div class="page" data-ng-controller="memberController">
<div class="panel-body" ng-init="test_funct()"></div>
</div>
Please assist me on this. Thanks in advance.
There are 2 things going on here.
First, you should separate controllers for the different views, so you end up with something like this:
<div class="page" data-ng-controller="memberController">
<table>
<!-- your whole big table here -->
</table>
</div>
And your editing form as follows:
<div class="page" data-ng-controller="editController">
<div class="panel-body"></div>
</div>
Notice that you now have two distinct controllers - your "editController" and your "memberController".
The second question then becomes, how do you transfer the selected ID from the list view ("memberController") to the edit view ("editController").
There are 2 ways of doing that.
First, you could use a service shared between the controller:
.factory('SelectedId',function() {
return {};
});
And then in your "member" view, you would set it upon clicking:
{{member.businessname}}
Notice the ng-click, which then needs a function in the memberController and the injected service:
.controller('memberController',function($scope,SelectedId) {
$scope.setId = function(id) {
SelectedId.id = id;
};
});
While the editController retrieves it:
.controller('editController',function($scope,SelectedId) {
$scope.id = SelectedId.id;
});
The above option works well, especially for complex things like shopping carts. If all you are doing is passing an ID, I would just stick it in the URL:
{{member.businessname}}
So that the ID is part of the URL. You then can retrieve it in the "editController":
.controller('editController',function($scope,$routeParams) {
$scope.id = $routeParams.member;
});
assuming you are using ng-route, and your route would look like:
$routeProvider.when('/pages/edit_form/:member',{templateUrl:'/route/to/template.html',controller:'editController'});
In html do that
<td>{{member.businessname}}</td>
...
In app.js or where you define route do that
.when('/edit/:memberid',
{
templateUrl:'partials/edit.html',
controller:'editController'
})
In controller you have to take this id by doing that
app.controller("editController",function($routeParams,$scope){
$scope.memberid= $routeParams.memberid;
//Now use this member id to fetch all data
});

KnockoutJS - Print iteration index as input name

I am trying to create my first KnockoutJS form view in combination with Spring MVC's #ModelAttribute binding.
Data is loaded over Ajax and populated with KnockoutJS
Data is added over KnockoutJS
Data is removed over Ajax and KnockoutJS
Data will be saved with an normal POST submit to Spring MVC controller.
To bind the form inputs to a Spring MVC controller, I need the iteration index from KnockoutJS. So I tried following:
But the values from my database are never bound like they are when I am bind them with data-bind='value: key'. Can you help me, finding the mistake?
JSP:
<form:form modelAttribute="configurationHelper" action="/saveConfigurationList.htm" method="POST" id="configuration-form" class="form-inline">
<tbody data-bind="foreach: configurations">
<tr>
<td>
// this is working
<input data-bind='value: key' class="form-control input-sm" type="text"/>
// this is not working
<input data-bind='attr:{value: key, name:configurationHelper.configurations[$index].key' class="form-control input-sm" type="text"/>
</td>
<td>
<a href='#' data-bind='click: $root.removeConfiguration' class="ordinary-tooltip" title='<spring:message code="general.delete"/>'>
<i class="fa fa-lg fa-trash-o "></i>
</a>
</td>
</tr>
</tbody>
</form:form>
ModelView:
function ConfigurationViewModel() {
var self = this;
self.configurations = ko.observableArray([]);
self.loadConfigurations = function() {
$.ajax({
type : "POST",
url : "/loadConfigurationList.htm",
success : function(response) {
var responseArray = JSON.parse(response);
var mappedConfigurations = $.map(responseArray.configurations, function(configuration) {
return new Configuration(configuration);
});
self.configurations(mappedConfigurations);
},
error : function(e) {
alert('Error: ' + e.status);
}
});
}
self.saveConfigurationList = function() {
$("#configuration-form").submit();
}
self.addConfiguration = function() {
self.configurations.push({
id: 0,
key: "",
value: "",
});
};
self.removeConfiguration = function(configuration) {
if(confirm(springMessageGeneralDeleteReally)){
$.ajax({
type : "POST",
url : "/deleteConfiguration.htm",
data: {"configurationId": configuration.id},
success : function(response) {
self.configurations.remove(configuration);
},
error : function(e) {
alert('Error: ' + e.status);
}
});
}
};
}
function Configuration(data) {
this.id = ko.observable(data.id);
this.key = ko.observable(data.key);
this.value = ko.observable(data.value);
}
Summary:
Knockout should only take care of binding the values (loaded with AJAX) to the inputs and display the correct input-name. (to bind the input-value back to the Spring MVC controller)
configurationHelper is a request parameter and should not bother Knockout. It is only available to bind the list of configurationHelper.configurations to Spring MVC.
Following form is properly bound to Spring MVC controller:
<form:form modelAttribute="configurationHelper" action="/leina16/configuration/saveConfigurationList.htm" method="POST" id="configuration-form" class="form-inline">
<form:input path="configurations[0].key" class="form-control input-sm"/>
</form:form>
Now I want to extend inputs with Knockout JS so I need at least the data-bind attribute as well as the foreach: $index from Knockout:
<tbody data-bind="foreach: configurations">
<input data-bind='attr:{value: key, name:"configurations[$index].key}' class="form-control input-sm" type="text"/>
</tbody>
But the snipped above is neither bound to Spring MVC controller method nor the values are populated.
You have a missing } and are probably getting an error about Knockout being unable to parse bindings.
Change:
'attr:{value: key, name:configurationHelper.configurations[$index].key'
To:
'attr:{value: key, name:configurationHelper.configurations[$index].key}'
As configurationHelper is defined outside of your foreach loop, you'll need to reference this using $parent or $root:
'attr:{value: key, name:$parent.configurationHelper.configurations[$index].key}'
Solution:
Add quotes to "non-Knockout" elements and use $index() function.
<tbody data-bind="foreach: configurations">
<tr>
<td>
<input data-bind='attr:{value: key, name:"configurations["+$index()+"].key"}' class="form-control input-sm" type="text"/>
</td>
</tr>
</tbody>

Categories

Resources