Load JSON data into a Bootstrap modal - javascript

I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person's picture, the modal pops up.
<li class="project span3" data-type="pfa">
<a data-toggle="modal" data-target="#myModal" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
Here's an example of the JSON data:
var florida_exoneration = [
{
"last_name":"Atkins",
"first_name":"Kenneth",
"age":16,
"race":"Caucasian",
"state":"FL",
"crime":"Sexual Assault",
"sentence":"10 years",
"conviction":2004,
"exonerated":2008,
"dna":"",
"mistaken witness identification":"",
"false confession":"",
"perjury/false accusation":"Y",
"false evidence":"",
"official misconduct":"",
"inadequate legal defense":"",
"compensation":""
}
]
I'd like the modal to display something like this inside the box:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""
I also want to make sure the data is tied to the picture so the modal doesn't get confused. I'm sorry if this is a bit confusing. I'll try and clarify if anyone has any questions.

Method 1: using Ajax
Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" data-id="2" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
$.ajax({
type: "GET",
url: 'getJson.php?id='+$(this).data('id'),
dataType: 'json',
success: function(data){
htmlData = '<ul><li>title: '+data.first_name+'</li><li>age: '+data.age+'</li></ul>';
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
}
});
return false;
});
})(jQuery);
Method 2: using hidden div
No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
<div class="profile hide">
<ul>
<li>title: Atkins Kenneth</li>
<li>Age: 16</li>
</ul>
</div>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
htmlData = $(this).find('.profile').html();
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
return false;
});
})(jQuery);

Related

Issue on getting id from Selected HTML elements from Ajax GET response with jQuery

I am using ajax to display product data and then delete on click a specific on using the product id but am not able to get the product id as it is showing undefine can you guys suggest something.
In this code first I am getting the product details for the cart dropdown menu and then displaying it in list format with delete button through the first ajax and then on clicking delete should delete the element in the second ajax using the elements product id which I have saved inside data-r but on console, it showing undefined can anyone tell me what is the issue. As I know that the elements are created dynamically but I am not getting a solution
function TopCartVal() {
// Used Route inside the ajax
var url = "{{ route('pdt.details', ':id') }}";
var yui = "{{ route('delete_fr.cart', ':id') }}";
// Ajax Structure
$.getJSON( "{{ route('my.cart','json') }}", function( data ) {
console.log(data);
var Cart = $('#cart_dp_sec_pdt_desc');
// Loop for data
$.each(data, function(key , value) {
console.log(value);
url = url.replace(':id', value.product_id);
yui = yui.replace(':id', value.product_id);
Cart.append(`
<div class="row">
<div class="col-xs-4">
<div class="image">
<a href="`+url+`">
<img src="{{ asset('')}}`+value.image+`" alt=""/>
</a>
</div>
</div>
<div class="col-xs-7">
<h3 class="name">
`+value.product_name+`
</h3>
<div class="price">`+value.currency+value.product_price+`</div>
</div>
<div class="col-xs-1 action">
<a href="#"
data-r"`+value.id+`"
class="cart_dp_btn_ctn_delete">
<i class="fa fa-trash"></i>
</a>
</div>
</div>
`);
});
});
}
// delete part
$(document).on('click', '.cart_dp_btn_ctn_delete', function(e){
e.preventDefault();
var id = $(this).attr('data-r'); // id of to be deleted element
var yui = "{{ route('delete_fr.cart', ':id') }}";
yui = yui.replace(':id', id);
console.log(yui);
console.log(id); // it is showing undefined`enter code here`
// $.getJSON( yui, function(data){
// TopCartVal();
// });
});
You are missing an = here:
data-r"`+value.product_id+`"
But using template literals correctly will make it easier to see
`<div class="row">
<div class="col-xs-4">
<div class="image">
<a href="${url">
<img src="{{ asset('')}}${value.image}" alt=""/>
</a>
</div>
</div>
<div class="col-xs-7">
<h3 class="name">
${value.product_name}
</h3>
<div class="price">${value.currency+value.product_price}</div>
</div>
<div class="col-xs-1 action">
<a href="#" data-r="${value.product_id}" class="cart_dp_btn_ctn_delete">
<i class="fa fa-trash"></i>
</a>
</div>
</div>`

How to load separate html page into a div on click?

I am really new to javascript and jquery, but I am trying to create a page that will allow the user to click on a Country name and information for that country will load in a div from a separate html file.
Else where I found this code which works nicely for this, using the .click(function) on the <a> tag:
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("a").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#partnerContent").html(response);
}
});
return false;
});
});
Here is the basic html:
<div id="contentcontain">
<div class="partnercol1">
<div class="container">
<div id="menu" class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data- toggle="dropdown">International Sales <span class="caret"></span></button>
<ul class="dropdown-menu scrollable-menu" role="menu">
<li>Belgium</li>
<li>Brunei</li>
<li>Bulgaria</li>
</ul>
</div>
</div>
</div>
<div class="partnercol2">
<div id="partnerContent"></div>
</div>
However, now every <a> tag on the page (including top and bottom menus) loads their href into the div when clicked. How can I target just the div containing the state menu to work with this function?
Make the selector for the elements you're attaching the events to more restrictive:
// this selects all the anchors below the items with ID menu
$j("#menu a").click(function () {
...
});
in your html, put:
<ul class="dropdown-menu scrollable-menu" role="menu">
<li><a class="menu-item" href="partners/belgium.html">Belgium</a></li>
<li><a class="menu-item" href="partners/brunei.html">Brunei</a></li>
<li><a class="menu-item" href="partners/bulgaria.html">Bulgaria</a></li>
</ul>
And in your javascript
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j(".menu-item").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#partnerContent").html(response);
}
});
return false;
});
});
You're loading an entire html page, which means you're loading
<html>...</html>
and then stuffing that in its entirety into your page, that means you'll eventually have
<html>
....
<html>...</html>
...
</html>
which is NOT valid. If you're trying to replace the contents of a single <div> in your page, then either you fetch that entire page into a var and slice out the chunk you want, or have jquery fetch/insert ONLY the part you want, e.g.
$('#div_to_replace').load('source_of_new.html #id_of_element_to_use_for_replacement');
Note the second #... argument in the .load() call. That tells jquery to ignore everything in the page EXCEPT for the specified element/ID. Only that ID's contents will be stuffed into #div_to_replace.

How to pass the values to the other html page and redirect the to that page for onclick thumbnail using jquery?

Here I need to click on a thumbnail, so that it will show the details on other page, it should show the details of that particular thumb only. I used xml file here to fetch the data and display thumbnail. I am unable to pass the values to other page and open it at the same time onclick event. pls help
<div class="container-page">
<div class="row" id="portfolio">
<div class="col-md-2">
<nav>
<ul class="nav nav-pills nav-stacked" id="test">
<li role="presentation" class="active">Services</li>
<li role="presentation">Desktop</li>
<li role="presentation">Web</li>
<li role="presentation">Mobile</li>
<li role="presentation">Design</li>
</ul>
</nav>
</div>
<div class="col-md-10">
<div class="row" id="thumb">
</div>
</div>
</div>
</div>
<!-- js -->
$.ajax({
type:"GET",
url:"portfolio.xml",
dataType:"xml",
success:function(xml)
{
$(xml).find('thumbnail').each(function()
{
var $thumbnail=$(this);
var type=$thumbnail.find('type').text();
var descr=$thumbnail.find('description').text();
var title=$thumbnail.attr('title');
var imageurl=$thumbnail.attr('imageurl');
var thum='<div class="col-xs-6 col-md-3"> </div>';
thum=$(thum).appendTo("#thumb");
thum = $('').appendTo(thum);
var thumName = $('<div class="thumTitle"></div>').appendTo(thum);
$('<h2>'+title+'</h2>').appendTo(thumName);
$('<p>'+type+'</p>').appendTo(thumName)
thum = $('<img src="'+imageurl+'" alt="image" class="thumbImgSize imgSlide">').appendTo(thum);
$(".forHove").mouseup(function()
{
//here is the redirection code, and want to pass $thumbnail to testxml.html page
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
});
}
});
Well, one of the alternative is using Web Storage API.
Just store img html and use it.
// use 'click' instead of 'mouseup'
$(".forHove").click(function()
{
// store image html to sessionStorage
window.sessionStorage.image_data = $thumbnail.clone().wrapAll("<div>").parent().html();
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
// in http://www.bookmane.in/skillworks/testxml.html
// You have data sotred and insert it somewhere
$(document.body).append(window.sessionStorage.image_data);
You can achieve this thing using the following steps:
Add a form tag like
<form action="YOUR_PATH" method="GET">
<a class="thubnailClick" href="#" >
<html_of_your_thumbnail>
<input type="text" name="NAME_OF_PARAMETER" />
</a>
</form>
Now override the click event of <a> tag with
$(document).ready(function() {
$(".thubnailClick").on('click', function(event) {
// to override the default behavior of <a> tag.
preventDefault();
// Find the form element using closest() of jQuery.
// Call submit event of that form using $(form_element).submit();
});
})
Now on the other page you can get parameter from URL using location.search or follow:
Getting Query params using JavaScript
Now use these Params according to your needs.

How to get a listview to refresh with new data from a Kendo datasource

How do I get my list view page to refresh when I load new data into my kendo.data.DataSource?
I'm working on a Hybrid Mobile app using Telerik AppBuilder.
I have a simple listview that is bound to a data source.
I use an ajax POST request to load some JSON,
then place it in the datasource.
I have two pages, home and list view.
The home has some anchors that lead to a single list view page,
but with different data id values to produce different lists.
The first time I the list view page it loads correctly.
After that, the list view does not refresh when I reload the datasource;
the contents of the first list always display no matter what data id value I send in.
Here is the source:
JavaScript
window.APP =
{
blamListSource: null,
home:
{
fetchBlam: function(event)
{
var argumentData = event.button.data();
var requestBody =
{
"requestVersionId": "1",
"blamId": argumentData.id.toString()
};
$.ajax(
{
url: getBlamURI,
type: "POST",
data: JSON.stringify(requestBody),
dataType: "json",
contentType: 'application/json',
success: function(requestData, textStatus, jqxhr)
{
APP.blamListSource = new kendo.data.DataSource(
{
data: requestData.userList,
});
APP.blamListSource.read();
app.navigate("views/blamlist.html");
},
error: function(jqxhr, textStatus, error)
{
alert("Error");
},
});
}
}
};
home.html
<div data-role="view" data-title="Home" data-layout="main"
data-model="APP.models.home" data-zoom="true">
<div id="form-blam" data-role="content">
<a id="commercial" data-role="button"
data-bind="click: fetchBlam" data-id="27">Something</a>
<a id="personal" data-role="button"
data-bind="click: fetchBlam" data-id="39">Something Else</a>
</div>
</div>
views/blamlist.html
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true">
<div data-role="navbar">
<a class="nav-button" data-align="left" data-role="backbutton">Back</a>
</div>
<ul id="blam-listview" data-style="inset" data-role="listview"
data-template="blamListTemplate" data-bind="source: blamListSource">
</ul>
<p id="no-contactlist-span" hidden="hidden" class="no-items-msg">
<b>No blam.</b>
</p>
</div>
<!-- Blam ListView Template -->
<script type="text/x-kendo-template" id="blamListTemplate">
<div>
<div>
<img id="blamPhoto" src="#: data.photoUri #"/>
</div>
<div>
<div id="name">#: data.name #</div>
<div>#: data.title #</div>
<div>
<div>
<a data-role="button" class="callimg"
data-phone="#: data.phone #" href="tel:#: data.phone #"
data-rel="external"></a>
</div>
<div>
<a data-role="button" class="emailimg"
href="mailto:#: data.email #"
data-rel="external"></a>
</div>
</div>
</div>
</div>
</script>
It appears to be fairly easy.
Add data-reload="true" to the view.
Old - does not refresh
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true">
New - refreshes
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true" data-reload="true">
Edit I accidentally put "data-refresh", which is wrong. The correct value (edited to be correct) is "data-reload".

Jquery on('click') not firing after first click

I have some HTML:
<div class="post-container self">
<a href="/user/Wiz">
<img class="avatar" alt="Profile Picture" src="">
</a>
<div class="post-body">
<div class="post" style="margin-left:0px;">
<div class="post-timestamp" style="display:inline-block;float:right">
Oct 31
</div>
<div class="post-functions dropdown displaynone" style="float:right;margin-right:5px;">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="icon-cog">
</i>
</a>
<ul class="dropdown-menu post-dropdown" role="menu" aria-labelledby="dLabel">
<a class="post-delete" href="javascript:void(0)"><i class="icon-trash"> </i>Delete</a>
</ul>
</div>
</div>
</div>
</div>
And with that, I have some Jquery:
$('.posts-content').on('click', '.post-delete', function(e) {
$('.post-dropdown').dropdown();
if (confirm('Are you sure you want to delete this post?')) {
var $this = $(this);
$.ajax({
url: '/a/delete_post',
type: 'POST',
dataType: 'json',
data: {'p' : post_id},
success: function() {
//...
return true;
}
});
}
return false;
});
Everything works perfectly the first click, but if I go to another post, and try to click .post-delete, the event never fires, and nothing shows up in the console. It also works if I use $.click(), but I need to dynamically create elements. Why does the $.on('click') not fire the second click?
My guess is that dropdown plugin you use change the DOM structure.
$('.post-dropdown').dropdown();
BTW,
$this.parent().parent().parent().parent().parent() this is really really bad practice.
You should use closest instead.
If you are dynamically creating elements try:
$(document).on('click', '.post-delete', function(e) { });

Categories

Resources