I store input values into mongodb using scope name. I have a 3 fields when I click add all values are in object so I directly send the scope name into server and store it.
I would like to store only 2nd textbox values and remaining values should be NULL into the database. But I don't know how to do this. Anyone can help me?
Server.js
app.post('/AddNewcontact', function (req, res) {
db.Manage_Facility.insert(req.body, function (err, docs) {
console.log(docs);
res.json(docs);
});
});
controller.js
$scope.AddNew = function () {
$http.post('/AddNewcontact', $scope.Contact).success(function (response) {
});
};
html
<input type="text" name="Name" class="form-control" ng-model="Contact.Name">
<input type="text" name="email" class="form-control" ng-model="Contact.email">
<input type="text" name="cellno" class="form-control" ng-model="Contact.cellno">
<button class="btn btn-primary" ng-click="AddNew()" >Submit</button>
controller.js
$scope.AddNew = function () {
$http.post('/AddNewcontact',{ 'Name': $scope.Contact.email}).success(function (response) {
});
};
Let's say you want to send just the email, do following :
delete $scope.Contact.Name;
delete $scope.Contact.cellno;
here is example
$http.post('/AddNewcontact', $scope.Contact).success(function (response) {
});
Related
I have made a search bar on the customers page of my website and whatever string the admin enters in the search bar will be sent as a get request, and based on the input I am trying to find all the data in MySQL db which contains the input string inside of the fullname field.
My website build as MVC model, using Express to display data and Node.js
This is my form
<form class="d-flex" method="GET">
<input class="form-control me-2 py-1" type="text" id="search" name="search" placeholder="Search customer name" aria-label="Search" value="<%= %>" />
<button class="btn btn-sm btn-secondary" type="submit">Search</button>
</form>
This is route in web.js file
router.get('/customer?search',authentication.handleAuthentication, authadmin.authAdmin,adminController.searchCustomer);
getCustomerByName() inside adminServices.js
let getCustomerByName = (name) => {
return new Promise(async (resolve, reject) => {
try {
let user = await db.User.find({ fullname: name });
if (user) {
console.log(user);
resolve(user);
} else {
resolve(user);
}
} catch (e) {
reject(e);
}
});
};
searchCustomer() inside adminController.js
let searchCustomer = async (req,res,next) =>{
let name = req.params.search;
let customer = await adminServices.getCustomerByName(name);
return res.render('admin/customer.ejs', {
customer: customer,
});
}
I had tried req.body.search / req.params.search / req.query but seem like it can't get the input.
The URL like this: http://localhost:8080/customer?search=mai. I couldn't find where is the problem because there is nothing show in the console. Are there any method I could try?
You need to add action tag to form element. Change route name to just customer and use req.query.search in controller.
router.get('/customer', authentication.handleAuthentication, authadmin.authAdmin, adminController.searchCustomer);
let searchCustomer = async(req, res, next) => {
let name = req.query.search; // change params to query
let customer = await adminServices.getCustomerByName(name);
return res.render('admin/customer.ejs', {
customer: customer,
});
}
<form class="d-flex" action="/customer" method="GET">
<input class="form-control me-2 py-1" type="text" id="search" name="search" placeholder="Search customer name" aria-label="Search" value="<%= %>" />
<button class="btn btn-sm btn-secondary" type="submit">Search</button>
</form>
I have two fields in my form, customer name, card name, i am trying to implement autocomplete to fetch details from the database to auto fill the rest of the fields.
I have got typeahead working on the first input field, however, when using the same method for the second field which is the card number, autofill is not coming up at all. I am not sure what i am doing wrong, a little guidance is appreciated here.
here is my create.blade.php
<div class="form-group">
<strong>Customer Name:</strong>
<input class="typeahead form-control" type="text" id='cust' onkeypress="myFunction1()" placeholder="Customer Name">
</div>
<div class="form-group">
<strong>Card Number:</strong>
<input class="typeahead form-control" type="text" id='card' autocomplete="off" onkeypress="myFunction()" placeholder="Card Number">
</div>
<script>
function myFunction() {
var path = "{{ route('autocompletecard') }}";
$('#card').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
}
function myFunction1()
{
var path = "{{ route('autocomplete') }}";
$('#cust').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
}
</script>
here is my Assignee controller:
public function autocomplete(Request $request)
{
$data = Customer::select("name")
->where("name","LIKE","%{$request->input('query')}%")
->get();
return response()->json($data);
}
public function autocompletecard(Request $request)
{
$data = Card::select("number")
->where("number","LIKE","%{$request->input('query')}%")
->get();
return response()->json($data);
}
after checking the console and network tab on the browser autocompletecard is being executed, it is returning a card number as response. but it is not showing as autocomplete.
I am attempting to add a search functionality with my database using Node & Handlebars to render. However when I search now it's giving me a 404 error, why is it not display search results? Here is my routing info
function searchPokemon(res, mysql, context, searchinput, complete){
var inserts = [req.body.searchinput];
var sql = 'SELECT pokemonname FROM pokemon WHERE pokemonname LIKE "%' + inserts + '%';
mysql.pool.query(sql, inserts, function(error, results, fields){
if(error){
res.write(JSON.stringify(error));
res.end();
}
context.search = results;
complete();
});
}
router.get('/search', function(req, res){
callbackCount = 0;
var context = {};
var mysql = req.app.get('mysql');
searchPokemon(res, mysql, context, req.body.searchinput, complete);
function complete(){
callbackCount++;
if(callbackCount >= 1) {
res.render('search-pokemon', context);
}
}
});
Here is my current page that I am rendering the search functionality on (pokemon.handlebars)
<h1>Current Pokemon Moves -</h1>
<table id="table">
<thead>
<th>Pokemon Name </th>
<th>Evolution Level </th>
<th>Move Name </th>
<th>Strength</th>
</thead>
<input type="text" class="search form-control" name="searchinput" placeholder="Pokemon Name">
<input type="button" class="btn btn-primary" value="Search" onclick="getUsers({{searchinput}})">
<br>
And here is my script to search
function getUsers(searchinput){
$.ajax({
url: '/search-pokemon',
type: 'GET',
success: function(result){
window.location.reload(true);
}
})
};
I had the same issue with the search function and I used typeahead.js.
Instead of 'post' I have used 'get'
router.post('/search', function(..)..
I'll put my code here, so u can get an idea.
app.js
// return homepage
app.get('/',function(req,res){
res.render('index');
});
// search function
app.post('/search',function(req,res){
var str = {
stringPart:req.body.typeahead
}
db.query('SELECT songTitle FROM song WHERE songTitle LIKE "%'+str.stringPart+'%"',function(err, rows, fields) {
if (err) throw err;
var data=[];
for(i=0;i<rows.length;i++)
{
data.push(rows[i].songTitle);
}
res.send(JSON.stringify(data));
});
});
index.ejs
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../JS/jquery.typeahead.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote: 'http://localhost:3000/search?key=%QUERY',
limit: 10
});
});
</script>
<form method="POST" action="/search">
<label>Search Data</label>
<input class="typeahead tt-query" spellcheck="false" autocomplete="off" name="typeahead" type="text" />
</form>
I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource
I've made a registration form with a lot of fields. Since when I submit data and the validator redirects back with errors some inputs are empty and the user has to lose time refilling them, I want to implement some front-end validations.
I'm stuck on checking if an username is already used on submit button press becasuse I'm not expert about AJAX.
In the AuthController I've created a function that returns a Json containing a response in relation of existence or not of the username in the database.
class UserAuthController extends Controller
{
public function isUserNameInUse( $username )
{
if (Auth::where('username', $username) != null){
return [ 'is_used' => 1 ];
}
return [ 'is_used' => 0 ];
}
}
In the routes.php there are these lines:
Route::group([ 'as' => 'api', 'prefix' => 'api', 'namespace' => 'Api'], function () {
Route::group([ 'as' => 'auth', 'prefix' => 'auth'], function () {
Route::any('/is_username_in_use/{username}', [
'as' => 'isUserNameInUse',
'uses' => 'UserAuthController#isUserNameInUse']);
});
});
The view is like that (only a piece of the form):
<form action="{{ route('web.company.postSignup') }}" method="post" id="signup-form" class="form-horizontal">
{!! csrf_field() !!}
#include( 'errors.handler' )
<label for="username">
{{ _('Username*') }} </label>
<input type="text" class="form-control" name="username" id="username"
value="{{ Input::old('username') }}" required>
<label for="password">
{{ _('Password*') }}
</label>
<input type="password" class="form-control" name="password" id="password"
value="{{ Input::old('password') }}" onchange="form.confirmPassword.pattern = this.value;"
required>
<label for="confirmPassword">
{{ _('Confirm Password*') }}
</label>
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" required>
<button class="btn btn-warning" id="submit-btn" type="submit">{{ _('Sign Up') }}</button>
</form>
This is the script, for now I've only tried to log the response of the controller, but it prints anything.
$(document).ready(function () {
$('form#signup-form').submit(function () {
var input_username = $('input[name=username]').val();
console.log(input_username);
$.getJSON('/api/auth/is_username_in_use/' + input_username, function (json) {
console.log(json);
});
return false;
});
});
There is no need to make an explicit check if user name is in use. You may skip this part and instead, when you storing your user's data validate them accordingly.
An example of this might be
public function store(Request $request)
{
$this->validate($request, [
'username' => 'required|unique:users',
'password' => 'required|confirmed'
]);
// process your logic
}
This way, if validation failed, you'll get a json response object containing error messages.
Note, this will work if you're on Laravel 5. If you are on 4.* refer to documentation for validation part.
You should change return [ 'is_used' => 0 ]; into return Response::json([ 'is_used' => 0 ]); and add use Response; to the top of your controller.