Retrieve newly updated article without refreshing the page - javascript

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
});

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]);

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>`

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....
})

Django UpdateView form displaying in modal but not updating

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?

Modal Form Submission without refresh

I have a modal window that pops up when I want to add a new project to my dashboard. I have gotten it to work with jquery post however, I cannot prevent it from refreshing. What I want to do is after the project is added to the database, show a success message and close the modal window after few seconds and not refresh the page (parent page of modal).
Here is my modal
<div class="modal fade" id="add-project-dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" 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">&times;</button>
<h4 class="modal-title" id="myModalLabel">Add a new Project</h4>
</div>
<div class="modal-body">
<h3>New Project:</h3>
<form class="form-horizontal" id="add-project-form" action="/projects/add" method="POST">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Project Name</label>
<div class="col-md-4">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="description">Project Description</label>
<div class="col-md-4">
<input id="description" name="description" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="project_state">Project State</label>
<div class="col-md-4">
<input id="project_state" name="project_state" type="text" placeholder="" class="form-control input-md">
</div>
</div>
</fieldset>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add-btn" class="btn" type="submit">Add</button>
</div>
</form>
</div>
</div>
Here is my project-dashboard.js
AddProject = function(){
$(document).ready(function() {
$("#submit").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
}
My views.py
class AddProject(webapp2.RedirectHandler):
def get(self):
template_values = {
#'greetings': greetings,
#'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), '../templates/project-add.html')
self.response.write(template.render(path, template_values))
def post(self):
project = Project()
project.name = self.request.get('name')
project.description = self.request.get('description')
project.project_state = self.request.get('project_state')
time.sleep(2)
project.put()
self.redirect('/projects')
I have tried removing the self.redirect('/projects') however that only takes me to a blank page that is /projects/add (that is the action in the form).
The issue is that you added .ready(foo) handler inside of the AddProject function. I suppose that document is loaded when AddProject is called.
Another issue is that in your HTML, the form has id add-project-form, so you should do $("#add-project-form") instead of $("#submit").
$(document).ready(function () {
$("#add-project-form").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
});
Take ready handler outside of the AddProject function and it should work (the submit handler is added).
Edit: After some debugging, the answer was to use the right id and proper placing of the javascript code, as noted by the comments.
For starters, a refresh is easy to avoid, just make sure to prevent the default event from running; since you're using jQuery, I would recommend doing return false to end the function, since it both 'prevents default' and 'stops propagation'.
So the first thing you should do is check if your javascript code is actually running and not erring in the middle of execution. If everything is fine there, the worst case is that the project is not actually added (server side error) but the page should not refresh.
Your server side code has nothing to do with the refresh (if it's being properly hijacked), so the response doesn't really matter, I would actually return the id of the new project (so you could provide a link for the newly created item or something like that), but i digress...
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok")) //custom validation dont copy
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular class button
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Now you should get no page refreshes on any of your modals if u follow these steps.

Categories

Resources