How to make webpage show specific database item? - javascript

I'm trying to make the website link such that when I click on the thumbnail, it will bring me to another page. However, the details will be displayed based on the itemID I get in browser.html. How do I do that?
My result just ended me up with ALL of database results. I have also done the getdetails function so it works. MySQL variables are .item at the back of the variable declaration. My route for the SQL is /details/:itemID
function displaythumbs()
{
var table = document.getElementById("DetailsTable");
console.log("details_array is => ", details__array)
table.innerHTML = "";
totalDetails = details_array.length;
for (var count = 0; count < totalDetails-1; count++)
{
var itemID = details_array[count].itemID;
var thumb = details_array[count].thumb;
var cell = '<div class="container-fluid>' +
'<div class="rightside" >' +
'<div class="right-left" style="margin-left:1%;">' +
'<a id="details" href="details.html">'+
'<img class="thumbstyle img-thumb" src=' +thumb+ ' />'+
'</a>'+
'</div>'+
'</div>' +
'</div>';
table.insertAdjacentHTML('beforeend', cell);
}
}
in my details.js
function displaydetails()
{
var table = document.getElementById("detailsTable");
table.innerHTML = "";
totalDetail = details_array.length;
for (var count = 0; count < totalDetail; count++)
{
var itemID = details_array[count].itemID;
var Hyperlink = details_array[count].HyperLink;
var name = details_array[count].itemName;
var ratings = details_array[count].Ratings;
var picture = details_array[count].picture;
var picture2 = details_array[count].picture2;
var cell = '<div class="overall">' +
'<div class="leftside"' +
'<div class="centertop">' +
'<h1 id="name"><u>' + name + '</u></h1>'+
'<div class="starratings" style="margin-right: 10%; margin-left: 10%; font-size:25px;">'+
'<span class="fa fa-star checked"></span>'+
'<span class="fa fa-star checked"></span>'+
'<span class="fa fa-star checked"></span>'+
'<span class="fa fa-star checked"></span>'+
'<span class="fa fa-star checked" style="margin-right: 1%;"></span>'+ratings+
'</div>'+
'<div class="visitwebsitelink" id="hyperlink">'+
'<a href='+Hyperlink +' />'+'<h3 style="color: black;"><u><i>Visit Website</i></u></h3>'+
'</a>'+
'</div>'+
'</div>'+
'<div class="fontstuff">'+
'Recent Reviews'+
'</div>'+
'</div>' +
'<div class="rightside">'+
'<div class="itemimg>'+
'<img src='+ picture + ' />'+
'<img src='+ picture2 + ' />'+
'</div>'+
'</div>';
table.insertAdjacentHTML('beforeend', cell);
}
}

Related

How can i get current Index using for each loop in javascript and update into realtime database

I am working with javascript also am a newbie in js so actually, I want to get the current index and then update a specific field to the realtime if somebody helps me out I will thankful to him here is my script where I fetch the data in realtime firebase and I put my value inside inner HTML format so I want when user press specific buttons its pending data update to booked.
userDataRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot, index) {
console.log(childSnapshot.val());
key = childSnapshot.key;
userid = childSnapshot.val().userid;
var carid = childSnapshot.val().carid;
var imageload = childSnapshot.val().imgurl;
var loadfirstname = childSnapshot.val().userfirstname;
var loadcarname = childSnapshot.val().carname;
var loadlastname = childSnapshot.val().userlastname;
var loadphonenumber = childSnapshot.val().phoneNumber;
var loaddropoffadd = childSnapshot.val().dropoffaddress;
var loadpickupadd = childSnapshot.val().pickupaddress;
loadprice = childSnapshot.val().price;
var appenddata =
'<div class="container rounded" style="background-color: #00829E" id="datalist">' +
'<div class="row">' +
'<div class="col-md-12">' +
'<div class="row">' +
'<div class="col-md-4 mt-2 mb-2 ml-2">' +
'<div class="container rounded"style="background-color: #efefef">' +
'<center>' +
'<img src="' + imageload + '" id="loadimage" style="height: 100px; width: 100px;">' +
'</center>' +
'</div>' +
'</div>' +
'<div class="col-md-6 mt-2 mb-2">' +
'<div class="container rounded para">' +
'<h5 id="loadcarname">' + loadcarname + '</h5>' +
'<p id="loadfirstname">First Name: ' + loadfirstname + '</p>' +
'<p id="loadlastname">Last Name: ' + loadlastname + '</p>' +
'<p id="loadphone">Phone Number: ' + loadphonenumber + '</p>' +
'<p id="loadpickup">Pickup Address: ' + loadpickupadd + '</p>' +
'<p id="loaddropoff">Dropoff Address: ' + loaddropoffadd + '</p>' +
'</div>' +
'</div>' +
'<div class="col-md-2"></div>' +
'</div>' +
'<div class="row">' +
'<div class="col-md-4"></div>' +
'<div class="col-md-4"></div>' +
'<div class="col-md-2 para1 mt-2">' +
'<p id="loadprice">Price:' + loadprice + ' Sum/Day</p>' +
'</div>' +
'<div class="col-md-2 mb-3">' +
'<button class="btn btn-info btn-sm rounded-pill check" id="approvebutton" value ="Booked" onclick="myFunction(this.value)" aria-pressed="true">Approve</button>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$("#listshow").append(appenddata);
});
});
when user press the button I call function named Myfunction I just want to update specific id in that function
my function name script
function myFunction(value) {
approvecar = document.getElementById('loadprice').value;
firebase.database.ref("carBooking/" + userid).update({
status: ""
});
}
To be able to write a value in the database, you need to know the complete path to that node. Right now, you know what value to write, but you've lost information about what key (the -M.... value) to write it to.
So you'll need to pass the key of the item the user clicked on, from your HTML into the myFunction function.
The simplest way to do that is something like:
'<button class="btn btn-info btn-sm rounded-pill check" id="approvebutton" value ="Booked"
onclick="myFunction(\''+key+'\', this.value)" // 👈 is changed
aria-pressed="true">Approve</button>' +
There may be some syntax problems in this part as I'm having a hard time parsing your HTML construction code.
Now that you're passing both the key and the value, you can update the correct node with:
function myFunction(key, value) {
approvecar = document.getElementById('loadprice').value;
firebase.database.ref("carBooking").child(key).update({
status: ""
});
}

Freezing bootstrap according while creating from AJAX

Actually in my website i populate bootstrap according dynamically when an according is opened, once it has been open the data is saved.
The issue is that when i open the according for first time it's freezing (as it have to append a lot of divs) and that trigger me a lot, so i would know how should i make it more performable or like which approach should i take to prevent that freezing.
The AJAX method is build as the following:
function getBody(body, key) {
$.ajax({
type: "POST",
url: "casse.aspx/getBody",
data: JSON.stringify({ key: key }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
data = r.d;
data = $.parseJSON(data);
$.each(data, function (i, item) {
var piva = item.piva;
var desmag = item.desmag;
var via = item.via;
var loc = item.loc;
var servb2b = item.servb2b;
var idtrabb2b = item.idtrabb2b;
var matricola = item.matricola;
var azzer = item.azzer;
var mac = item.mac;
var vp = item.vp;
var vb = item.vb;
var dr = item.dr;
var vu = item.vu;
var cpu = item.cpu;
var rt = item.giart;
var datart = item.avviort;
var card = "";
card += '<div class="row ml-2 mr-2">';
card += '<div class="col">';
card += '<div class="row"><span class="badge badge-primary">Cliente</span></div>';
card += '<div class="row"><small class="text-muted">P.Iva</small></div>';
card += '<div class="row"><p class="info">' + piva + '</p></div>';
card += '<div class="row"><small class="text-muted">Info Negozio</small></div>';
card += '<div class="row"><p class="info">' + desmag + '</p></div>';
card += '<div class="row"><small class="text-muted">Via</small></div>';
card += '<div class="row"><p class="info">' + via + '</p></div>';
card += '<div class="row"><small class="text-muted">Localita</small></div>';
card += '<div class="row"><p class="info">' + loc + '</p></div></div>';
card += '<div class="col">';
card += '<div class="row"><span class="badge badge-primary">Software</span></div>';
card += '<div class="row"><small class="text-muted">VisualPos</small></div>';
card += '<div class="row">' + vp + '</div>';
card += '<div class="row"><small class="text-muted">VisualB2B</small></div>';
card += '<div class="row">' + vb + '</div>';
card += '<div class="row"><small class="text-muted">Driver</small></div>';
card += '<div class="row">' + dr + '</div>';
card += '<div class="row"><small class="text-muted">VisualUpdate</small></div>';
card += '<div class="row"><p class="info">' + vu + '</p></div></div>';
card += '<div class="col">';
card += '<div class="row"><span class="badge badge-primary">Fiscale</span></div>';
card += '<div class="row"><small class="text-muted">Matricola</small></div>';
card += '<div class="row"><p class="info">' + matricola + '</p></div>';
card += '<div class="row"><small class="text-muted">Azzeramento Fiscale</small></div>';
card += '<div class="row"><p class="info">' + azzer + '</p></div>';
card += '<div class="row"><small class="text-muted">RT</small></div>';
card += '<div class="row"><p class="info">' + rt + '</p></div>';
card += '<div class="row"><small class="text-muted">Data Avvio RT</small></div>';
card += '<div class="row"><p class="info">' + datart + '</p></div></div>';
card += '<div class="col">';
card += '<div class="row"><span class="badge badge-primary">Fatturazione Elettronica</span></div>';
card += '<div class="row"><small class="text-muted">Servizio B2B</small></div>';
card += '<div class="row"><p class="info">' + servb2b + '</p></div>';
card += '<div class="row"><small class="text-muted">Trasmittente B2B</small></div>';
card += '<div class="row"><p class="info">' + idtrabb2b + '</p></div></div>';
card += '<div class="col">';
card += '<div class="row"><span class="badge badge-primary">Hardware</span></div>';
card += '<div class="row"><small class="text-muted">CPU</small></div>';
card += '<div class="row"><p class="info">' + cpu + '</p></div>';
card += '<div class="row"><small class="text-muted">MAC</small></div>';
card += '<div class="row"><p class="info">' + mac + '</p></div></div></div>';
$(body).find('.card-body').append(card);
});
},
error: function (error) {
OnFailure(error);
alert('Error');
}
});
}
And called when the according is triggered
$('.accordion').on('show.bs.collapse', function (e) {
var id = $(e.target).attr('id');
var item = '#' + $(e.target).attr('id');
if ($(item).find('.card-body').is(':empty')) {
getBody(item, id);
} else {
}
});
You are going to need to manually trigger the toggle after the data has finished loading, and after you have put your data into the DOM. That means you need to remove the data-target value from your Collapse and manually add the event listener/handler. I wish that there was a pre/post collapse aspect that you could hook to, but there isn't.
Consider the example below that doesn't have the lag you experience.
$("#test-button").click(e => {
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos",
dataType: "json"
}).done(d => {
$("#collapseOne .card-body").text(JSON.stringify(d
, null, 4));
$("#collapseOne").collapse("toggle");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button id="test-button" class="btn btn-link" type="button" data-toggle="collapse" aria-expanded="false" aria-controls="collapseOne">
Collapsible Group Item #1
</button>
</h5>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body"></div>
</div>
</div>
</div>

I want The input value is not cleared when I popup a second time

I want to add html code using append, but when adding a second time, the text in the input does not follow the new line :
HTML :
'<form>' +
'<input type="text" id="newFoldr" name="fname" placeholder=".ex nameFanpage" value="">' +
'<input type="button" class="cancelButton" id="cancelButton" value="Cancel" data-dismiss="modal" aria-label="Close">' +
'<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">' +
'</form>' +
Javascript :
$('.submitButton').click(function () {
var addFolder = '<div class="_5bm7 _2mk4" role="presentation" style="height: 50px;border:none;"><div class="_5bmf"></div>' +
'<div class="_1577">' +
'<div class="ellipsis">' +
'<div class="_1i5z"><div class="_1i5-">' +
'</div>' +
'</div>' +
'<span id="namaFolder"></span>' +
'</div>' +
'</div>' +
'</div>';
if( document.getElementById("newFoldr").value === '' ){
swal("Whoops!", "You need to write something!", "info");
} else {
$('.columnFolder').append(addFolder);
var inputan = document.getElementById("newFoldr").value;
document.getElementById("namaFolder").innerHTML= inputan;
swal("Success!", "Your folder has been created!", "success");
}
});
Screenshot : http://prntscr.com/h1pz43
if you are not able to clear the input value just add below code in else block
document.getElementById("newFoldr").value = "";
Complete javascript code is as below
$('.submitButton').click(function () {
var addFolder = '<div class="_5bm7 _2mk4" role="presentation" style="height: 50px;border:none;"><div class="_5bmf"></div>' +
'<div class="_1577">' +
'<div class="ellipsis">' +
'<div class="_1i5z"><div class="_1i5-">' +
'</div>' +
'</div>' +
'<span></span>' +
'</div>' +
'</div>' +
'</div>';
if( document.getElementById("newFoldr").value === '' ){
swal("Whoops!", "You need to write something!", "info");
} else {
$('.columnFolder').append(addFolder);
var inputan = document.getElementById("newFoldr").value;
$('.columnFolder div._5bm7._2mk4:last').find('span').text(inputan);
document.getElementById("newFoldr").value = "";
swal("Success!", "Your folder has been created!", "success");
}
});

How set default value for dropdown list after it is dynamic download

I try to set default value for dropdown list after it is dynamic download and I do this in the following way:
function editUser() {
// массив для взятий информации о пользователе из таблицы
var userInfo = [];
// $("table").find("tr").each(function () {
//
// if($(this).is(":visible")){
// alert("success");
// console.log("SUCCESS")
// }
// })
var count = 0;
// здесь надо передать одно значение, то есть один ряд с инфой о пользователе иначе кинуть alert
$("table").find("tr").each(function () {
if ($(this).find("input").is(":checked")) {
count++;
}
});
if (count <= 1) {
$("table").find("tr").each(function () {
if ($(this).find("input").is(":checked")) {
$(this).find("td").each(function () {
userInfo.push(this.innerHTML);
})
return false;
}
count = 0;
});
}
else {
alert("Выбрано больше одного значения");
if ($("#tableForUser").length != 0) {
getUsers();
count = 0;
return;
}
if ($("#tableForOwners").length != 0) {
getOwners();
count = 0;
return;
}
if ($("#tableForDrivers").length != 0) {
getDrivers();
count = 0;
return;
}
}
console.log(userInfo);
// alert("SUCCESS");
console.log(listCities);
$("#head").children().remove();
var trHTML = '';
trHTML += '<form id="changeForm" class="form-horizontal" role="form">' +
'<input id="inputID" class="form-control" type="text" style="visibility:hidden">' +
'<div class="form-group">' +
'<label class="col-lg-3 control-label">Ник:</label>' +
'<div class="col-lg-8">' +
'<input id="inputNick" class="form-control" type="text">' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-lg-3 control-label">Имя:</label>' +
'<div class="col-lg-8">' +
'<input id="inputFirstname" class="form-control" type="text">' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-lg-3 control-label">Фамилия:</label>' +
'<div class="col-lg-8">' +
'<input id="inputLastname" class="form-control" type="text" >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-lg-3 control-label">Мобильный телефон:</label>' +
'<div class="col-lg-8">' +
'<input id="inputMobile"class="form-control" type="text">' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-lg-3 control-label">Электронная почта:</label>' +
'<div class="col-lg-8">' +
'<input id="inputEmail" class="form-control" type="text">' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-lg-3 control-label">Город:</label>' +
'<div class="col-lg-8">' +
'<div class="ui-select">' +
'<select id="cities" class="form-control">' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-md-3 control-label">Пароль:</label>' +
'<div class="col-md-8">' +
'<input id="inputPassword1" class="form-control" type="password">' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-md-3 control-label">Подтвердите пароль:</label>' +
'<div class="col-md-8">' +
'<input id="inputPassword2" class="form-control" type="password">' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="col-md-3 control-label"></label>' +
'<div class="col-md-8">' +
// '<input type="button" class="btn btn-primary" onclick="saveChanges();" value="Save Changes">'
'<button type="button" class="btn btn-primary" onclick="saveChanges();">Сохранить</button><br>' +
'<span></span>' +
'<button type="button" class="btn btn-default" onclick="">Отменить</button><br>' +
'</div>' +
'</div>' +
'</form>';
$("#head").append(trHTML);
if (userInfo[1] == null) {
alert("Выберите пользователя для редактирования");
$("#head").children().remove();
}
else {
//Записываем индекс
// massChanges.push(userInfo[0]);
// console.log(massChanges);
$(getCities().done(function () {
document.getElementById("inputID").value = userInfo[0];
document.getElementById("inputNick").value = userInfo[1];
document.getElementById("inputFirstname").value = userInfo[2];
document.getElementById("inputLastname").value = userInfo[3];
document.getElementById("inputMobile").value = userInfo[4];
document.getElementById("inputEmail").value = userInfo[5];
$("#cities").val(userInfo[6]);
// $('cities option:contains(userInfo[6])').prop('selected',true);
document.getElementById("inputPassword1").value = userInfo[7];
document.getElementById("inputPassword2").value = userInfo[7];
userInfo = [];
}))
}
}
where function getCities() declare as:
var listCities = [];
var city;
function getCities() {
$.ajax({
type: "GET",
url: "/admin/getCities",
datatype: "json",
success: function (response) {
$.each(response, function (i, item) {
listCities.push(item);
});
$.each(listCities, function (i, item) {
city += '<option>' + item + '</option>';
})
$("#cities").append(city);
},
error: function () {
alert("error")
}
})
}
But every times I get following error:
Cannot read property 'done' of undefined at editUser. There are any idea how i can solve this problem?
But every times I get following error: Cannot read property 'done' of
undefined at editUser. There are any idea how i can solve this
problem?
You are passing function call of getCities() to jQuery(), which does not have a .done() method. Remove jQuery() wrapper around getCities() call
getCities().done(function(){/* do stuff */})
Also, return $.ajax() call from getCities function
function getCities() {
return $.ajax(/* settings */)
}

JavaScript loop within template

I am trying to make this work but I am clearly doing something wrong which I can't figure out:
function template(data){
var contentString =
'<div id="content">'+
'<div class="left">'+
"<div class='icon'><img src='assets/image/cloudy.png' /></div>"+
'</div>'+
'<div class="right">'+
'<p class="temp">'+data.currently.temperature+'</p>'+
'<p class="summary">'+data.daily.summary+'</p>'+
'</div>'+
'<div class="day_wrapper">'+
for(i = 0; i < data.daily.data.length; i++){
'<div class="day"><p>'+data.daily.data[i].temperatureMax+'</p></div>'+
}
'</div>';
return contentString;
}
Error: Uncaught SyntaxError: Unexpected token for
How can I fix this?
How would I add a 'last' class to the last paragraph in the loop?
function template(data){
var contentString =
'<div id="content">'+
'<div class="left">'+
"<div class='icon'><img src='assets/image/cloudy.png' /></div>"+
'</div>'+
'<div class="right">'+
'<p class="temp">'+data.currently.temperature+'</p>'+
'<p class="summary">'+data.daily.summary+'</p>'+
'</div>'+
'<div class="day_wrapper">';
if(data!=undefined && data.daily.data.length > 0)
{
for(i = 0; i < data.daily.data.length; i++){
contentString += '<div class="day"><p>'+data.daily.data[i].temperatureMax+'</p></div>';
}
}
contentString += '</div>';
return contentString;
}

Categories