Bootstrap Table Load Issues - javascript

I'm having challenges with updating my Bootstrap table using the load method. Even when I simplify the problem and try and update using a single record, nothing changes. I would eventually like to update the data set with the rowData, but I want to get the test_data working first.
Index Page
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>
<body>
<div class="mb-3">
<label for="sequence_input" class="form-label">Sequence Input</label>
<textarea class="form-control" id="sequence_input" rows="3"></textarea>
</div>
<button id="blastButton" type="button" onclick="blast_request();" class="btn btn-primary">Submit Blast Query</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">FASTA Validation</h5>
<button type="button" onclick="$('#exampleModal').modal('toggle')" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
There was an error with the FASTA validation. Please check your input and try again.
</div>
<div class="modal-footer">
<button onclick="$('#exampleModal').modal('toggle')" type="button" class="btn btn-secondary" data-dismiss="modal" data-target="exampleModal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
<!-- Start Table -->
<table
id="table"
class="table table-sm"
>
<thead>
<tr>
<th data-field="id">Hit ID</th>
<th data-field="def">Hit Definition</th>
<th data-field="acc">Hit Accession</th>
</tr>
</thead>
</table>
<!-- End Table -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://unpkg.com/bootstrap-table#1.20.2/dist/bootstrap-table.min.js"></script>
<script src="./script.js"></script>
</body>
</html>
My Script
/*
Function used courtesy of Oxford Protein Informatics Group
https://www.blopig.com/blog/2013/03/a-javascript-function-to-validate-fasta-sequences/
*/
function validateFasta(fasta) {
if (!fasta) { // check there is something first of all
return false;
}
// immediately remove trailing spaces
fasta = fasta.trim();
// split on newlines...
var lines = fasta.split('\n');
// check for header
if (fasta[0] == '>') {
// remove one line, starting at the first position
lines.splice(0, 1);
}
// join the array back into a single string without newlines and
// trailing or leading spaces
fasta = lines.join('').trim();
if (!fasta) { // is it empty whatever we collected ? re-check not efficient
return false;
}
// note that the empty string is caught above
// allow for Selenocysteine (U)
return /^[ACDEFGHIKLMNPQRSTUVWY\s]+$/i.test(fasta);
}
async function blast_request(){
let form_data = document.getElementById("sequence_input").value
let fasta_valid = validateFasta(form_data);
if (fasta_valid){
console.log('FASTA data validates')
try{
let response = await fetch(
'http://localhost:8000/', {
method: 'PUT',
headers: {"Content-type": "application/json"},
body: JSON.stringify({"formInput":form_data})
});
// get blast data
let blastData = await response.json();
console.log("data received", blastData);
// extract relevant fields
let rowData = getRowData(blastData)
console.log("row data ready", rowData);
// load data to table
// $('#table').bootstrapTable('load', rowData)
test_data = [{id:1, def:"definition1", acc:"acc1"}]
$('#table').bootstrapTable('load', test_data)
console.log("data loaded to table")
} catch (error){
console.log(error)
}
} else {
console.log("Input does not validate");
$('#exampleModal').modal('show')
}
}
function getRowData(input){
n = input['data'].length
data = input['data']
console.log(input)
rows = []
for (var i = 0; i<n; i++){
rows.push({
id: data[i]['Hit_id'],
def: data[i]['Hit_def'],
acc: data[i]['Hit_accession']
})
}
return rows
}

Related

How to display a pop up notification laravel using ajax?

How to display a pop-up notification in admin side when a customer click an order?. Now its not getting the pop-up notification?.when inspect the values getting.
var audio = document.getElementById("myAudio");
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
}
Ajax
<script>
setInterval(function () {
$.ajax({
url: '{{route('get-order-data')}}',
dataType: 'json',
success: function (response) {
let data = response.data;
if (data.new_order > 0) {
playAudio();
$('#popup-modal').appendTo("body").modal('show');
}
},
});
}, 1000);
Controller
public function order_data()
{
$new_order = DB::table('orders')->where(['checked' => 0])->count();
return response()->json([
'success' => 1,
'data' => ['new_order' => $new_order]
]);
}
pop up code
<div class="modal" id="popup-modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12">
<center>
<h2 style="color: rgba(96,96,96,0.68)">
<i class="tio-shopping-cart-outlined"></i> You have new order, Check Please.
</h2>
<hr>
</center>
</div>
</div>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function(){
setInterval(function () {
$.ajax({
url: '{{route('get-order-data')}}',
type: 'GET',
dataType: 'json',
success: function (response) {
$.each(response.new_order, function (key, value) {
if (value.new_order > 0) {
playAudio();
$('#popup-modal').modal('show');
}
});
}
});
}, 1000);
});
</script>
Controller
public function order_data()
{
$data = DB::table('orders')->where('checked', 0)->get();
$count = $data->count();
$res['new_order'] = array([
'success' => 1,
'new_order' => $count
]);
return response()->json($res);
}
You are displaying the popup through modal window. You can trigger the modal window through javascript. I hope the below code will be useful for you. Try this code in jsFiddle with jQuery enabled. Append the javascript code inside the ajax code where you need to display the notification.
$('.btn').click(function () {
$("#myModal").modal('show');
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="myModal" class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<button class="btn">
Submit
</button>

How do i fix the result without reloading the site?

Whenever I am writing apple or samsung, It is showing results, but if I don't refresh the page for the second time, it gives me error. However, If I reload the website, then it is showing me the results of samsung or oppo or whatever. Can you please tell me where I made the mistake ? I am attaching the HTML and JS below :
// error handle
const displayHandle = (direction, id) => {
const errorMessage = document.getElementById(id);
errorMessage.style.display = direction;
}
// clear previous result
const clearSearchResult = (direction) => {
const searchResult = document.getElementById(direction);
searchResult.innerHTML = '';
}
// details button action form
const allDetails = (id) => {
// console.log(id)
fetch(`https://openapi.programming-hero.com/api/phone/${id}`)
.then(response => response.json())
.then(data => {
const sensorName = data.data.mainFeatures.sensors;
let storeSensorName = '';
for (const sensor of sensorName) {
storeSensorName = `${storeSensorName} ${sensor}, `
}
const mobileDetails = document.getElementById('show-details');
mobileDetails.innerHTML = `
<div class=" row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card">
<img src=${data.data.image} class="card-img-top w-50 h-50" alt="...">
<div id="details-body" class="card-body">
<h5 class="card-title">Brand: ${data.data.brand}</h5>
<p class="card-text">Storage: ${data.data.mainFeatures.storage}</p>
<p class="card-text">ChipSet: ${data.data.mainFeatures.chipSet}</p>
<p class="card-text">DisplaySize: ${data.data.mainFeatures.displaySize}</p>
<p class="card-text">Sensors : ${storeSensorName}</p>
</div>
</div>
</div>
</div>
`;
// inject release Date
const container = document.getElementById('details-body');
const p = document.createElement('p');
if (data.data.releaseDate) {
p.innerText = `Release Information:${data.data.releaseDate}`;
container.appendChild(p);
} else {
p.innerText = `Release Information Not Found`;
container.appendChild(p);
}
});
}
//search button action form
document.getElementById('search-btn').addEventListener('click', function() {
clearSearchResult('show-details');
clearSearchResult('show-mobile');
displayHandle('none', 'error-message');
displayHandle('none', 'show-all-Button')
// get search field
const searchBox = document.getElementById('search-box');
const searchData = searchBox.value;
fetch(`https://openapi.programming-hero.com/api/phones?search=${searchData}`)
.then(res => res.json())
.then(data => {
if (data.data.length != 0) {
displayMobile(data.data)
} else {
displayHandle('block', 'error-message');
}
})
// clear search field
searchBox.value = ' ';
})
const displayMobile = (mobiles) => {
// console.log(phones);
const showMobile = document.getElementById('show-mobile');
let count = 0;
for (const mobile of mobiles) {
if (count < 20) {
const div = document.createElement('div');
div.classList.add("col");
div.innerHTML = `
<div class="card d-flex align-items-center">
<img src=${mobile.image} class="card-img-top w-50 h-50" alt="...">
<div class="card-body">
<h5 class="card-title">Model : ${mobile.phone_name}</h5>
<p class="card-text">Brand : ${mobile.brand}</p>
<button class="card-button" onclick="allDetails('${mobile.slug}')">Details</button>
</div>
</div>
`;
showMobile.appendChild(div);
} else {
displayHandle('block', 'show-all-Button');
}
count++;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- connection with bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
.display-handle {
display: none;
color: rgb(231, 49, 49);
}
.card-button {
color: white;
background-color: brown;
border-radius: 10px;
}
</style>
</head>
<body>
<!-- search box section
----------------->
<section class="container w-75 mx-auto pt-5">
<h5 id="error-message" class="display-handle text-center">Not found..! Press authentic data...</h5>
<h3 class="text-center bg-dark text-white">Mobile Maya</h3>
<div class="input-group mb-3">
<input id="search-box" type="text" class="form-control" placeholder="Enter your desired mobile " aria-label="" aria-describedby="button-addon2">
<button class="btn btn-success" type="button" id="search-btn">Search</button>
</div>
</section>
<!-- display products details -->
<section id="show-details" class="container">
<!-- inject details here -->
</section>
<!-- search result display section
---------------------------------->
<section class="container pt-5">
<div id="show-mobile" class=" row row-cols-1 row-cols-md-3 g-4">
</div>
</section>
<!-- show all button -->
<section class="container">
<div class="d-flex justify-content-center">
<button style="color: white; background-color:tomato; border-radius: 8px;" id="show-all-Button" class="display-handle" type="button" class="btn btn-primary">Show All</button>
</div>
</section>
<!-- connection with js
----------- -->
<script src="js/app.js"></script>
<!-- connection with bootstrap script -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
It is because of this line, you don't really clear the search field :
// clear search field
searchBox.value = ' ';
You should either assign the empty string value '' or call the method trim() on searchData.

How to load extensions for the Forge Viewer (without a viewerApp)

I'm trying to developp a Forge Autodesk Viewer for a webapp, this tutorial. I have an issue while trying to load extensions, indeed they never load on the viewer.
I've already developped the viewer of the tutorial, and the extensions worked correctly.
The main difference between my viewer and the tutorial's viewer is the use of a viewerApp in the tutorial while I had to use directly a GUIViewer3D (For the aggregation of several models).
I've already tried to load the viewer and the extensions in a different order, but it didn't change worked either. I assumed the code of the extension is correct, since it works in the tutorial, but I'm not sure about how I linked it to my viewer.
The code to load the viewer :
Autodesk.Viewing.Initializer(options, function onInitialized() {
// Initialisation du Viewer
var viewerDiv = document.getElementById('MyViewerDiv');
var config = {
extensions: ['DockingPanelExtension']
};
viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv, config);
viewer.initialize();
});
The code of the index
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<!-- The Viewer CSS -->
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/6.*/style.min.css"
type="text/css">
<!-- Developer CSS -->
<link rel="stylesheet" href="/static/style.css" type="text/css">
<!-- Common packages: jQuery, Bootstrap, jsTree -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.7/jstree.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.7/themes/default/style.min.css" />
</head>
<body>
<!-- Fixed navbar by Bootstrap: https://getbootstrap.com/examples/navbar-fixed-top/ -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<ul class="nav navbar-nav left">
<li>
<a href="http://developer.autodesk.com" target="_blank">
<img alt="IM-Pact" src="static/img/IMPact.png"
height="20">
</a>
</li>
<li>
<button type="button" class="btn btn-default navbar-btn" onClick="callNew()">Add next model</button>
</li>
</ul>
</div>
</nav>
<!-- End of navbar -->
<div class="container-fluid fill">
<div class="row fill">
<div class="col-sm-4 fill">
<div class="panel panel-default fill">
<div class="panel-heading" data-toggle="tooltip">
Buckets & Objects
<span id="refreshBuckets" class="glyphicon glyphicon-refresh" style="cursor: pointer"></span>
<button class="btn btn-xs btn-info" style="float: right" id="showFormCreateBucket"
data-toggle="modal" data-target="#createBucketModal">
<span class="glyphicon glyphicon-folder-close"></span> New bucket
</button>
</div>
<div id="appBuckets">
tree here
</div>
</div>
</div>
<div class="col-sm-8 fill">
<div id="MyViewerDiv"></div>
</div>
</div>
</div>
<form id="uploadFile" method='post' enctype="multipart/form-data">
<input id="hiddenUploadField" type="file" name="theFile" style="visibility:hidden" />
</form>
<!-- Modal Create Bucket -->
<div class="modal fade" id="createBucketModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Cancel">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Create new bucket</h4>
</div>
<div class="modal-body">
<input type="text" id="newBucketKey" class="form-control"> For demonstration purposes, objects
(files) are
NOT automatically translated. After you upload, right click on
the object and select "Translate". Bucket keys must be of the form [-_.a-z0-9]{3,128}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="createNewBucket">Go ahead, create the
bucket</button>
</div>
</div>
</div>
</div>
<!-- <button id="MyNextButton" onClick="callNext()">Next!</button> -->
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js?v=v6.6"></script>
<!-- Developer JS -->
<script src="static/js/docLoad.js"></script>
<script src="static/js/modelLoad.js"></script>
<script src="static/js/extensions/dockingpannelextension.js"></script>
<script src="static/js/viewer.js"></script>
<script src="static/js/tree.js"></script>
</body>
The code of the extension
// *******************************************
// Model Summary Extension
// *******************************************
var propsToList = [];
function addToList(item) {
if (propsToList.includes(item)) {
var index = propsToList.indexOf(item);
propsToList.splice(index, 1);
} else {
propsToList.push(item)
}
console.log(propsToList)
}
function ModelSummaryExtension(viewer, options) {
Autodesk.Viewing.Extension.call(this, viewer, options);
this.panel = null; // create the panel variable
}
ModelSummaryExtension.prototype = Object.create(Autodesk.Viewing.Extension.prototype);
ModelSummaryExtension.prototype.constructor = ModelSummaryExtension;
ModelSummaryExtension.prototype.load = function () {
if (this.viewer.toolbar) {
// Toolbar is already available, create the UI
this.createUI();
} else {
// Toolbar hasn't been created yet, wait until we get notification of its creation
this.onToolbarCreatedBinded = this.onToolbarCreated.bind(this);
this.viewer.addEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, this.onToolbarCreatedBinded);
}
return true;
};
ModelSummaryExtension.prototype.onToolbarCreated = function () {
this.viewer.removeEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, this.onToolbarCreatedBinded);
this.onToolbarCreatedBinded = null;
this.createUI();
};
ModelSummaryExtension.prototype.createUI = function () {
var _this = this;
// prepare to execute the button action
var modelSummaryToolbarButton = new Autodesk.Viewing.UI.Button('runModelSummaryCode');
modelSummaryToolbarButton.onClick = function (e) {
// check if the panel is created or not
if (_this.panel == null) {
_this.panel = new ModelSummaryPanel(_this.viewer, _this.viewer.container, 'modelSummaryPanel', 'Model Summary');
}
// show/hide docking panel
_this.panel.setVisible(!_this.panel.isVisible());
// if panel is NOT visible, exit the function
if (!_this.panel.isVisible()) return;
// ok, it's visible, let's get the summary!
// first, the Viewer contains all elements on the model, including
// categories (e.g. families or part definition), so we need to enumerate
// the leaf nodes, meaning actual instances of the model. The following
// getAllLeafComponents function is defined at the bottom
_this.getAllLeafComponents(function (dbIds) {
// now for leaf components, let's get some properties
// and count occurrences of each value.
// get only the properties we need for the leaf dbIds
_this.viewer.model.getBulkProperties(dbIds, propsToList, function (dbIdsProps) {
// iterate through the elements we found
dbIdsProps.forEach(function (item) {
// and iterate through each property
item.properties.forEach(function (itemProp) {
// now use the propsToList to store the count as a subarray
if (propsToList[itemProp.displayName] === undefined)
propsToList[itemProp.displayName] = {};
// now start counting: if first time finding it, set as 1, else +1
if (propsToList[itemProp.displayName][itemProp.displayValue] === undefined)
propsToList[itemProp.displayName][itemProp.displayValue] = 1;
else
propsToList[itemProp.displayName][itemProp.displayValue] += 1;
});
});
// now ready to show!
// the Viewer PropertyPanel has the .addProperty that receives the name, value
// and category, that simple! So just iterate through the list and add them
propsToList.forEach(function (propName) {
if (propsToList[propName] === undefined) return;
Object.keys(propsToList[propName]).forEach(function (propValue) {
_this.panel.addProperty(
/*name*/
propValue,
/*value*/
propsToList[propName][propValue],
/*category*/
propName);
});
});
})
})
};
// modelSummaryToolbarButton CSS class should be defined on your .css file
// you may include icons, below is a sample class:
modelSummaryToolbarButton.addClass('modelSummaryToolbarButton');
modelSummaryToolbarButton.setToolTip('Model Summary');
// SubToolbar
this.subToolbar = (this.viewer.toolbar.getControl("MyAppToolbar") ?
this.viewer.toolbar.getControl("MyAppToolbar") :
new Autodesk.Viewing.UI.ControlGroup('MyAppToolbar'));
this.subToolbar.addControl(modelSummaryToolbarButton);
this.viewer.toolbar.addControl(this.subToolbar);
};
ModelSummaryExtension.prototype.unload = function () {
this.viewer.toolbar.removeControl(this.subToolbar);
return true;
};
ModelSummaryExtension.prototype.getAllLeafComponents = function (callback) {
var cbCount = 0; // count pending callbacks
var components = []; // store the results
var tree; // the instance tree
function getLeafComponentsRec(parent) {
cbCount++;
if (tree.getChildCount(parent) != 0) {
tree.enumNodeChildren(parent, function (children) {
getLeafComponentsRec(children);
}, false);
} else {
components.push(parent);
}
if (--cbCount == 0) callback(components);
}
this.viewer.getObjectTree(function (objectTree) {
tree = objectTree;
var allLeafComponents = getLeafComponentsRec(tree.getRootId());
});
};
// *******************************************
// Model Summary Panel
// *******************************************
function ModelSummaryPanel(viewer, container, id, title, options) {
this.viewer = viewer;
Autodesk.Viewing.UI.PropertyPanel.call(this, container, id, title, options);
}
ModelSummaryPanel.prototype = Object.create(Autodesk.Viewing.UI.PropertyPanel.prototype);
ModelSummaryPanel.prototype.constructor = ModelSummaryPanel;
Autodesk.Viewing.theExtensionManager.registerExtension('ModelSummaryExtension', ModelSummaryExtension);
Thanks in advance !
In the extension JavaScript file, you're registering the extension under the name ModelSummaryExtension, but in the viewer initialization code you're passing the config object with extensions: ['DockingPanelExtension']. That's likely why the extension isn't loaded. Try initializing the GuiViewer3D class with the following config instead:
let config = {
extensions: ['ModelSummaryExtension']
};
EDIT (after the extension naming has been fixed):
When initializing the GuiViewer3D, call its start() method instead of initialize(). It will internally call initialize() (for initializing internal structures, event handlers, etc.), setUp(); (for configuring the viewer based on your config object), and finally it will call loadModel() if there's a URN or a filepath argument passed to the function.

How to stop my modal from appending new rows?

Table
<table id="fisicHostsTable">
<tr class="row">
<th class="tableHeader">Nombre</th>
<th class="tableHeader">IP</th>
<th class="tableHeaders">Sistema Operativo</th>
<th class="tableHeaders">Notas</th>
</tr>
<th:block th:each="fh : ${datacenterFisicHosts}">
<div>
<tr class="row">
<td id="fisicHostName" th:text="${fh.name}"></td>
<td id="fisicHostIp" th:text="${fh.ip}"></td>
<td id="fisicHostOS" th:text="${fh.operatingSystem}"></td>
<td id="fisicHostNotes" th:text="${fh.notes}"></td>
<td><button class="credentialsButton" th:attr="data-fisic-host-id=${fh.id}">CREDENCIALES</button></td>
</tr>
</div>
</th:block>
</table>
Modal:
<!-- Modal -->
<div class="modal fade" id="credentialsModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-title">Credenciales</h5>
</div>
<div class="modal-body">
<table id="credentialsTable">
<tr class="row">
<th>Usuario</th>
<th>Clave</th>
<th>Notas</th>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
JS
$(".credentialsButton").click(function(){
var fisicHostId = $(this).data('fisic-host-id');
$.get( "/fisicHost/" + fisicHostId + "/credentials", data => {
console.log(data);
for (i = 0; i < data.length; ++i) {
var fisicHost = data[i];
var new_row = document.createElement('tr');
new_row.className = "row fisichost";
var userCol = document.createElement('td');
userCol.textContent = fisicHost["user"];
new_row.append(userCol);
var passwordCol = document.createElement('td');
passwordCol.textContent = fisicHost["password"];
new_row.append(passwordCol);
var notesCol = document.createElement('td');
notesCol.textContent = fisicHost["notes"];
new_row.append(notesCol);
$("#credentialsTable").append(new_row);
}
$('#credentialsModal').modal('show');
$('#credentialsTable').remove(new_row);
}).fail(function(xhr, status, error) {
console.error(error);
alert('No se pudieron cargar las credenciales.');
});
});
The data array looks always like this:
the problem I have is that the credentials are repeating each time I click on the button. I want to show them once, not in a cicle but can't find the way to stop them from cycling !
I've added the remove(new_row) after the modal is showing but it's removing everything !
EDIT:
This is the modal:
I just want to show the first two rows cause there are two credentials I need to show, but as you can see, each time I open the modal the data is repeating itself ... i want to stop that repetition!
I would say, right before the loop for(i= etc, put:
$('#credentialsTable').empty();
Thus you remove all rows before adding.
So put this code just before the loop.
I think you are retrieving credentials and adding them to the table that you have in the modal. The problem is that once you close and open model, previous data is still there and new data is being added. To avoid such situation you need to listen to modal close event and once modal is closed remove added rows.
Something like this:
$('#credentialsModal').bind('hide', function () {
$('#credentialsModal tr.fisichost').remove();
});
You can use the jquery method .one instead of .on to only run a function the first time an event occurs.
$("button").one("click", function() {
console.log("ran only the once");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me</button>

Confirm user from a remote api url in AngularJS?

so, I have this bug in my code, that I can't quite figure it out. So, my app needs to do is to click on the confirm button to remove that user from its list within the remote api url. So, when I click on confirm button, it removes the user from console.log but it does not update the view. So, please check out my code and I will be thankful for your help.
if you are visiting my plunker, please write comments here, so I can know where was the bug fixed. Thanks for your time.
Here is a full plunker: https://plnkr.co/edit/nWFi81KannLcQfratr0t
PS: in the plunker, there is a UI-Bootstrap that it need it to work with it, but plunker did not run with it so, I have comment UI-Bootstrap.
Here is some code
$scope.confirmedAction = function(person) {
var index = $scope.userInfo.lawyers.map(function(e) {
return e.id;
}).indexOf(person.id);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
// console.log($scope.userInfo);
$window.location.href = '#/lawyer';
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
//console.log($scope.userInfo);
}, function (error) {
console.log(error)
});
}
});
The user isn't removed because you are removing it form client side but you didn't update the sever with the changes so after the delete the the page is reloading the data again from the server which will be the full array.
You should send this removed user back to server
Notice: the UI-Bootstrap you removed prevent the modal from injecting, but i can see the value throw the console.log
This is a full sample acutlly i used bootstrap framework in the view to handle the confirm dialog.
When user click on a item we should select it as target in this sample
our target detect by $scope.selectUser() function, after that and
when delete is confirmed we use splice the target from our array
by detect the index of the target
var app = angular.module("app", []);
app.controller("ctrl", ["$scope", function($scope) {
$scope.users = [{
name: "John"
},
{
name: "Mike"
}
];
$scope.selectUser = function(user) {
$scope.userIs = user;
}
$scope.deleteConfirmed = function() {
$scope.users.splice($scope.users.indexOf($scope.userIs), 1);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div ng-app="app" ng-controller="ctrl">
<br />
<div class="col-lg-4 col-lg-offset-4">
<ul class="list-group">
<li class="list-group-item" ng-repeat="user in users">
{{user.name}}
<a data-toggle="modal" data-target="#myModal" class="text-danger pull-right" ng-click="selectUser(user)">Delete</a>
</li>
</ul>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete...</h4>
</div>
<div class="modal-body">
Are you sure want delete user "{{userIs.name}}"?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="deleteConfirmed()" data-dismiss="modal">do it</button>
</div>
</div>
</div>
</div>
</div>

Categories