I'm Trying to Implement an accordion list. So basically this a bootstrap accordion. The title of the accordion is already set by PHP. When the user clicks the accordion it must display list of the session that is coming from server. I am using an ajax call for this, the issue every time I click the accordion only first elements get the results. Other elements didn't get the result just a blank view is displayed. I am fairly new to jquery. Here is my Html Code
<div class="accordion" id="myAccordion">
<?php foreach($modules as $module): ?>
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button id="<?php echo $module->id;?>" type="button" class="btn" data-toggle="collapse"
data-target="#collapse<?php echo $module->id; ?>"><?php echo $module->module_name; ?></button>
</h2>
</div>
<div id="collapse<?php echo $module->id; ?>" class="collapse" aria-labelledby="headingOne"
data-parent="#myAccordion">
<div class="card-body">
<ul id="sessionlist" class="list-group list-group-flush">
<li class="list-group-item">
<i class="icon-play_circle_outline text-blue"></i>'+data[i].session_name+'' +
</li>
</ul>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
This is my Jquery and ajax code
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$.ajax({
url: "<?php echo base_url(); ?>dashboard/displaysession/" + this.id,
type: 'GET',
data: {},
error: function () {
alert('Something is wrong');
},
success: function (data) {
for (var i = 0; i < data.length; i++) {
var myhtmlstring = '<li class="list-group-item">' +
'<i class="icon-play_circle_outline text-blue"></i><a href="#">' +
data[i].session_name + '</a>' +
'</li>';
console.log($.parseHTML(myhtmlstring));
$("#sessionlist").append($.parseHTML(myhtmlstring));
}
},
dataType: 'json'
});
});
});
</script>
Really appricate your help
You need to give your sessionlists unique ids aswell. Because when you append your myhtmlstring to #sessionlist it only ever takes the first one.
<ul id="sessionlist<?php echo $module->id; ?>" class="list-group list-group-flush">
<li class="list-group-item">
<i class="icon-play_circle_outline text-blue"></i>'+data[i].session_name+'' +
</li>
</ul>
then you can append it to the right sessionlist in your ajax success:
<script type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
const currentModuleId = this.id
$.ajax({
url: "<?php echo base_url(); ?>dashboard/displaysession/" + currentModuleId ,
type: 'GET',
data: {},
error: function () {
alert('Something is wrong');
},
success: function (data) {
$("#sessionlist" + currentModuleId ).html("");
for (var i = 0; i < data.length; i++) {
var myhtmlstring = '<li class="list-group-item">' +
'<i class="icon-play_circle_outline text-blue"></i><a href="#">' +
data[i].session_name + '</a>' +
'</li>';
console.log($.parseHTML(myhtmlstring));
$("#sessionlist" + currentModuleId ).append($.parseHTML(myhtmlstring));
}
},
dataType: 'json'
});
});
});
</script>
I implemented the creation of tables (based od Datatables library). The strange thing is that I getting DataTables warning: (table id=scoringTableI - Cannot reinitialize DataTable on my server) on the server-side but on the localhost everything works perfectly. Bellow text is PrintScreen and my source code. Does anyone know where is a problem?
scoringDetailView.js
/*
timer to reinit datatable after it is properly loaded
*/
var reinitInterval;
var scoreDown = false;
const scaleHeight = 20; // Height of the canvases on which to draw the score scales
const sliderHeight = 15; // Height of the slider controlling the scores
$(document).ready(function() {
console.log('document ready');
initTables();
reinitScoringTable();
initSliders();
$('.alert-dismissable').delay(2500).fadeOut();
$('[data-toggle="popover"]').popover();
$(document).keydown(function(event) { // bind function called when key is released
if (event.keyCode == 16){
scoreDown = true;
}
});
$(document).keyup(function() { // click method to call keydown() function
scoreDown = false;
});
});
/*
init all tables for the first time
*/
function initTables(){
$( ".table-bordered" ).each(function( index ) {
var id = '#' + this.getAttribute('id');
initTable(id);
console.log(id);
if($(this).has('input.score-slider').length){
// Add event listener to recalculate slider size on data table column width change
$(this).on('column-sizing.dt', function (){
initSliders();
});
}
// reinit table page to avoid empty buttons
$(id).on( 'page.dt', function () {
var reinitInterval = setInterval(function(){ reinitScoringTable() }, 10);
});
//reinit table on click of the first field.
//If the table shrunk due to the responsiveness the expanding buttons
//is placed there
$(id).DataTable().on( 'select', function ( e, dt, type, indexes ) {
dt.deselect();
if ( dt[0][0].column == 0) {
reinitScoringTable();
}
});
});
}
/*
options of one single table
*/
function initTable(id){
console.log('initTable(id=' + id + ')');
$(id).DataTable({
paging : true,
lengthChange: true,
pageLength : 10,
searching : true,
ordering : true,
info : true,
autoWidth : false,
responsive : true,
aaSorting : [],
language: {
paginate: {
previous: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
next: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
}
},
lengthMenu : [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
select: {
style: 'single',
items: 'cell'
},
dom: "<'row'<'col-12 col-sm-12 col-md-12 col-lg-12 additional-buttons'B><'float-right col-12 col-sm-8 col-md-8 col-lg-8'f><'col-12 col-sm-4 col-md-4 col-lg-4'l>>" +
"<'row'<'col-md-12't>><'row'<'col-md-12'ip>>",
buttons: [
{
extend: 'pdf',
className: 'btn btn-default h-spacer-3',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
className: 'btn btn-default h-spacer-3',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excel',
className: 'btn btn-default h-spacer-3',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csv',
className: 'btn btn-default h-spacer-3',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'copy',
className: 'btn btn-default h-spacer-3',
exportOptions: {
columns: ':visible'
}
},
]
});
console.log('initTable(id=' + id + ')' + ' finished');
}
/*
fixes detached buttons, corrects displayed values in table buttons,
recalculates responsive table
*/
function reinitScoringTable() {
console.log('reinitScoringTable()');
clearInterval(reinitInterval);
$( ".table-bordered" ).each(function( index ) {
var id = '#' + this.getAttribute('id');
$(id).DataTable().columns.adjust().responsive.recalc();
});
//rebind all buttons. Used for AOI scoring
$('.btn-scoring').unbind();
$('.btn-scoring').click(function() {
var form = $($(this).attr('form-id'));
var typeId = form.attr('type-id');
var min = parseFloat(form.attr('min'));
var max = parseFloat(form.attr('max'));
var stepsize = parseFloat(form.attr('stepsize'));
var view = $(this).attr('view');
//will only be executed in the beginning and will update all scores to minimum
if(isNaN(parseFloat(form.val()))){
var newVal = min;
//updates the rest of the row
$('.' + form.attr('class').split(' ').join('.')).each(function( index ) {
$(this).val(parseFloat($(this).attr('min')));
updateButtons();
});
}else{
//normal increment by stepsize
var val = parseFloat(form.val()) == 0 ? form.val() : parseFloat(form.val()) || min;
if(scoreDown){
a = val-min-stepsize
b = max-min+stepsize
var newVal = ((a%b)+b)%b+min;
}else {
var newVal = (val-min+stepsize)%(max-min+stepsize)+min;
}
}
form.val(newVal);
updateSystemScores(form.attr('class'), form, view);
setTypeLabel(typeId, (newVal-min)/stepsize, this, newVal);
});
// Slider for image scoring
$('.score-slider').off("input change");
$('.score-slider').on('input change', function(){
var newVal = $(this).val();
var form = $($(this).attr('form-id'));
var typeId = form.attr('type-id');
var min = parseFloat($(this).attr('min'));
var stepsize = parseFloat($(this).attr('step'));
var label = $($(this).parent().parent().find('.score-label'));
// If no score was saved yet, initialise all to minimum
if(isNaN(parseFloat(form.val()))){
$('.' + form.attr('class').split(' ').join('.')).each(function(){
$(this).val(parseFloat($(this).attr('min')));
});
// Set the current one to the new value
form.val(newVal);
updateSliderLabels();
} else {
form.val(newVal);
}
setTypeLabel(typeId, (newVal-min)/stepsize, label, newVal);
// The saving of the new score is only done on slider release
if(event.type == 'change'){
var view = $(this).attr('view');
updateSystemScores(form.attr('class'), form, view);
}
})
updateButtons();
updateAllSystemScorings();
}
//set values of all buttons in table
function updateButtons(){
$( ".btn-scoring" ).each(function( index ) {
var form = $($(this).attr('form-id'));
if(isNaN(parseFloat(form.val()))){
$(this).html('n.d.');
}else{
var typeId = form.attr('type-id');
var val = parseFloat(form.val()) || 0;
var min = parseFloat(form.attr('min'));
var max = parseFloat(form.attr('max'));
var stepsize = parseFloat(form.attr('stepsize'));
setTypeLabel(typeId, (val-min)/stepsize, this, val);
}
});
}
/*
* Set values for all slider labels
*/
function updateSliderLabels(){
$('.score-slider').each(function(){
var form = $($(this).attr('form-id'));
var label = $($(this).parent().parent().find('.score-label'));
// If no value for this type yet, label is 'n.d.'
if(isNaN(parseFloat(form.val()))){
label.html('n.d.');
} else { // Else set label to current value
var val = parseFloat(form.val()) || 0;
setTypeLabel(form.attr('type-id'), (val - parseFloat($(this).attr('min'))/parseFloat($(this).attr('step'))), label, val);
}
})
}
// recalc responsive on resizing
$(window).resize( function(){
if(document.readyState === 'complete'){
reinitScoringTable();
}
});
/*
Save type scores, recalculate system score and load the result
*/
function updateSystemScores(rowClass, form, view){
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-spinner fa-spin scoring-status-symbol');
var data = $('.' + rowClass.split(' ').join('.')).serialize() + "&imageId=" + $('#image_id').attr('value');
if(form[0].hasAttribute('subSystem-id')){
data = data + '&subSystemId=' + form.attr('subSystem-id');
}
$.ajax({
type: 'POST',
url: "/scoring/systemscore",
data: data,
success: function(data, textStatus, xhr){
if(xhr.status == 200){
var scores = data[0];
var summary = data[1];
// Refill the score system scores with the new calculated scores
for (var score in scores) {
$(form.attr('score-ref') + '_' + scores[score]['score_system_id']).attr('value',scores[score]['result']);
}
updateAllSystemScorings();
// Reload summary view
$("#summary-pane" + view).html(summary);
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-check scoring-status-symbol');
}else{
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-exclamation scoring-status-symbol');
}
},
error: function() {
console.log("AJAX save failed")
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-exclamation scoring-status-symbol');
}
});
}
/**
* sets right system scores in scoring tables
*/
function updateAllSystemScorings(){
$( ".lab-scoring" ).each(function( index ) {
var form = $($(this).attr('form-id'));
var val = form.attr('value');
$(this).html(val);
});
}
/*
reinit on tab change
*/
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
reinitScoringTable();
});
/**
* Delete image (div_id = I) or AOI (div_id = AOI) scores
* #param String div_id, indicates if request for deletion is coming from AOI or Image
* #param Int subSystemId potential subSystem to delete the scores from
*/
function deleteScores(div_id, subSystemId = null){
if(subSystemId){
var url = '/scoring/deletetimepointscores/';
url = url + $('#image_id').attr('value') + '/' + subSystemId;
} else {
var url = (div_id.indexOf('AOI') !== -1) ? '/scoring/deleteaoiscores/' : '/scoring/deleteimgscores/';
url = url + $('#image_id').attr('value');
}
$('.active .scoring-status-symbol').attr('class', 'fa fa-spinner fa-spin scoring-status-symbol');
$.ajax({
type: 'POST',
url: url,
success: function(data, textStatus, xhr){
console.log('Ajax successful');
$('.active .scoring-status-symbol').attr('class', 'fa fa-exclamation scoring-status-symbol');
if(xhr.status == 200){
var summary = data[0];
var score_labels = data[1];
$('#summary-pane' + div_id).html(summary);
$('#scoringTable' + div_id).find('.btn-scoring').each(function(index){
var form = $($(this).attr('form-id'));
// Reset buttons to n.d
$(this).html('n.d.');
form.val('n.d');
// Reset labels to minimum values
for (var score_label in score_labels) {
$(form.attr('score-ref') + '_' + score_labels[score_label][0]).attr('value', score_labels[score_label][1]);
}
});
if(subSystemId){
var scoringTableId = '#scoringTable' + subSystemId;
} else {
var scoringTableId = '#scoringTable' + div_id;
}
$(scoringTableId).find('.score-slider').each(function(index){
var form = $($(this).attr('form-id'));
var typeId = form.attr('type-id');
// Set slider to minimun
setSliderToMin($(this));
form.val('n.d');
$($(this).parent().parent().find('.score-label')).html('n.d.');
for (var score_label in score_labels) {
$(form.attr('score-ref') + '_' + score_labels[score_label][0]).attr('value', score_labels[score_label][1]);
}
})
updateAllSystemScorings();
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-check scoring-status-symbol');
}else{
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-exclamation scoring-status-symbol');
}
},
error: function(){
console.log('Ajax failed');
$('.active .scoring-status-symbol').attr( "class" , 'fa fa-exclamation scoring-status-symbol');
}
});
}
/*
* Display modal for delete confirm and callback the delete function
* #param element: button triggering the function
* #param text: description text to display in the delete modal
* #param title: title for the delete modal
* remark: text and title should not be undefined, otherwise the modal message will not be related to its function anymore
*/
function ConfirmDeleteScores(element, text, title)
{
setUpDeleteScoresModal(text, title);
var div_id = (element.id).replace('delete-scores', ''); // check if AOI or image scores
$('#confirm-delete-modal').find('.modal-footer #modal-delete-btn').on('click', function(){
$("#confirm-delete-modal").modal("hide");
deleteScores(div_id, element.getAttribute('subSystem'));
return true;
});
return false;
}
$("#delete-scoresAOI").unbind();
$("#delete-scoresI").unbind();
documentation.blade.php
#if($scoreConfig->scoring_enabled)
<div class="row">
<div class="card ml-2" style="width: 100%;">
<div class="card-body" id="score-button-small" style="height: 10px;">
<button class="btn btn-box-tool collapse-tab-content float-right" href="#note-tabs">
<i style="color: #1e88e5;" class="fa fa-minus"></i>
</button>
</div>
<div class="card-body">
<div class="row">
<div class="nav-tabs-custom nav-tabs-documentation" style="width: 100%;">
<ul class="nav nav-tabs customtab" id="score-tabs">
#php
$activePane = "active";
#endphp
#if($scoreConfig->scoring_enabled && $scoreConfig->image_based_score)
<li class="nav-item {{$activePane}}">
#php
$activePane = "";
#endphp
<a class="nav-link active" href="#{{trans('scoring.scoring')}}" data-toggle="tab" aria-expanded="true">
<span data-toggle="tooltip" data-placement="top" title="{{trans('scoring.scoring_per_img')}}">
<span class="hidden-lg-up">ScI <i class="fa fa-check scoring-status-symbol"></i></span> </span>
<span class="hidden-md-down">{{trans('scoring.scoring_per_img')}} <i class="fa fa-check scoring-status-symbol"></i></span>
</a>
</li>
#if(in_array(\Auth::user()->userGroup->id,config('usergroups.summaryScoring')))
<li class="nav-item">
<a class="nav-link" href="#summary-paneI" data-toggle="tab" aria-expanded="true">
<span data-toggle="tooltip" data-placement="top" title="{{trans('scoring.summary_per_img')}}">
<span class="hidden-lg-up">SuI</span> </span>
<span class="hidden-md-down">{{trans('scoring.summary_per_img')}}</span>
</a>
</li>
#endif
#endif
#if($scoreConfig->scoring_enabled && $scoreConfig->aoi_based_score)
<li class="nav-item {{$activePane}}">
<a class="nav-link" href="#{{trans('scoring.scoring')}}-aoi" data-toggle="tab" aria-expanded="true">
<span data-toggle="tooltip" data-placement="top" title="{{trans('scoring.scoring_per_AOI')}} ">
<span class="hidden-lg-up">ScA <i class="fa fa-check scoring-status-symbol"></i></span> </span>
<span class="hidden-md-down">{{trans('scoring.scoring_per_AOI')}} <i class="fa fa-check scoring-status-symbol"></i></span>
</a>
</li>
#if(in_array(\Auth::user()->userGroup->id,config('usergroups.summaryScoring')))
<li class="nav-item ">
<a class="nav-link" href="#summary-paneAOI" data-toggle="tab" aria-expanded="true">
<span data-toggle="tooltip" data-placement="top" title="{{trans('scoring.summary_per_AOI')}} ">
<span class="hidden-lg-up">SuA</span> </span>
<span class="hidden-md-down">{{trans('scoring.summary_per_AOI')}}</span>
</a>
</li>
#endif
#endif
<div class="box-tools ml-auto" id="score-button-big">
<button class="btn btn-box-tool collapse-tab-content" href="#note-tabs">
<i style="color: #1e88e5;" class="fa fa-minus"></i>
</button>
</div>
</ul>
<div class="tab-content" id="note-tabs">
#php
$activePane = "active";
#endphp
#if($scoreConfig->scoring_enabled && $scoreConfig->image_based_score)
<div class="tab-pane {{$activePane}}" id="{{trans('scoring.scoring')}}">
#php
$activePane = "";
#endphp
#if($scoreConfig->scoreSuperSystem)
#include('scoring.image.subsystem')
#elseif($scoreConfig->types->isEmpty())
#include('scoring.demo.scoring')
#else
#include('scoring.image.scoring')
#endif
</div>
<div class="tab-pane" id="summary-paneI">
#if($scoreConfig->scoreSuperSystem)
#include('scoring.image.subsystemsummary')
#elseif($scoreConfig->types->isEmpty())
#include('scoring.demo.summary')
#else
#include('scoring.image.summary')
#endif
</div>
#endif
#if($scoreConfig->scoring_enabled && $scoreConfig->aoi_based_score)
#php
$demoAOI = 1;
#endphp
<div class="tab-pane {{$activePane}}" id="{{trans('scoring.scoring')}}-aoi">
#if($scoreConfig->types->isEmpty())
#include('scoring.demo.scoring')
#else
#include('scoring.aoi.scoring')
#endif
</div>
<div class="tab-pane" id="summary-paneAOI">
#if($scoreConfig->types->isEmpty())
#include('scoring.demo.summary')
#else
#include('scoring.aoi.summary')
#endif
</div>
#endif
</div>
</div>
</div>
#endif
</div>
</div>
</div>
<link rel="stylesheet" type="text/css" href="{{asset('/plugins/DataTablesBootstrap4/bootstrap4.min.css') }}"/>
<link rel="stylesheet" type="text/css" href="{{asset('/plugins/DataTablesBootstrap4/responsive.bootstrap4.min.css') }}"/>
<link rel="stylesheet" type="text/css" href="{{asset('/plugins/DataTablesBootstrap4/datatables.min.css') }}"/>
<script src="{{asset('/plugins/DataTablesBootstrap4/jquery.dataTables.min.js') }}"></script>
<script src="{{asset('/plugins/DataTablesBootstrap4/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{asset('/plugins/DataTablesBootstrap4/dataTables.responsive.min.js') }}"></script>
<script src="{{asset('/plugins/DataTablesBootstrap4/responsive.bootstrap4.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('/plugins/datatables/1.10.16/datatables.min.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/dataTables.buttons.min.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/buttons.flash.min.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/jszip.min.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/pdfmake.min.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/vfs_fonts.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/buttons.html5.min.js') }}"></script>
<script type="text/javascript" src="{{asset('/plugins/DataTablesBootstrap4/buttons.print.min.js') }}"></script>
<script src="{{ asset('/js/jquery.form.js') }}"></script>
<script src="{{ asset('/js/scoring/scoringDetailView.js?v=2.25.0') }}"></script>
<script src="{{ asset('/js/scoring/scoring.js?v=2.25.0') }}"></script>
scoring.blade.php
<style>
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
.dataTables_wrapper {
width: 100%;
}
</style>
{!! Form::open(['route' => ['documentation.scoring.scoring',$image->id], 'onSubmit' => '$.fn.showPleaseWait();', 'id' => 'scoringFormI']) !!}
<div style='position: absolute; visibility: hidden'>
#foreach ($scoreConfig->types as $type)
{!! Form::number('scoring',
$value = $prevScoresI->isEmpty() ? 'n.d.' : $prevScoresI->get($type->id)->score ,
['min' => $type->min, 'max' => $type->max,'stepsize' => $type->stepsize,
'class' => 'btn btn-default btn-datarow-image',
// id : id which is set as form-id in the according button,
// number code is the same as in the name field
'id' => 'scores'.$type->id,
// href to the system score div
'score-ref' => '#systemScoreImage',
// array field in which the score is saved
'name' => 'scores['.$type->id.']',
'type-id' => $type->id,
'style' => 'outline: none; visibility: hidden','required','readonly']) !!}
#endforeach
#if ($systemScoresI->count())
#foreach ($systemScoresI as $key => $scoreI)
<div id="systemScoreImage_{{$scoreI->systemScore->scoreSystem->id}}" style="visibility: hidden;" value="
{{ $scoreI->systemScore->result($scoreI, $scoreI->systemScore->scoreSystem->style->name) }}"></div>
#endforeach
#else
#foreach ($scoreConfig->scoreSystems as $key => $systems)
<div id="systemScoreImage_{{$systems->id}}" style="visibility: hidden;" value="
{{$systems->scoreSystemScores[0]->result(NULL, $systems->style->name)}}"></div>
#endforeach
#endif
</div>
<div class="card-body">
<div class="row">
<div class="table-responsive">
<table id='scoringTableI' class="table table-striped table-bordered">
<thead>
<tr>
<th style="width: 30%">{{trans('scoring.parameter')}}</th>
<th>{{trans('scoring.score')}}</th>
</tr>
</thead>
<tbody>
#foreach ($scoreConfig->types as $type)
<tr>
<!-- If the type has a description, show it, otherwise show the name -->
#if(isset($type->description))
<th title="{{$type->name}}">{{$type->description}} ({{$type->min}}-{{$type->max}})</th>
#else
<th>{{$type->name}} ({{$type->min}}-{{$type->max}})</th>
#endif
<td>
<div class="row">
<!-- The JS of this view relies on the position of the slider and its label in the DOM.
If the DOM structure is changed, please update the JS file accordingly
regarding the slider event listener which also updates the label -->
#php
if($prevScoresI->isEmpty()){
$savedScore = 'n.d.';
$hasScore = false;
} else {
$savedScore = $prevScoresI->get($type->id)->score;
$hasScore = true;
}
$savedScore = $prevScoresI->isEmpty() ? 'n.d.' : $prevScoresI->get($type->id)->score;
#endphp
<div class="col-lg-9 col-md-6 col-sm-6 col-xs-12">
<canvas class="score-scale" style="position: absolute"></canvas>
<input style="position: inherit; width: 80%;" class="score-slider" type="range" min="{{$type->min}}" max="{{$type->max}}" step="{{$type->stepsize}}" value="#if($hasScore){{$savedScore}}#else{{$type->min}}#endif" style=" position: absolute;" view="I" form-id="{{'#scores'.$type->id}} "class="form-control-range">
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
<label class="score-label float-right">{{$savedScore}} #if(count($type->labels) && $hasScore)({{$type->labels->where('type_index', ($savedScore - $type->min) / $type->stepsize)->pluck('label')->first()}})#endif </label>
</div>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#if($scoreConfig->scoreSystems->count())
<div class="row">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th style="width: 30%">{{trans('scoring.scoreSystem')}}</th>
<th>{{trans('scoring.score')}}</th>
</tr>
</thead>
<tbody>
#foreach ($scoreConfig->scoreSystems as $key => $system)
<tr>
<td>{{$system->name}}</td>
<td><label class="lab-scoring" form-id="#systemScoreImage_{{$system->id}}"></label></td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
{!! Form::close() !!}
<div class ='card-footer' style="background-color: white;">
<div class="row justify-content-center">
<div class='col-md-2'>
<button id='delete-scoresI' class='btn btn-default btn-2icons btn-wrapper' onclick="return ConfirmDeleteScores(this, '{{trans('modals.delete_current_image_scores')}}', '{{trans('modals.delete_current_image_scores_title')}}')" data-toggle='tooltip' data-placement='top' title="{{trans('tooltips.delete_current_image_scores')}}">
<i class='fa fa-trash'></i>
</button>
</div>
</div>
</div>
<div id="appFeatureimg" class="carousel slide">
<div class="carousel-inner row w-100 mx-auto">
<div class="carousel-item col-md-3 col-sm-3 col-3" :class= "{active: index==0 }" v-for="(screenshot,index) in app_details.screenshots">
<div class="panel panel-default">
<div class="panel-thumbnail">
<a href="#" class="thumb">
<img class="img-fluid mx-auto d-block" :src="screenshot"alt="slide 1" >
</a>
</div>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#appFeatureimg" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next text-faded" href="#appFeatureimg" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
This is my html where i generate carousel item
<script>
vue js code goes here
</script>
and other js code
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.13.0/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
$( document ).ready(() => {
console.log('ready');
$('#appFeatureimg').on('slide.bs.carousel', (e) => {
console.log('ready2');
var $e = $(e.relatedTarget);
var idx = $e.index();
var itemsPerSlide = 4;
var totalItems = $('.carousel-item').length;
if (idx >= totalItems-(itemsPerSlide-1)) {
var it = itemsPerSlide - (totalItems - idx);
for (var i=0; i<it; i++) {
// append slides to end
if (e.direction=="left") {
$('.carousel-item').eq(i).appendTo('.carousel-inner');
}
else {
$('.carousel-item').eq(0).appendTo('.carousel-inner');
}
}
}
});
});
</script>
and this is my jQuery for carousel.
After document.ready function I get my console print but bootstrap event slide.bs.carousel is not firing.
i put those code before my vue js and other script but no result.
any suggestion will be really appreciable.
Move this
$( document ).ready(() => {
console.log('ready');
$('#appFeatureimg').on('slide.bs.carousel', (e) => {
console.log('ready2');
var $e = $(e.relatedTarget);
var idx = $e.index();
var itemsPerSlide = 4;
var totalItems = $('.carousel-item').length;
if (idx >= totalItems-(itemsPerSlide-1)) {
var it = itemsPerSlide - (totalItems - idx);
for (var i=0; i<it; i++) {
// append slides to end
if (e.direction=="left") {
$('.carousel-item').eq(i).appendTo('.carousel-inner');
}
else {
$('.carousel-item').eq(0).appendTo('.carousel-inner');
}
}
}
});
to the mounted section of vue js component
Can I know how can we append the title and message to the div using jquery for every row? The issue with my code is that each of the data is not being displayed in a row.
<!--
For instance: Title1
Message1
Title2
Message2 -->
<div class="widget-box">
<div class="widget-title bg_lo" data-toggle="collapse" href="#collapseG3" > <span class="icon"> <i class="icon-chevron-down"></i> </span>
<h5>Topic</h5>
</div>
<div id="announcement" class="widget-content nopadding updates collapse in" id="collapseG3">
<div class="new-update clearfix">
<div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div>
</div>
</div>
</div>
<script>
$.ajax({
url: '/test/back-api/admin/announcements',
method: 'GET',
success: function(d){
if(d.result){
var posts = d.data;
for(var i=0; i < posts.length; i++){
var post = posts[i];
$('#announcement').append(post.title, post.message);
}
}else{
$('#announcement').append("<div> </div>");
}
}
});
</script>
Here is a snippet showing the use case
SNIPPET
var message_container = '<div class="new-update clearfix"><div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div></div>';
$("#add").on('click',function(){
var message= $(message_container);
var post = { title: "<h1>title</h1>", message: "<p>message</p>"};
message.find('#title').append(post.title);
message.find('#message').append(post.message);
$("#announcement").append(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-box">
<div class="widget-title bg_lo" data-toggle="collapse" href="#collapseG3" > <span class="icon"> <i class="icon-chevron-down"></i> </span>
<h5>Topic</h5>
</div>
<div id="announcement" class="widget-content nopadding updates collapse in" id="collapseG3">
</div>
</div>
<button id="add">Add</button>
You can do the same thing in ajax
var message_container = '<div class="new-update clearfix"><div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div></div>';
$.ajax({
url: '/test/back-api/admin/announcements',
method: 'GET',
success: function(d) {
if (d.result) {
var posts = d.data;
for (var i = 0; i < posts.length; i++) {
var post = posts[i];
var message = $(message_container);
message.find('#title').append(post.title);
message.find('#message').append(post.message);
$("#announcement").append(message);
}
});
Looks to me like your markup isn't going to work very well if you're working with a collection of records. What you're likely to end up with the way you're going is something like...
<!-- Title1
Title2
Message1
Message2 -->
Change your code up a little so that you can add to the markup for each record:
$.ajax({
url: '/test/back-api/admin/announcements',
method: 'GET',
success: function(d){
if(d.result){
var posts = d.data;
for(var i=0; i < posts.length; i++){
var post = posts[i];
var Title = "<div class=\"title\">" + post.title + "</div>";
var Message = "<div class=\"message\">" + post.message + "</div>";
$('#announcement').append(Title, Message);
}else{
$('#announcement').append("<div> </div>");
}
});
I'm trying to retrive data from a database but I get the error “Resource interpreted as Document but transferred with MIME type application/json: "http://127.0.0.1:8000/"”.
Page loads with JSON array.
[{"id":1,"pic":"C:\\Users\\extra\\Downloads","type":"img","events_id":1,"created_at":"2017-04-18 19:16:02","updated_at":"2017-04-18 19:16:02","event":null},{"id":2,"pic":"background-pics-12.jpg","type":"img","events_id":2,"created_at":"2017-04-18 19:16:02","updated_at":"2017-04-18 19:16:02","event":null}]
I'm unable to use data to insert it in any tags. This is the code of the view.
<section class="no-padding" id="media">
<div class="container-fluid">
<ul id="hexGrid">
<!--#foreach($items as $item)
<li class="hex">
<div class="hexIn">
<a class="hexLink" href="#" id="{{$item->id}}" role="button" data-toggle="modal" data-dismiss="modal" data-target="#myModal">
<img src="{{$item->pic}}" alt="" />
<h1>sdfghjk</h1>
<p>Some sample text about the article this hexagon leads to</p>
</a>
</div>
</li>
#endforeach
-->
</ul>
</div>
</section>
<!-- Trigger the modal with a button -->
<!-- <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-dismiss="modal" data-target="#myModal">Open Modal</button>-->
<!-- Modal -->
<div class="modal fade" hidden="true" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="panel panel-filled">
<div class="panel-body">
<div class="modal-header">Events</div>
<div class="modal-body">
<div id="myCarousel" class="carousel slide" data-ride="carousel" >
<!-- Indicators -->
</div>
</div>
</div>
<script>
var xmlhttp;
xmlhttp = new XMLHttpRequest();
// var xhttp1=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if(this.readyState==4 && this.status==200)
{
var arr=JSON.parse(this.responseText);
console.log(arr.result.length);
console.log(arr);
var count=arr.result.length;
if(count!=0)
{
for(var i=0;i<count;i++)
{
if(arr.result[i].Type=='img')
{ var listelement=document.createElement("LI");
listelement.setAttribute('id', arr.result[i].ID);
listelement.className += "hex";
var div=document.createElement("div");
div.className += "hexIn";
var image=document.createElement("img");
var heading=document.createElement("h1");
var parag=document.createElement("p");
image.src=arr.result[i].image.replace("\\","");
heading.innerHTML=arr.result[i].Date; //content of heading
parag.innerHTML=arr.result[i].Name;
var anchor=document.createElement("a");
anchor.className += "hexLink";
anchor.setAttribute('href',"#");
anchor.appendChild(image);
anchor.appendChild(heading);
anchor.appendChild(parag);
div.appendChild(anchor);
listelement.appendChild(div);
var ule=document.getElementById("hexGrid");
ule.appendChild(listelement);
anchor.onclick = function(){
};
}
else {var listelement=document.createElement("LI");
listelement.setAttribute('id', arr.result[i].ID);
listelement.className += "hex";
var div=document.createElement("div");
div.className += "hexIn";
var image=document.createElement("iframe");
var heading=document.createElement("h1");
var parag=document.createElement("p");
var divv=document.createElement("div");
image.style["width"] = "auto";
image.style["height"] = "auto";
image.src=arr.result[i].image.replace("\\","");
heading.innerHTML=arr.result[i].Date; //content of heading
parag.innerHTML=arr.result[i].Name;
var anchor=document.createElement("a");
anchor.className += "hexLink";
anchor.setAttribute('href',"#");
divv.appendChild(image);
anchor.appendChild(divv);
anchor.appendChild(heading);
anchor.appendChild(parag);
div.appendChild(anchor);
listelement.appendChild(div);
var ule=document.getElementById("hexGrid");
ule.appendChild(listelement);}
}
}
else { var parag=document.createElement("p");parag.innerHTML="nmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmo";
var ule=document.getElementById("hexGrid");
ule.appendChild(parag);};
}
};
xmlhttp.open("POST","/",true);
xmlhttp.send();
</script>
<script>
$(document).ready(function(){
$("#myModal").on("show.bs.modal", function(e) {
e.preventDefault();
//var id1 = $(e.relatedTarget).data('target-id');
// var id2 = $(e.relatedTarget).data('target');
var id3 = e.relatedTarget.id;
// console.log('Val1=' + id1 + '; Val2=' + id2 + '; Val3=' + id3);
$.get('/' + id3, function( data ) {
alert(data);
$(".modal-body").html(data);
});
});
});
</script>
And this is the controller's code.
public function getmedia()
{
$event=Events::all();
$items = Media::with('event')->get();
$e=$items->unique('events_id');
$e->values()->all();
return response()->json($e);
}
Try setting Content-Type: application/json header in your.
xmlhttp.open("POST","/",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send();