Add Javascript and HTML form entries to database - javascript

How can I add this javascript/html form to the database? I know only how to connect html/php with SQL...
here is the code that will allow the user to pick up the dates but its connected with javascript .. I need a way to save it into the database ..
HTML
<div id="hourForm">
<div id="Sunday" class="day"></div>
<div id="Monday" class="day"></div>
<div id="Tuesday" class="day"></div>
<div id="Wednesday" class="day"></div>
<div id="Thursday" class="day"></div>
<div id="Friday" class="day"></div>
<div id="Saturday" class="day"></div>
</div>
javascript
$('.day').each(function() {
var day = $(this).attr('id');
$(this).append('<div id="label">' + day + ': </div>');
$(this).append('<select name="' + day + 'FromH" class="hour from"></select>');
$(this).append('<select name="' + day + 'FromM" class="min from"></select>');
$(this).append('<select name="' + day + 'FromAP" class="ampm from"></select>');
$(this).append(' to <select name="' + day + 'ToH" class="hour to"></select>');
$(this).append('<select name="' + day + 'ToM" class="min to"></select>');
$(this).append('<select name="' + day + 'ToAP" class="ampm to"></select>');
$(this).append(' <input type="checkbox" name="closed" value="closed" class="closed"><span>Closed</span>');
});
$('.hour').each(function() {
for (var h = 1; h < 13; h++) {
$(this).append('<option value="' + h + '">' + h + '</option>');
}
$(this).filter('.from').val('9');
$(this).filter('.to').val('5');
});
$('.min').each(function() {
var min = [':00', ':15', ':30', ':45'];
for (var m = 0; m < min.length; m++) {
$(this).append('<option value="' + min[m] + '">' + min[m] + '</option>');
}
$(this).val(':00');
});
$('.ampm').each(function() {
$(this).append('<option value="AM">AM</option>');
$(this).append('<option value="PM">PM</option>');
$(this).filter('.from').val('AM');
$(this).filter('.to').val('PM');
});
$('input').change( function() {
if($(this).filter(':checked').val() == "closed") {
$(this).siblings('select').attr('disabled', true);
} else {
$(this).siblings('select').attr('disabled', false);
}
});
$('#Saturday .closed, #Sunday .closed').val(["closed"]).siblings('select').attr('disabled', true);
please give me a hint or a tutorial if you can't help..

You'll need to learn how to use AJAX, this will allow you to send and receive data from the database, usually you'll have some PHP which will display JSON and your AJAX will request this from the PHP page.
http://www.formget.com/submit-form-using-ajax-php-and-jquery/
Your AJAX will look something like this:
$.ajax({
method: "GET",
url: "test.php",
data: { param1 : "Bob", param2 : "Larry" },
dataType: "script"
});
This will call your PHP file "test" and pass in parameters param1 and param2

Related

Searching name using JS and AJAX

I am making name searching bar with JS and AJAX.
If write name on searching bar, only searched member must be shown.
And these are my code.
html:
...
<input type="text" id="searchName" name="searchName" placeholder="Search name..." onkeyup="nameFilter()" >
</div>
<ul class="invite-list03"></ul>
<ul id="memberList" class="member-list-group"></ul>
AJAX:
for (let i in user.family) {
let familyUserSn = user.family[i].familyUserSn;
let familyMemberNm = user.family[i].familyMemberNm;
let userProflPhotoCn = user.family[i].userProflPhotoCn;
let memberCreatDt = user.family[i].memberCreatDt;
let today = common_getTodayWithHyphen();
let family;
let hideDeleteBtn = '<div class="button-area"><button type="button" class="button-member-hide">hide</button><button type="button" class="button-member-delete" id="memberDeletePopUp">delete</button></div>';
// If today is invited day, show New icon up side of family member image
if(memberCreatDt == today) {
if(!userProflPhotoCn && userProflPhotoCn < 1) {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + DATA_NO_PROFILE + '" alt="profilePicture"></figure><label class="new">N</label></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
} else {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + userProflPhotoCn + '" alt="profilePicture"></figure><label class="new">N</label></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
}
} else {
if(!userProflPhotoCn && userProflPhotoCn < 1) {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + DATA_NO_PROFILE + '" alt="profilePicture"></figure></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
} else {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + userProflPhotoCn + '" alt="profilePicture"></figure></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
}
}
// append to memberList
$("#memberList").append(family);
}
// I am first member of list
$(".family").first().click();
JS:
function nameFilter() {
let searchNameSave = $('#searchName').val();
if(searchNameSave.length > 0) {
$("#memberList").html("");
$("ul#memberList > li > .member-name:contains('" + searchNameSave + "')").parent().show();
}
}
What should I write in javascript? Now it doesn't working.
Thank you for your help.
Hi there are a few things you need to do
Ajax get source information
Filter the source data according to the search criteria
Remove the old data and replace the filtered data
You can set your code according to this idea
The following is an example of using jquery-ui + ajax + autocomplete for your reference
$("#queryname").autocomplete({
source: function(request, response) {
$.ajax({
type: 'get',
url: "https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/objects_salary.txt",
dataType: 'json',
success: function(data) {
const matcher = new RegExp(request.term, "i");
const datas = data['data'];
response($.map(datas, function(item) {
if (matcher.test(item.name)) {
return {
label: item.name,
value: item.name
}
}
}));
}
});
}
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type='text' id='queryname' name='queryname' placeholder='Enter some text' />

Run a javascript from a html table cell

I am using asp.net core 5 and I have the following cell in a table -
<td id="actionId" class="text-left">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
</td>
I am trying to call a javascript function and add html at designationplaceholder for each record in the table.
I have tried -
$('tr').each(function (i, item) {
var html = DesignationStatus($('#dedesignatedDateId').val(), $('#renewalDueId').val(), $('#nextRenewalDueAtId').val(), #(ViewBag.NumberOfDays));
$('#designationPlaceHolderHere').html(html);
});
Doesn't work properly.
I want to call the function, for each record, passing the appropriate values for each record.
Any ideas?
Thanks
[UPDATE]
This is the function I call -
function DesignationStatus(dedesignatedDate, renewalDue, nextRenewalDue, numberOfDays) {
var isRenewalDue = (renewalDue === 'true')
//Get today's date
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
//Create next renewal due date display value.
var reDate = new Date(nextRenewalDue);
var reDay = reDate.getDate();
var reMonth = reDate.getMonth() + 1;
var displayRenewalDate = (reDay < 10 ? '0' : '') + reDay + '/' + (reMonth < 10 ? '0' : '') + reMonth + '/' + reDate.getFullYear()
//Create de-designation date display value.
var deDate = new Date(dedesignatedDate);
var deDay = deDate.getDate();
var deMonth = deDate.getMonth() + 1;
var displayDedesignationDate = (deDay < 10 ? '0' : '') + deDay + '/' + (deMonth < 10 ? '0' : '') + deMonth + '/' + deDate.getFullYear()
//Calculate what one day is
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
//Parse the number off days passed in
var numOfDays = parseInt(numberOfDays);
//If no number has been passed in set to default of 90.
if (isNaN(numberOfDays)) {
numOfDays = 90;
}
//Start html string
var html = '<div>'
html += ' <label>Designation status:</label>'
html += ' </div>'
html += ' <div>'
//Get rest of html dependant on due date etc.
if (dedesignatedDate != null && dedesignatedDate != "") {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>De-designated on</label>' + ' ' + displayDedesignationDate
}
else {
if (nextRenewalDue != null && nextRenewalDue != "") {
var today = new Date();
var renewal = new Date();
today = Date.parse(todaysDate);
renewal = Date.parse(nextRenewalDue);
if (renewal > today) {
if (!isRenewalDue) {
html += ' <div class="alert alert-success" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Active</label>'
}
else {
html += ' <div class="alert alert-warning" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Due to renew - renew before </label>' + ' ' + displayRenewalDate
}
}
else if (renewal < today) {
//Work out the number of days between renewal and today's date
var diffDays = Math.round(Math.abs(((new Date(today).getTime()) - (new Date(renewal).getTime())) / (oneDay)));
if (diffDays < numOfDays) {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive - lapsed on </label>' + ' ' + displayRenewalDate;
}
else {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive</label>'
}
}
}
}
//Finish off the html string
html += ' </div>'
html += ' </div>'
html += '</div>'
//return html strin
return html
}
<td id="actionId" class="text-left" onclick="DesignationStatus('#clinic.VaccClinic.DedesignationDate','#clinic.RenewalDue','#clinic.VaccClinic.NextRenewalDueAt','#ViewBag.NumberOfDays')">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
This should call your javascript function. Also never use the same id="dedesignatedDateID".

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

jQuery split() returns undefined

i have problam idont know why bat i see all time "undefined" in all "field_input"
when i try to add from jquery .split
function field_include()
{
var form_id = $( ".form" ).val();
$.ajax({
url: 'ajax/field_include.php',
type: 'POST',
data: {
form_id : form_id
},
success: function(data) {
var fields = data;
var field = fields.split(";").filter(Boolean);
$.each(field, function(i, val){
var field_val = val.split(",");
$( ".addfromform" ).append('<div class="form-group"><label class="col-lg-2 control-label mt10">'+field_val[2]+'</label><div class="col-xs-10"><label for="'+field_val[1]+'" class="field prepend-icon"><input type="'+field_val[0]+'" name="'+field_val[1]+'" id="first_name" class="gui-input" placeholder="'+field_val[3]+'" autocomplete="off"><label for="'+field_val[1]+'" class="field-icon"><i class="fa fa-user"></i></label></label></div></div>').fadeIn('slow');
});
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
string from "field_include.php":
1,first_name,First Name:,First Name,1;1,last_name,Last Name:,Last Name,2;1,email,Email:,Email,3;1,job,Job title:,Job title,4;
how i can fix ?
Try chaining .filter(Boolean) to fields.split(";") to remove empty string "" at last index of field where character at last index of string is ";" which would return undefined at var field_input = val.split(','); as val would be empty string ""
var field = fields.split(";").filter(Boolean);
var fields = "1,first_name,First Name:,First Name,1;1,last_name,Last Name:,Last Name,2;1,email,Email:,Email,3;1,job,Job title:,Job title,4;";
var field1 = fields.split(";");
var field2 = fields.split(";").filter(Boolean);
$.each(field2, function(i, val) {
var field_val = val.split(",");
$("body").append('<div class="form-group"><label class="col-lg-2 control-label mt10">' + field_val[2] + '</label><div class="col-xs-10"><label for="' + field_val[1] + '" class="field prepend-icon"><input type="' + field_val[0] + '" name="' + field_val[1] + '" id="first_name" class="gui-input" placeholder="' + field_val[3] + '" autocomplete="off"><label for="' + field_val[1] + '" class="field-icon"><i class="fa fa-user"></i></label></label></div></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

handling 2 different select option which were just appended with jquery

first thank to this question https://stackoverflow.com/questions/14792014/select-option-which-were-just-appended-with-jquery
i have another problem when option value from spilting data on sql result there are two select in one page.
Here my code
as default page
<div>
Warehouse Product
<br><input type="text" id="wh" readonly/>WHK</br>
</br>
Nomor Rak
<br><input type="text" id="posisi" readonly/></br>
Product Kategori
<br><select id="pkategori">
<option selected = "selected" value = "option1">-Kategori Produk-</option>
<?php
$q = mssql_query("SELECT DISTINCT ProductCategory from tblMstProductUHT1");
while ($r = mssql_fetch_array($q)){
echo "<option value='$r[ProductCategory]'>$r[ProductCategory]</option>";
}?>
</select>
</br>
Nama Produk
<br><select id="pname">
<option selected = "selected" value="option1" >-Nama Produk-</option>
<?php
$q = mssql_query("SELECT DISTINCT ProductName from tblMstProductUHT1");
while ($r = mssql_fetch_array($q)){
echo "<option value='$r[ProductName]'>$r[ProductName]</option>";
}?>
</select>
</br>
Kode Produksi
<br><input type='text' id="pdate"></br>
Line/FM
<br><input type='text' id="line"></br>
Nomor Palet
<br><input type="text" id="pnumber"/>
</br>
Nomor Seri Produk
<br><input type='text' id="seri"></br>
Quantity(Carton)
<br><input type='text' id="quantity"></br>
<button id="save">Save</button>
<button id="edit">Edit</button>
<button id="view">View</button>
<button id="delete">Delete</button>
</div>
you see there two select option <select id="pkategori"> and <select id="pname">. Now for Edit button i call available data using ajax like below
$("#edit").click(function(){
posisi = $("#posisi").val();
$.ajax({
type:'POST',
url: "aksi.php",
data: "op=edit&posisi="+posisi,
cache: false,
success: function(msg){
if(msg=="error"){
$(".status").html("<font color='##480000'><strong> Data tidak ditemukan..! </strong></font>");
}
else{
//karna di server pembatas setiap data adalah |
//maka kita split dan akan membentuk array
data = msg.split("|");
//masukkan ke masing-masing textfield
var r = [data[0]];
options = [{id:0, value:r}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pkategoriOption_' + data['id'] + '" class="pkategori" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pkategori').append(option);
}
$("#pkategori .pkategori:first").prop('selected', true);
var s = [data[1]];
options = [{id:0, value:s}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pnameOption_' + data['id'] + '" class="pname" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pname').append(option);
}
$("#pname .pname:first").prop('selected', true);
$("#pdate").val(data[2]);
$("#pnumber").val(data[3]);
$("#seri").val(data[4]);
$("#quantity").val(data[5]);
$("#line").val(data[6]);
//hilangkan status dan animasi loading
$(".status").html("");
$(".loading").hide();
}
}
});
});
on url: "aksi.php", i split data using "|". According to the question that i linked in first. I succesfull append option value on <select id="pkategori"> and set this as default selected.
But when i use the same code for the second option <select id="pname"> it's caused error and data that i split doesn't show. so i stuck, what the problem?
actually your linked have the answer. in your code you just have similar var. mean on "data", it's cause conflict. Jquery will confuse to bind data,
so you just change data = msg.split("|"); to another name variable.
Your code will be like below
$("#edit").click(function(){
posisi = $("#posisi").val();
$.ajax({
type:'POST',
url: "aksi.php",
data: "op=edit&posisi="+posisi,
cache: false,
success: function(msg){
if(msg=="error"){
$(".status").html("<font color='##480000'><strong> Data tidak ditemukan..! </strong></font>");
}
else{
//karna di server pembatas setiap data adalah |
//maka kita split dan akan membentuk array
da = msg.split("|"); // it can be another variable name
//masukkan ke masing-masing textfield
var r = [da[0]];
options = [{id:0, value:r}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pkategoriOption_' + data['id'] + '" class="pkategori" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pkategori').append(option);
}
$("#pkategori .pkategori:first").prop('selected', true);
var s = [da[1]];
options = [{id:0, value:s}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pnameOption_' + data['id'] + '" class="pname" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pname').append(option);
}
$("#pname .pname:first").prop('selected', true);
$("#pdate").val(da[2]);
$("#pnumber").val(da[3]);
$("#seri").val(da[4]);
$("#quantity").val(da[5]);
$("#line").val(da[6]);
//hilangkan status dan animasi loading
$(".status").html("");
$(".loading").hide();
}
}
});
});

Categories

Resources