Dynamic drop down menu node js - javascript

I'm new to node. I need to make a dependent dropdown menu which gets the address data of the selected user from another dropdown menu in the same page..The proplem is that the hole page is updated not only the second dropdown menu.. I think it's the same problem as dynamically dropdown in nodejs mysql, but it didn't help me much.
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
<% address.forEach((address) => { %>
<option value="<%= address.addressId %>" > <%=address.addressName %> </option>
</select>
<% }) %>
my ajax request:
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
var add = $('#address').val();
$.ajax({
type:'GET',
data: {selectedId : item },
url:'/order/new',
success: function(result1){
$('#body').html(result1);
}
});
});
});
order.js
module.exports = {
addOrderPage: (req, res) => {
let query1 = "SELECT * FROM users";
getConnection().query(query1, (err, result1) => {
let query2 = "SELECT * FROM address WHERE userId = '" +req.query.selectedId + "'";
getConnection().query(query2, (err, rows, fields) => {
if (err) {
return res.status(500).send(err);
}
console,log(rows)
res.render('newOrder.ejs', {
address : rows,
users: result1
});
});
});
}
}
app.js
app.get('/order/new', addOrderPage)

Your success function has missing the data that is return from request update your success function
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
$.ajax({
type:'GET',
data: { selectedId: item },
url:'/users/address',
success: function(data){
console.log(data);
$('#address').empty();
$('address').append("<option disabled selected> Select Address..</option>");
$.each(data, function (index, addressObj) {
$('#address').append("<option value = '" + addressObj.id + "' > " + addressObj.first_name + ". </option > ");
});
}
});
});
And in your order.js you need create one call for users and one call is for usersaddress data:-
module.exports = {
addOrderPage: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM users";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.render('newOrder.ejs', {
players: result1,
});
});
},
getUserAddress: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM address WHERE userId = '" + selectedId + "'";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.send(result1);
});
}
}
neworder.js
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
</select>
And in your app.js or index.js you need to add its route
app.use("/users/address", order.getUserAddress);

Related

Send true or false to database wether checkbox is checked or not

i got an issue regarding checkboxes with nedb. I want to send true or false if the checkbox is checked or not to the database i cannot solve this issue. i am working with node.js and nedb. please help!
client js eventlistener:
var taskDone = document.querySelectorAll('.taskDone');
taskDone.forEach(btn => {
btn.addEventListener('click', (e) => {
var done = e.target.attributes[1].value;
let id = e.target.getAttribute('data-id');
let isDone = document.querySelector(`input[data-id=${id}]`).value;
console.log(isDone + "isdone")
if ($(taskDone).is(':checked')) {
$('.text').addClass('line-through')
console.log("trues")
$.ajax({
url: 'http://localhost:3000/done/' + id,
type: 'PUT',
data: { isDone }
}).done(function (data) {
//location.reload()
console.log(data)
})
} else {
console.log('falses')
$('.text').removeClass('line-through')
}
})
})
update function to nedb:
function taskIsDone (id, done) {
return new Promise((resolve, reject) => {
db.update({ _id: id }, { $set: done }, { returnUpdatedDocs: true }, (err, num, updateDocs) => {
if (err) {
reject(err)
} else {
resolve(updateDocs)
}
})
})
}
server:
app.put('/done/:_id', async(req, res) => {
try {
var id = req.params._id;
let done = {
title: req.body.isDone,
}
const updateToDo = await taskIsDone(id, done)
console.log(updateToDo + " Todo done");
res.json(updateToDo);
} catch (error) {
res.json({error: error.message});
}
})
html/ejs:
<% for ( var i = 0; i < row.length; i++) { %>
<div class="edit-container" >
<input type="text" name="editTask" value="<%=row[i].title %>" data-id="<%=row[i]._id %>">
<button name="<%= row[i]._id %>" class="edit" data-id="<%=row[i]._id %>">save edit</button>
</div>
<div>
<input type="checkbox" name="isDone" class="taskDone" data-id="<%=row[i]._id %>">
<span class="text"><%= row[i].title %></span>
<button class="delete" name="<%= row[i]._id %>">delete</button>
</div>
<br>
<% } %>
i could really need some help with this! thanks
I have recreated a minimal example of what you are trying to do with checkbox checked state. I have added three checkboxes with same class name .taskDone
And i have using a change function not a click function. Every-time you clicked on the checkbox and check it will show the console log with checked and the data-id of that checkbox as well.
To get the data-id you can simply use .data function of jQuery and just specify what you want after the data-** to get it stored value.
In addition, do not use fat arrow - => function with jQuery. Use normal function statements so you can access you things by using $(this) instead of specifying each class or id
Live Working Demo:
let taskDone = document.querySelectorAll('.taskDone'); //get all the chechbox with same class .taskDone
taskDone.forEach(function(btn) { //use normal function
btn.addEventListener('change', function() {
let id = $(this).data('id') //get the data id of checkbox
if ($(this).is(':checked')) { //check if the clicked checkbox is checked or not
console.log(id + ' is Checked - Updating neDB') //console.log
$.ajax({
url: 'http://localhost:3000/done/' + id,
type: 'PUT',
data: 'isDone'
}).done(function(data) {
console.log(data)
})
} else {
console.log("Not Checked")
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="isDone" class="taskDone" data-id="1">
<input type="checkbox" name="isDone" class="taskDone" data-id="2">
<input type="checkbox" name="isDone" class="taskDone" data-id="3">

Laravel 7: How to get name instead of id in dependent dropdown?

I have a dependent dropdown and it gets values by comparing ID's, the issue here is when I am trying to save the form values I am getting the ID's instead of names of the select fields. Can anyone tell me how can I get the NAME instead of ID.
My blade view with the javascript: index.blade.php`
<div class="container">
<h2>Region</h2><br>
<form action="details" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Select Country:</label>
<select id="country" name="country" class="form-control" style="width:350px" required>
<option value="" selected disabled>Select</option>
#foreach($countries as $key => $country)
<option value="{{$key}}">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" id="state" class="form-control" style="width:350px" required>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" id="city" class="form-control" style="width:350px" required>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script type="text/javascript">
$('#country').change(function() {
var countryID = $(this).val();
if (countryID) {
$.ajax({
type: "GET",
url: "{{url('get-state-list')}}?country_id=" + countryID,
success: function(res) {
if (res) {
$("#state").empty();
$("#state").append('<option value="">Select</option>');
$.each(res, function(key, value) {
$("#state").append('<option value="' + key + '">' + value + '</option>');
});
} else {
$("#state").empty();
}
}
});
} else {
$("#state").empty();
$("#city").empty();
}
});
$('#state').change(function() {
var stateID = $(this).val();
if (stateID) {
$.ajax({
type: "GET",
url: "{{url('get-city-list')}}?state_id=" + stateID,
success: function(res) {
if (res) {
$("#city").empty();
$("#city").append('<option value="">Select</option>');
$.each(res, function(key, value) {
$("#city").append('<option value="' + key + '">' + value + '</option>');
});
} else {
$("#city").empty();
}
}
});
} else {
$("#city").empty();
}
});
</script>
My Controller for the dropdown: DropdownController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DropdownController extends Controller
{
public function index()
{
$countries = DB::table("countries")->pluck("name", "id");
return view('index', compact('countries'));
}
public function getStateList(Request $request)
{
$states = DB::table("states")
->where("country_id", $request->country_id)
->pluck("name", "id");
return response()->json($states);
}
public function getCityList(Request $request)
{
$cities = DB::table("cities")
->where("state_id", $request->state_id)
->pluck("name", "id");
return response()->json($cities);
}
public function show(Request $request)
{
dd(request()->all());
}
}
The payload I am getting after data dump is the ID's:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxx"
"country" => "1"
"state" => "5"
"city" => "124"
]
What I want is to get Names:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxx"
"country" => "country_name"
"state" => "state_name"
"city" => "city_name"
]
You should change the name of your select from name to name[]

Laravel 7 - Trouble retrieving old value of dynamic select when validation fails

The form has a select for Customer with populates from a variable in the controller. I can easily retrieve the old input value using old('customer_id').
My problem comes from the second select. The second select uses javascript to populate the Customer Contact based on which Customer is chosen. When validation fails, I lose that value.
Here is the controller code for the store method:
$rules = [
'number' => 'required',
'customer_id' => 'required',
'contact_id' => 'required',
'payment_type' => 'nullable',
'department_id' => 'required',
'requested_ship_date' => 'required|after:yesterday',
];
$customMessages = [
'number.required' => 'The Sales Order number is required.',
'customer_id.required' => 'Please choose a customer.',
'contact_id.required' => 'Please choose a contact.',
'requested_ship_date.required' => 'You must enter a ship date.',
'requested_ship_date.yesterday' => 'The requested ship date must be today or after.',
'department_id.required' => 'Please choose a department.'
];
$salesorder = \request()->validate($rules, $customMessages);
SalesOrder::create($salesorder);
return redirect('/salesorders');
Here is Customer Select:
<select
name="customer_id"
class="shadow text-sm">
#if (old('customer_id'))
<option
value>
</option>
#else
<option
selected
value>
</option>
#endif
#foreach($customers as $customer)
#if (old('customer_id'))
<option
value="{{ $customer->id }}" {{ old('customer_id') == $customer->id ? 'selected' : '' }}>
{{ ucfirst($customer->name) }}
</option>
#else
<option
value="{{ $customer->id }}">
{{ ucfirst($customer->name) }}
</option>
#endif
#endforeach
</select>
Here is the select for the Customer Contact:
<select
name="contact_id"
class="shadow text-sm text-center"
>
<option>
</option>
</select>
And here is the javascript:
$('select[name="customer_id"]').on('change', function () {
var customerId = $(this).val();
if (customerId) {
$.ajax({
url: '/customer/contacts/get/' + customerId,
type: "GET",
dataType: "json",
beforeSend: function () {
$('#loader').css("visibility", "visible");
},
success: function (data) {
$('input[name="email"]').val('');
$('select[name="contact_id"]').empty();
$('select[name="contact_id"]').append('<option value="Choose">Choose Contact</option>');
$.each(data, function (key, value) {
$('select[name="contact_id"]').append('<option value="' + key + '">' + value + '</option>');
});
},
complete: function () {
$('#loader').css("visibility", "hidden");
}
});
} else {
$('select[name="customer_id"]').empty();
}
});

clone form include dependent fields by vuejs

I have a form in which there should be submitting a price for various health care services. Treatments are already categorized. Now, I want to first select a treatment group from a selector and then select the treatment list for that category in the next selector. When I have just one form on the page, I have no problem. But I need to clone this form and the user can simultaneously record the price of some treatments. In this case, all the second selectors are set according to the last selector for the categories. While having to match their category's selector. I searched for the solution very well and did not get it. My code in vuejs is as follows. Please guide me. Thank you in advance.
<template>
<div>
<div id="treatment_information">
<div class="col-md-3">
<select id="category_name" class="form-control show-tick"
v-on:change="getTreatmentList($event)"
name="treatment_rates[]category_id" v-model="treatment_rate.category_id"
>
<option value="0"> -- select category --</option>
<option class="form-control main"
v-for="item in vue_categories" :id="item.id+1000" :value="item.id"
:name="item.name">
{{ item.name }}
</option>
</select>
</div>
<div class="col-md-3">
<select id="treatment_id" class="form-control show-tick"
name="treatment_rates[]treatment_id" v-model="treatment_rate.treatment_id"
>
<option value="0"> -- select treatment --</option>
<option class="form-control main"
v-for="item in vue_treatments" :value="item.id">
{{ item.value }}
</option>
</select>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
vue_temp: [],
vue_categories: [],
vue_treatments: [],
vue_category: '',
//for clone form
treatment_rate: {
category_id: 0,
treatment_id: 0,
hospital_id: 0,
dollar: 'دلار',
rial: 'ریال'
},
treatment_rates: [],
};
},
mounted() {
console.log('Component mounted.');
this.getList();
},
methods: {
getList() {
var self = this;
axios.get('/vueDashboard/get/categories').then(function (response) {
self.vue_temp = response.data;
const len = self.vue_temp.length;
self.vue_temp.forEach(function (item) {
if (self.vue_right.length > 0) {
while (self.vue_right[self.vue_right.length - 1] < item['rgt']) {
self.vue_right.pop();
if (self.vue_right.length == 0)
break;
}
}
self.vue_categories.push({
'id': item['id'],
'name': '---'.repeat(self.vue_right.length) + ' ' + item['name']
});
self.vue_right.push(item['rgt'])
var str = "---";
});
}).catch(function (error) {
console.log(error);
});
axios.get('/vueDashboard/get/treatments?category=' + JSON.stringify(self.treatment_rates)).then(function (response) {
console.log(response.data);
self.vue_treatments = response.data;
}).catch(function (error) {
console.log(error);
});
},
addForm(event) {
var self = this;
self.vue_increment_id[self.vue_counter++]=self.vue_counter;
console.log(self.vue_increment_id);
self.treatment_rates.push(Vue.util.extend({}, self.treatment_rate));
},
}
}
</script>

how retrieve data from db using ajax in laravel 4?

how retrieve data from database using ajax in laravel 4?
sorry I am new to ajax and this is just the code I started
html
<select id="bookstatus">
<option value="" disabled selected>Sort by Book Status</option>
<option value="1">For Rent</option>
<option value="2">For Barter</option>
</select>
js & ajax:
$('#bookstatus').on('change', function() {
var bs = document.getElementById("bookstatus");
var getbookstatus = bs.options[bs.selectedIndex].value;
$.ajax({
method: 'post',
url: 'discover',
data: {getbookstatus:getbookstatus},
success: function() {
}
});
});
routes:
Route::post('discover', 'BookController#getbook');
Route::get('discover', 'BookController#getbook');
my controller:
public function getbook(){
$bookstatus = Input::get('getbookstatus');
$getbook = DB::select("SELECT title FROM books WHERE forRent='$bookstatus' ");
im expecting that it will display books based on selected value
in view
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select id="bookstatus">
<option value="" disabled selected>Sort by Book Status</option>
<option value="1">For Rent</option>
<option value="2">For Barter</option>
</select>
<br><br>
<span ><strong>Show the books </strong></span>
<div id="result">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('ready work');
$(document).on('change','#bookstatus',function(){
var getbookstatus=$(this).val();
console.log(getbookstatus);
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findbookstatus')!!}',
data:{'statusid':getbookstatus},
success:function(data){
console.log(data);
console.log(data.length);
op+='<ul>';
for(var i=0;i<data.length;i++){
op+='<li>'+data[i].title+'</li>';
}
op+='<ul>';
$('#result').html(op);
},
error:function(){
console.log('error');
}
});
});
});
</script>
</body>
</html>
in Route
Route::get('/discover','BookController#getbook');
Route::get('/findbookstatus','BookController#findbookstatus');
in Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class BookController extends Controller
{
public function getbook(){
return view('bookview');
}
public function findbookstatus(Request $request){
$getbook=DB::table('books')->select('title')->
where('forRent',$request->statusid)->take(100)->get();
return response()->json($getbook);
}
}
Database Connection
in case laravel 4.2 go to config/database.php
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
in case laravel 5.3 go to .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=root
DB_PASSWORD=
table structure 'books'
enter image description here
For details you may watch this video
https://www.youtube.com/watch?v=N5ctY9nPt9o&feature=youtu.be

Categories