modal iteration in foreach loop using ajax - javascript

I got a problem with foreach loop. What am i trying to do is get data (JsonResult) from action in controller. Get get songs for each album.
public JsonResult SongListByAlbum(int albumID)
{
var songs = (from song in Song.GetSongList()
join album in Album.GetAlbumList()
on song.AlbumID equals album.AlbumID
where (albumID == album.AlbumID)
select song).ToList();
return Json(songs,JsonRequestBehavior.AllowGet);
}
Then put them into view, for album get list of songs and show them as modals
There is my view:
#foreach (var item in Model.Albums){
<button id="#item.AlbumID" type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-#item.AlbumID">
Show
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal-#item.AlbumID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-#item.AlbumID" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel-#item.AlbumID">#item.AlbumName #item.Year, #item.BandName</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="parent" class="modal-body">
</div>
<div class="modal-footer">
<button id="closeModal"type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
And there is a script, where I get songs for each album.
<script>
$(".myModals").on("click", function () {
var Id = $(this).attr('id');
alert(Id);
$.ajax({
type: "GET",
url: '#Url.RouteUrl(new{ action= "SongListByAlbum", controller="Default"})',
data: {albumID:Id},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
for (var i in result) {
$('#parent').append('<p class="toRemove">' + result[i].SongName + '</p>');
}
},
error: function (response) {
alert('error');
}
});
});
</script>
The problem is : when i click on the first modal button everything is fine, i get what i want to. But when i click on the second one i got empty modal. Then when i click again on the first one i got data from previous click and penultimate. Image: enter image description here

To avoid multiple <div id="parent"> elements, you should probably assign the Id the same way you do for the buttons. Like <div id="parent-#item.AlbumID">. Then in your ajax call reference the correct div. $('#parent-' + Id).
Not sure if that is your only probably, but might get you closer.

Related

Flask add modal to ask before deleting. How to get working?

In my Flask APP i have a page with a link to delete:
Is inside a table each row have this id, here I am sending the ID (that normaly I use to delete):
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" id="submits" onclick="send_to_modal('{{post.id}}')">
Borrar
</button>
Here is my javascript:
function send_to_modal(id){
document.getElementById("exampleModalLabel").innerHTML = id;
};
The modal:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" onclick="modal_a_funccion()">SI</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">NO</button>
</div>
</div>
</div>
</div>
I don´t know how to send the ID to another function that is charged to delete the specified data:
This is my function that works correcty and delete the data giving the ID:
function modal_a_funccion(id){
console.log("Solicitando un report para: "+id);
//fetch('/report/' + olt_hostname).then(function(response) {
fetch('/task/report_celery/' + id).then(function(response) {
response.json().then(function(data) {
for (var x of data.ip) {
console.log("REPORT_fetch recibe (IP): " +x.ip_oob)
console.log("REPORT_fetch recibe (ESTADO): " +x.estado)
};
});
});
};
I would like to know how to to it.
What I intend to do is add a modal to ask the user for confirmation whether or not to delete. I can't find a way to pass the Id to the function that is in charge of doing the deletion. I would like to know how to do it. Thank you so much.
A possible solution (in a different way)
When user clicks on delete for a row, add a class e.g. to_delete. Then display the modal popup asking if user wants to go ahead with the delete or not.
If user says no, close the modal and remove the class again
If user says yes, call the delete function
For 3, you do something like
// Find the element that user has marked for delete
const element = document.querySelect(".to_delete")
const id = element.id;
For 2, you do something like
// Find the element that user has marked for delete and remove the delete mark
document.querySelect(".to_delete").classList.remove("to_delete")

modal show not working after modal(hide) in jquery after submit

I have table in modal with edit button to update the user details
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">User Info</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form>
<div class="modal-body edit-info" >
</div>
<div class="modal-footer">
<button type="submit" class="roomupdate btn btn-warning">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
and my ajax code is
$(document).on('click', '.roomupdate', function(){
ev.preventDefault();
$id= $('#id').val();
$building=$('#building').val();
$floorno=$('#floorno').val();
$roomno=$('#roomno').val();
$priority=$('#priority1').val();
$nobeds=$('#nobeds').val();
$('#editModal').modal('hide');
$.ajax({
type: "POST",
url: "addroomlist.php",
async: false,
data: {
building: $building,
id: $id,
floorno: $floorno,
roomno: $roomno,
priority: $priority,
nobeds: $nobeds,
roomupdate: 1,
},
success: function(){
showUser();
},
});
});
and my edit button code to call modal with user info.
<td> <button data-id='<?php echo $row['id'] ?>' class='roomedit btn btn-warning'>Edit</button></td>
when i first click save button after modify the details its working fine and modal closed with
$('#editModal').Modal('hide');
when i click edit button second time Modal not show up until i reload the page.
where it went wrong please help
In your ajax code remove $('#editModal').modal('hide'); from the line where you are using right now and put it in success function of ajax.
Like:
success: function(){
$('#editModal').modal('hide');
showUser();},
and if you are using location.reload(); in your showUser(); function then it will work but as far i know i think you did not add it in showUser(); so add also location.reload(); after showUser(); function or at the end of code written in showUser(); function.
And one more thing do you write any code by which clicking on edit button the modal should open in javascript?

Get form values and pass it to Bootstrap modal on Submit

I'm trying to get my form data and pass it as JSON to my modal dialog, which also should open on Submit button!
Here is what I've done so far:
HTML
<form class="form-horizontal" id="configuration-form">
--unimportant--
<button type="submit" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please copy this code to your HTML</h4>
</div>
<div class="modal-body">
<code id="configurationObject"></code><br/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
(function(formId) {
$("#" + formId).submit(function(event){
event.preventDefault();
var errMsg = "Something went wrong with form submit, please try again";
var json = convertFormToJSON(this); //here I got my json object with all my form data
$.ajax({
type : 'POST',
data: {conf: JSON.stringify(json)},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data){
$("#configurationObject").html(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
return false;
});
})("configuration-form");
After Submit button is clicked I do get my JSON object with form data (I can log it after
var json = convertFormToJSON(this)
and my modal dialog window is opened, but I do miss my data aka.
element with id="configurationObject" is empty.
Thanks in advance
Have you tried to append() the data to #configurationObject rather than using html()?
According to documentation $.html() accepts A string of HTML to set as the content of each matched element. .
Here you are passing json data instead of string. So first, you have to convert json response to string. $("#configurationObject").html(JSON.stringify(data));
or you can use
$("#configurationObject").append(data);

Use modal in place of 'show' views

I am trying to use modals in place of the traditional 'show' views in Ruby. When a user clicks on a item in the index view, a modal popup shows instead of redirecting the user to a new 'show' page.
How can I accomplish this?
Let's assume that the controller looks something like this:
#list = Items.all
I want the modal to show the characteristics of each item on the #list object. For instance, one modal would show #list[0] and another would be #list[1]. How can I pass the index values to the modal?
An approach I might take would be, assuming that on your index there is a dropdown and a submit button ...
jQuery
$('#submit').click(function(){
$.ajax({
url: "items/get_item",
type: "GET",
data: { item: $('#select').val() },
success: function (data) {
//Populate modal in here with item details
$('#myModal modal-body').html(data)
}
});
});
Item Controller
def get_item
return :json => Item.where({:name => params[:item]}).to_json
end
View
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
You need to render a javascript template from the show action
def show
#list = Items.all
respond_to do |format|
format.js { render 'your_js_template' }
end
end
Then in your template you can use the #list instance variable to create the jQuery for the modal

Twitter Bootstrap modal windows shade not closing

Hello I have Page with modal windows which I open with this JS code:
$('.open-modal').on('click', function (event) {
event.preventDefault();
var object = $(this);
modals(object.attr('href'))
})
function modals(href) {
$("#Modal").modal("hide");
$.ajax({
url: href,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'html',
//data: { id: $(this).attr('id') },
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
$('.modal-body').html(data);
$("#Modal").modal('show');
$('.ChangeToEdit').on('click', function (event) {
$("#Modal").modal('hide');
event.preventDefault();
var object = $(this);
modals(object.attr('href'))
})
}
});
}
and html:
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
and example of buttons:
<a class="open-modal" href="/User/Edit/14">Edit</a> |
<a class="open-modal" href="/User/Details/14">Details</a> |
<a class="open-modal" href="/User/Delete/14">Delete</a>
If User open modal with Details he will find modal with details and button to edit this data. After pressing that button modal window should close and open new one with edit.
Unfortunately. When user use edit button on details modal a second " shade" appears and stay there even after edit modal is closed.
What I'm doing wrong? why second shade shade from first modal doesn't disappear?
Try to do$(".modal-backdrop").removeClass(); after you closed the first modal.

Categories

Resources