Load JSON data into Bootstrap modal module

I want to load a JSON file that creates a list inside Bootstrap Modal. I found where, if you click on the image of a person, 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 is an example of 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 would 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 that the data is attached to the image, so the modality is not confused. Sorry if this is a bit confusing. I will try and clarify if anyone has any questions.

+5
source share
1 answer

Method 1: using Ajax

Each time a user clicks an image, you get an identifier from the clicked image, and then you send an Ajax request to the server to get a 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); modal.modal('show'); } }); return false; }); })(jQuery); 

Method 2: use a hidden div

There is no need for any Ajax request, but you need to create a hidden div containing all the information you want to display in 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); 
+9
source

Source: https://habr.com/ru/post/1200981/


All Articles