Django UpdateView form displaying in modal but not updating - javascript

So I have this update view:
class UpdateRules(UpdateView):
model = BlackList
form_class = AddRules
template_name= 'blacklist_form.html'
success_url = reverse_lazy('posts:list')
which displays this template blacklist_form.html:
<form class="well contact-form" method="post" action="">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3>Editing Number</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{form.as_p}}
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save" />
</div>
</form>
Then in the template where the modal is called/rendered I have this link for each object to be edited:
<a class="contact" href="#" data-form="{% url 'posts:update_rules' obj.pk %}"
title="Edit">
And this div to display the modal:
<div class="modal" id="contactModal">
</div>
Lastly, the jQuery:
$(document).ready(function() {
$(".contact").click(function(ev) { // for each edit contact url
ev.preventDefault(); // prevent navigation
var url = $(this).data("form"); // get the contact form url
console.log(url);
$("#contactModal").load(url, function() { // load the url into the modal
$(this).modal('show'); // display the modal on url load
});
return false; // prevent the click propagation
});
$('.contact-form').on('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize(),
context: this,
success: function(data, status) {
$('#contactModal').html(data);
}
});
return false;
});
});
My problem is this: I'm able to get the update view form to display in the modal when I click the edit link for each object, but the submit button doesn't do anything. When I save the form from the actual updateview template, it works just fine, so I'm thinking it must be something wrong with the jQuery. I'm not getting any errors, the modal just disappears and the page doesn't reload. Any pointers on what going on?

Related

Is there a way to reload page and after that inmediately open a modal?

I want to refresh the page after I press the ".parseo" button and then open the "#modal_parseo" modal window but with this code all it does it's open the modal first then refresh the page and closes everything again.
What I tried so far(to clear cache and see If I could fix the issue I had without having to reload the page but the code works fine only after I reload the page before I open the modal):
$('#modal_parseo').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');//this doesn't do anything at all
});
And this:
$("#modal_parseo").on("hidden.bs.modal", function(){
graph_editor.html.set('');//this clears content inside froala editor
$("#tabla_grafico").html("");//this clears datatable I build using the data pasted inside froala editor
});
This is the HTML
<div class="modal fade" id="modal_parseo" tabindex="-1" role="dialog" aria-labelledby="modalLabelparseo" aria-hidden="true">
<div class="modal-dialog modal-98" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabelparseo">Constructor de Gráfico </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="body-parseo">
<div class="row mt-2">
<div class="col-md-6">
<div id="froala-grafico"></div>
<input type="hidden" name="editor_grafico" id="editor_grafico">
<input type="hidden" name="id_temporal" id="id_temporal">
</div>
<div class="col-md-6" id="container_parseo">
<table id="tabla_grafico" data-pagination="false" data-classes="table table-hover table-condensed" data-striped="false" style="width: 100%;"></table>
<br>
<div id="graph_selector" style="display:none; text-align: center;" >
<p><b>Tipo de Grafico: </b></p>
<div class="cc-selector">
<input id="axes" type="radio" name="sel_graph" class="radio_selector" value="axes" checked/>
<label class="drinkcard-cc axes"for="axes"></label>
<input id="activity" type="radio" name="sel_graph" class="radio_selector" value="activity" />
<label class="drinkcard-cc activity" for="activity"></label>
<input id="pie" type="radio" name="sel_graph" class="radio_selector" value="pie" />
<label class="drinkcard-cc pie" for="pie"></label>
</div>
</div> <!--DIV SELECTOR TIPO GRAFICO -->
</div> <!--DIV COL MD 6 -->
</div> <!--DIV ROW -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
<button type="button" class="btn btn-info" id="limpiar_froala">Limpiar</button>
<button type="button" class="btn btn-warning" id="vista_preliminar">Vista Preliminar</button>
<button type="button" class="btn btn-success" id="guardar_grafico">Guardar</button>
</div>
</div>
</div>
Here is the js
window.accionesFila = {
'click .parseo': function(e, value, row, index) {
window.location.reload();
$('#modal_parseo').modal('show');
//FUNCTION TO SAVE DATA
$('#guardar_grafico').click(function() {
//TABLE ID
var $table = $('#tabla_grafico');
//console.log(editor);
//$("#editor_grafico").val(graph_editor.html.get());
//GRAPH TYPE SELECTOR VALUE
var graph_selector = document.querySelector('input[name=sel_graph]:checked').value
function getRowSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row;
})
}
//SAVE SELECTED ROWS HERE
var selectedRows = getRowSelections();
agrupacion_array = [];
//ITERATE
$.each(selectedRows, function(index, value) {
id_grafico = value.col_grafico_id;
agrupacion_array.push(value.val_agrupacion);
});
$.ajax({
url: 'inc/datos-graficos-data',
dataType : "json",
type: 'POST',
data: {
q: 'guardar_grafico',
id: row.id_indicador,
graph_id: id_grafico,
agrupacion: agrupacion_array,
datos: editor
},
async: false,
beforeSend: function() {
//$("#ventasGrafico").html("<img src='images/loading.gif'>");
},
success: function(json) {
$('#modal_parseo').modal('hide');
//SWAL
Swal.fire(
'Exito!',
json,
'success'
)
},
cache: true
});
}); //INSERT GRAPH
}
}
Edit: I added this inside the 'click .parseo' function
'click .parseo': function(e, value, row, index) {
//$('#modal_parseo').modal('show');
var url = window.location.href;
if (url.indexOf('#modal') > -1){
window.location.href.split('#')[0]//I tried this to remove the hash now but it doesn't work
} else {
url += '#modal'
}
window.location.href = url;
window.location.reload();
And this outside, thanks to the 1st answer
$(function() {
if($(location).attr('hash') === '#modal') {
$('#modal_parseo').modal('show');
}
});
Edit2: I managed to remove the hash after I close my modal with this
$('#modal_parseo').on('hide.bs.modal', function(e) {
history.replaceState(null, null, ' ');
});
When you call window.location.reload(), the page is reloaded just like when you press f5 or hit enter on your url bar. This means your current page state is lost, so the execution of your code is interrupted and starts over from the beginning on the freshly loaded page.
What you could do is add a hash to your url when the user clicks the button (for example https://www.my.page/#modal) and then check if this is present when you load the page:
//this executes when the page is ready
$(function() {
if($(location).attr('hash') === '#modal') {
$('#modal_perso').modal('show');
}
});
Note that if somebody bookmarks the page including the hash, this will also be executed.
In your edit, you are trying to use window.location.href.split('#')[0] to remove the hash from the url. By itself, this doesn't do anything - it is just a value. You need to assign the value to something. You can not assign the value directly to window.location.href here because this will make most browsers reload the page.
What you can do is use HTML5 history API like this for example:
window.history.pushState(null, document.title, window.location.href.split("#")[0]);

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

AJAX call not triggered on show.bs.modal

I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})

Retrieve newly updated article without refreshing the page

I'd like to make a edit link to update the article when it's clicked,
In the template, it's structured as:
post-text
article-content
article-form
post-menu
I hide "article-form" in first place as <div class="article-form" style="display: none;"> until edit link is clicked.
<div class = "col-md-12 post-text" >
<div class="article-content">
{{article.content}}
</div>
<div class="article-form" style="display: none;">
<form class="form-horizontal" action="/article/edit/{{ b.id }}" method="POST">
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" id="editContent" name="content" rows="10" cols="30">
{{form.content.value}}
</textarea >
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-0 col-sm-12">
<button type = "submit" class = "btn btn-success btn-sm" id = "saveEditBtn"> Save Edits </button>
</div>
</div>
</form>
</div><!-- article-form -->
</div>
<div class="post-menu pull-left">
<a id="editArticleLink" href="{% url 'article:article_edit' article.id %}">
<span class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a>
<a id="delArticleLink">
<span class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>
After updating is completed and submit is cliked, send data to backend using Ajax, hide "article-form" and show "article-content".
<script>
$(document).ready(
$(".post-menu a").on("click", function(e){
e.preventDefault();
//retrieve the topmost element which the target lives in
$postText = $(e.target).closest(".post-text");
//hide article-content
$postText.find(".article-content").hide();
//show the article-form for users to update
$postText.find(".article-form").show();
//capture the button submitting event
$(".article-form button").on("click", function(e){
var content = $postText.find("textarea").val();
$.ajax({
type:"POST",
url: ,
data:,
success: function(){
//if saved successfully
$postText.find(".article-content").show();
$postText.find(".article-form").hide();
},//success
})//ajax post request
});//nested button click event
}) //click event
)//ready
</script>
My problem is that in ajax success,
$postText.find(".article-content").show() still display the non-updated article,
How could I retrieve the updated without refreshing the page?
If you can send the edited version to server... You have the new content! Update the .article-content with it then show.
Here is what I think it is...
//capture the button submitting event
$(".article-form button").on("click", function(e){
var content = $postText.find("textarea").val();
$.ajax({
type:"POST",
url: ,
data:, // <-- There is something missing here... I assume it's content.
success: function(){
//if saved successfully
$postText.find(".article-content").html(content).show(); // update before the show!
$postText.find(".article-form").hide();
},//success
})//ajax post request
});

.on() function not working for Ajax Loaded Form in Bootstrap Modal

So I am loading a form by doing the following in the index.html.
$(".add-cell").click(function(ev) { // for each edit contact url
ev.preventDefault(); // prevent navigation
var url = $(this).data("form"); // get the contact form url
$("#cell-modal").load(url, function() { // load the url into the modal
$(this).modal('show'); // display the modal on url load
});
return false; // prevent the click propagation
});
This loads a form located in a file add.html. This is the form:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>{{l_name}}, <small>new cell</small></h3>
</div>
<div class="modal-body">
<form class="cell-form" action="/cells/add/{{l_name}}/{{l_id}}/" method="post">
{% csrf_token %}
{{ cell_form.as_table }}
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success submit" type="submit" id="cell_submit" value="Submit" />
<input type="button" name="cancel" class="btn btn-danger" data-dismiss="modal" value="Close"/>
</div>
Now, in my index.html I have this code:
$('.cell-form').on('submit', function() {
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize(),
context: this,
success: function(data, status) {
//Do stuff
}
});
return false;
});
This code works, and this script is located in the index.html, not in add.html. However, why is this code, for the button in the add.html not working when placed in the index.html?:
$("#cell_submit").on('click', function(event){
alert("LOL");
});
I would like to place my JS in the index.html... not in the add.html.
Thanks!
The element to which you attach the event has to exist on the DOM. You'll need to use something like this
$("#cell_modal").on('click', '#cell_submit', function(event){
alert("LOL");
});
For more information about this, please check the section Direct and delegated events here
You need to start by selecting the document. It should look like this:
$(document).on('click', '#cell_submit', function(event){
alert("LOL");
});

Categories

Resources