Accordion List Using Jquery and Ajax - javascript

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>

Related

Convert html select dropdown to single button Nav bar

I have requirement for dynamic menu Navbar output like below with this design.
But now i am getting like below
I am getting dynamic menu data from database below is my code
<select id="dropdownlist" class="form-control" style="color:black">
</select>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/CDO/Menu",
data: "{}",
success: function (data) {
var s = '<option>All History</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].Id + '">' + data[i].type + '</option>';
}
$("#dropdownlist").html(s);
}
});
You can create a tags for button dropdown inside for-loop and then add that generated html inside your dropdown-menu.
Demo Code :
//just for demo :)
var data = [{
"Id": "1",
"type": "abc"
}, {
"Id": "2",
"type": "abc2"
}]
$(document).ready(function() {
var s = "";
/* $.ajax({
type: "GET",
url: "/CDO/Menu",
data: "{}",
success: function(data) {*/
for (var i = 0; i < data.length; i++) {
//generate a tag here ..
s += ' <a class="dropdown-item" href="#"> ' + data[i].Id + ' - Type : ' + data[i].type + '</a>'
}
$("#dropdownlist").html(s);
/* }
});*/
//on click of a tag inside dropdown
$(document).on('click', '.dropdown-menu a', function() {
console.log($(this).text())
$(".dropdown-toggle").text($(this).text()) //change text of button if needed
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<div class="dropdown">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
All History
</button>
<div class="dropdown-menu" id="dropdownlist">
<!--here options will come -->
</div>
</div>

Bootstrap carousel navigation is not working

a while ago i was working on bootstrap carousel, which has represents properties thumbnails based on offices and houses respectively.
entire function goes fine but the carousel navigation is not working.
Here is HTML code
<div class="container-fluid">
<div class="row-fluid">
<div class="span12" id="work_hider">
<div class="page-header">
<h2 class="pull-left"><?php if($this->lang->line('work') != '') { echo stripslashes($this->lang->line('work')); } else echo "Work"; ?></h2>
<h3 class="pull-right" id="geolocate_work"></h3>
<script>
$.getJSON("https://freegeoip.net/json/", function(data) {
var country = data.country_name;
var city = data.city;
$("#geolocate_work").html("<a href='property?city="+city+"'><?php if($this->lang->line('see_all') != '') { echo stripslashes($this->lang->line('see_all')); } else echo "See All"; ?></a>");
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("site/landing/get_work_places"); ?>',
data:{ city_name:city},
dataType: 'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json=="")
{
$('#work_hider').hide();
}else
{
$.each(json, function(key, data)
{
// All the variables from the database containing the post data.
var product_id=data.product_id;
var product_name=data.product_title;
var product_image=data.product_image;
var work_price = data.price_perhour;
var work_address = data.address;
$("#work-carousel").append('<li class="span3"><div class="thumbnail"><img src="'+product_image+'" alt=""></div><div class="caption"><h2>'+work_price+'</h2></div><div class="caption"><h4>'+product_name+'</h4> <p>'+work_address+'</p></div></li>');
});
for (i = 0; i <= 1; i++) {
$('.span3').slice(i * 4, (i + 1) * 4).wrapAll('<div class="item"><ul id="work_property">');
}
}
}
});
});
</script>
</div>
<div class="work_carousel slide" id="myCarousel">
<div class="carousel-inner" id="work-carousel">
<div class="item active" style="height: 100% !important;">
<ul class="thumbnails" id="work_property">
</ul>
</div>
</div>
<div class="control-box" style="margin-bottom: 2em;">
<a data-slide="prev" href="#myCarousel" class="carousel-control left">‹</a>
<a data-slide="next" href="#myCarousel" class="carousel-control right">›</a>
</div>
</div>
</div>
</div>
</div>
Here is my carousel JS
<script>
var totalItems = $('.item').length;
var currentIndex = $('div.active').index() + 1;
$('.num').html(''+currentIndex+'/'+totalItems+'');
$('.work_carousel').carousel({
interval: 2000
});
$('.work_carousel').on('slide.bs.carousel', function() {
currentIndex = $('div.active').index() + 1;
if(currentIndex >= 2){
$('#work_property').attr("id")="newid";
}
});
</script>
I've searched around a lot but i can't fix it. Does someone has a suggestion for me? Thanks in advance!

How to templating json using jquery

Let's say my json like this and i have 3 different data
[
{
"Pair":"",
"Id":"8ca2df56-2523-4bc3-a648-61ec4debcaaf",
"PubDate":"/Date(1463775846000)/",
"Provider":null,
"Market":""
},
{
"Pair":"",
"Id":"74b2d7c7-bc2c-40ee-8245-7c698befa54d",
"PubDate":"/Date(1463775247000)/",
"Provider":null,
"Market":""
},
{
"Pair":"",
"Id":"0ee3cd96-1df8-49ba-b175-7a75d0840973",
"PubDate":"/Date(1463773687000)/",
"Provider":null,
"Market":""
}
]
What I already try
JQUERY
$.ajax({
type: 'GET',
url: 'news.json',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log(data);
$.each(data, function(index, element) {
$( ".content-news h3" ).append( data[0].Title );
**/** Stuck Here and it only call 1 data but i already use each function **/**
});
}
});
HTML
<div class="news">
<div class="ano">
<div class="content-news">
<h3 id="jtitle"> **/** I Want to Show Id Here **/** </h3>
<h4 id="jprovider" class="author">**/** I Want To Show PubDate **/**</h4>
<p id="jsummary">
**/** I Want to Show Provider Here **/**
</p>
<div class="img-head" id="img-container">
<!-- <img src="" alt="img" class="img-responsive">-->
</div>
</div>
<div class="social-control">
<div class="head-control">
<p id="jdate" class="inline gray"></p>
<p class="pull-right">show more</p>
</div>
<div class="clear"></div>
<div class="footer-control">
<p><i class="ion-ios-heart ion-spacing"></i>20</p>
<p><i class="ion-chatbox ion-spacing"></i>2 comments</p>
<p><i class="ion-android-share-alt ion-spacing"></i>share</p>
</div>
</div>
</div>
</div>
JSFiddle
I managed to out only 1 result. Can you guys give a hint or tips show me how to templating jquery using json. Please be easy on me. Thanks
THIS IS THE RESULT WHAT I GET RIGHT NOW, Only 1 data display..
You can access the properties via the index on the data property as so:
$.ajax({
type: 'GET',
url: 'news.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function(data) {
//console.log(data);
$.each(data, function(index, element) {
console.log(
data[index].Id,
data[index].Pair,
data[index].PubDate,
data[index].Provider,
data[index].Market
);
});
}
});
Which produces
8ca2df56-2523-4bc3-a648-61ec4debcaaf /Date(1463775846000)/ null
74b2d7c7-bc2c-40ee-8245-7c698befa54d /Date(1463775247000)/ null
0ee3cd96-1df8-49ba-b175-7a75d0840973 /Date(1463773687000)/ null
To handle the templating you can create a function that returns the markup for each item:
function template(title, provider, summary) {
var $temp = $('<div/>');
$temp.append($('<h3/>', {
text: title
}));
$temp.append($('<h4/>', {
text: provider,
class: 'author'
}));
$temp.append($('<p/>', {
text: summary
}));
console.log($temp);
return $temp;
}
$.ajax({
type: 'GET',
url: 'https://cdn.rawgit.com/enki-code/4ec2b6efa84dfed8922b390d2a1a4c5a/raw/dc94405f12d1d5105e54584a6c53ca30d1863b4a/so.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function(data) {
//console.log(data);
$.each(data, function(index, element) {
$('.content-news').append(template(data[index].Id, data[index].PubDate, data[index].Provider));
console.log(
data[index].Id,
data[index].Pair,
data[index].PubDate,
data[index].Provider,
data[index].Market
);
});
}
});
Here is an updated version of your fiddle as an example.
You'll likely have to make a few small adjustments to the CSS and whatnot to get it looking how you like.
you json file have array of objects so first you need to loop for the objects one by one
also don't use each for serialized array cause it takes more time just use the normal for loop
answer is here jsfiddle.net/robert11094/65zjvy5k/3
or just use this html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://subscriptions.fxstreet.com/json/news.aspx?c=A0DC975D13C44CE697EC&i=englishnewscharts',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log(data);
for (var i=0;i<data.length;i++){
var html=
'<div class="ano">'+
' <div class="content-news">'+
' <h3 id="jtitle"> '+data[i].Id+' </h3>'+
' <h4 id="jprovider" class="author">'+data[i].PubDate+'</h4>'+
' <p id="jsummary">'+
data[i].Provider+
' </p>'+
' <div class="img-head" id="img-container">'+
' <!-- <img src="" alt="img" class="img-responsive">-->'+
' </div>'+
' </div>'+
' <div class="social-control">'+
' <div class="head-control">'+
' <p id="jdate" class="inline gray"></p>'+
' <p class="pull-right">show more</p>'+
' </div>'+
' <div class="clear"></div>'+
' <div class="footer-control">'+
' <p><i class="ion-ios-heart ion-spacing"></i>20</p>'+
' <p><i class="ion-chatbox ion-spacing"></i>2 comments</p>'+
' <p><i class="ion-android-share-alt ion-spacing"></i>share</p>'+
' </div>'+
' </div>'+
'</div>';
$('.news').append(html);
}
}
});
});
</script>
<div class="news">
<div class="ano">
<div class="content-news">
<h3 id="jtitle">Hello World</h3>
<h4 id="jprovider" class="author">David</h4>
<p id="jsummary">
This is content
</p>
<div class="img-head" id="img-container">
<!-- <img src="" alt="img" class="img-responsive">-->
</div>
</div>
<div class="social-control">
<div class="head-control">
<p id="jdate" class="inline gray"></p>
<p class="pull-right">show more</p>
</div>
<div class="clear"></div>
<div class="footer-control">
<p><i class="ion-ios-heart ion-spacing"></i>20</p>
<p><i class="ion-chatbox ion-spacing"></i>2 comments</p>
<p><i class="ion-android-share-alt ion-spacing"></i>share</p>
</div>
</div>
</div>
</div>
Try to use $.parseJSON or $.getJSON. It will be easier to find problems.
Reference: jQuery API

Trying to use an ajax get to get a div and its content from another page not working

I am receiving an error saying: Uncaught SyntaxError: Unexpected token <
I was using jquery load, but I need to pass headers, so I can no longer usethat and need to use jquery
my links:
<div class="list-group">
<a class="list-group-item active" href="<?php echo Config::get('URL'); ?>profile/timeline/<?php echo System::escape($this->user->user_id); ?>"><span><?php echo System::translate("Timelime"); ?></span></a>
<a class="list-group-item" href="<?php echo Config::get('URL'); ?>profile/about/<?php echo System::escape($this->user->user_id); ?>"><span><?php echo System::translate("About"); ?></span></a>
<a class="list-group-item" href=""><span>Images</span></a>
<a class="list-group-item" href="<?php echo Config::get('URL'); ?>profile/friends/<?php echo System::escape($this->user->user_id); ?>"><span><?php echo System::translate("Friends"); ?></span></a>
</div>
my ajax
$(function() {
$('.list-group-item').click(function(e){
e.preventDefault();
$.ajax({
url:$(this).attr('href'),
type:'GET',
success: function(data){
$('.layout-content-container').fadeOut('slow', function(){
$('.layout-content-container').html($(data).find('#inner_main_content').html(), function(){
$('.layout-content-container').fadeIn('slow');
});
});
}
});
});
});
Have I put the function in the correct place?
$('.layout-content-container').html($(data).find('#inner_main_content').html(), function(){
$('.layout-content-container').fadeIn('slow');
});
Rendered HTML from the other page
<div class="col-md-12 layout-content-container">
<div class="panel panel-default">
<div class="panel-heading"><strong>Overview</strong></div>
<div class="panel-body"> blah blah blah </div>
inside clicks anonymous function preserve $(this).attr('href') to some var and do because inside ajax this will point to other object.
$(function() {
$('.list-group-item').click(function(e){
var ur = $(this).attr('href');
e.preventDefault();
$.ajax({
url:ur,
type:'GET',
success: function(data){
$('.layout-content-container').fadeOut('slow', function(){
$('.layout-content- container').html($(data).find('#inner_main_content').html(), function(){
$('.layout-content-container').fadeIn('slow');
});
});
}
});
});
});

How to make "this" refer to the element firing the event

I'd like to make "this" refer to the element which is actually firing the event:
<div class="input-group">
<span class="input-group-addon header-text" id="action-header-text">Action</span>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="action-dropdown" data-toggle="dropdown" aria-expanded="true" style="min-width:250px;">
<span class=" caret">
</span>
</button>
<ul id="action-menu" class="dropdown-menu" role="menu"></ul>
</div>
</div>
Filling Ajax Request:
function UpdateActionDropdown() {
$.ajax({
url: 'FrontEnd/Action',
type: 'POST',
dataType: 'json',
data: {
lid: document.getElementById('selected-language-id').value
},
success: function (data) {
document.getElementById('action-dropdown').firstChild.data = data.UnSelectable[0].ActionTrailer.DescriptionText;
$('#action-menu').html(null);
for (var i = 0; i < data.UnSelectable.length; i++) {
$('#action-menu').append("<li role='presentation' class='disabled'><a role='menuitem' tabindex='-1'>" + data.UnSelectable[i].ActionTrailer.DescriptionText + "</a></li>")
}
$('#action-menu').append("<li role='presentation' class='divider'></li>");
for (var i = 0; i < data.Selectable.length; i++) {
$('#action-menu').append("<li role='presentation'>" +
"<a role='menuitem' tabindex='-1' text='" + data.Selectable[i].DescriptionText + "' value='" + data.Selectable[i].ActionTrailer.ID + "'\" href='#'>" + data.Selectable[i].ActionTrailer.DescriptionText + "</a></li>")
}
}
});
}
global listener:
$('.dropdown').on('click', '#action-menu li', function(){
// Inside here I want to access the li-element which got clicked.
});
I assume that "this" inside the onclick Handler would refer to the document (or window) itself - is it possible to refer to the actual event firing element?
Thanks in advance!
Use $(this) which will be a DOM(in the context of jQuery) element when you are in a callback function
$('.dropdown').on('click', '#action-menu li', function(){
$(this)// It will be the li element clicked
});
See jQuery: What's the difference between '$(this)' and 'this'? and https://remysharp.com/2007/04/12/jquerys-this-demystified

Categories