Clicking the browser back button after getting the confirmation page - javascript

I have a page where I have to fill the student details for example name, email and department. Once I fill the details and click the submit my button it goes to next page and it shows the entered student details in the next page.
Here I have shown the code step by step.
The below code after entering the details and clicking the submit button.
<div class="top-space-20">
<input class="btn btn-info" type="button" onclick="submitEvent()" class="btn" value="submit my details">
</div>
This is the script code for clicking the submit my details button.
function submitEvent() {
form = document.createElement("form");
form.method = "POST";
form.action = "/confirmation";
}
Once I clicked the button it goes to backend and fetch some details and it displays the confirmation.html page.
#app.route("/confirm",methods=['GET','POST'])
def confirm():
"Confirming the event message"
response_value = request.args['value']
return render_template("confirmation.html", value=json.loads(response_value))
#app.route("/confirmation", methods=['GET', 'POST'])
def ssubmit_and_confirm():
"submit an event and display confirmation"
if request.method == 'POST':
return redirect(url_for('confirm', value=value))
The below code is the confirmation.html page
<body style="background-color:powderblue;">
<div class="panel panel-default" style="max-width:1000px;max-height: 800px;margin-left:auto;margin-right:auto;">
<div class="panel-heading " style="text-align: center;">submit student details</div>
<div class="panel-body" id="resultDiv">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<label class="col-md-8" for="Date:">Date:
{{ value }}</br> Time :{{value}}</label>
<label class="col-md-8" for="dateApplied"></label>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<label class="col-md-8" for="student email:">
student email id:{{value}}</label>
</div>
</div>
</div>
</div>
</body>
So the problem here is once I come to the confirmation.html and if I click the browser back button it goes to the form and it lets me add the same details.
To avoid this I tried including this lines in the confirmation.html
</div>
<div><input type="hidden" id="reloadPage" /></div>
<script type="text/javascript">
$(document).ready(function() {
function reloadPage(){
location.reload(true); ; // RELOAD PAGE ON BUTTON CLICK EVENT.
// SET AUTOMATIC PAGE RELOAD TIME TO 5000 MILISECONDS (5 SECONDS).
var timerId = setInterval('refreshPage()', 5000);
}
});
function refreshPage() { clearInterval(timerId); location.reload(); }
</script>
But it's not working. I tried one more method which is given in the link
How to stop re submitting a form after clicking back button
This is also not working.
So what do I need is if I click the back button in the browser I should display the confirmation page only or it should tell this is not the authourized page.

Step 1:
On the form submission page, initially set the form submission value to false.
sessionStorage.setItem('form-submit', false)
Step 2:
And when submitting the form in previous page, check:
function submitEvent() {
formSubmitted = sessionStorage.getItem('form-submit')
if (!formSubmitted){
// Write your code here
}
}
Step 3:
On confirmation.html page, you can store a submission value in sessionStorage.
sessionStorage.setItem('form-submit', true)

You could add HTML5 history api. Use following code .
name = document.title
history.pushState(null,name,name)//add this code in your configuration.html file in document ready block
$(window).on("popstate",()=>{
//....Do whatever you want
/*If you want to display unauthorized page then
$(document).html("Unauthorized page")
*/
})

store the form data and reset the form just before the form data is sent to the server. Assuming that you are using $.ajax() to submit the form.
function submitEvent() {
form = document.createElement("form");
form.method = "POST";
form.action = "/confirmation";
// Add id attribute to the form
form.id = "student_details_form";
// Collect form data
// reset your form just before calling $.ajax() or $.post()
document.getElementById('student_details_form').reset();
// call $.ajax() or $.post()
$.ajax({
url: form.action,
// snipps
};
}

Related

Have a problem with disable button after click

I want to disable button after click for about 3 sec, I do that but I have a problem, on my web app it's working more than 10 users and I want to resolve that click button when someone click on that button it generate some sort of code, and when 2 users click in same time it generate same code two times.
It's server side web app.
Code bellow
#using (Html.BeginForm("GenerateCodes", "Index", FormMethod.Post))
{
<div class="box-header">
<div class="row">
<div class="col-md-3 text-right">
<button type="submit" id="ok" class="btn btn-primary btn-lg">Generate</button>
<script>
var fewSeconds = 5;
$('#ok').click(function () {
// Ajax request
var btn = $(this);
btn.prop('disabled', true);
setTimeout(function () {
btn.prop('disabled', false);
}, fewSeconds * 1000);
});
} </script>
</div>
</div>
</div>
Is it possible to do that with ajax and jQuery and should this pass to controller?

Pre-populate current value of WTForms field in order to edit it

I have a form inside a modal that I use to edit a review on an item (a perfume). A perfume can have multiple reviews, and the reviews live in an array of nested documents, each one with its own _id.
I'm editing each particular review (in case an user wants to edit their review on the perfume once it's been submitted) by submitting the EditReviewForm to this edit_review route:
#reviews.route("/review", methods=["GET", "POST"])
#login_required
def edit_review():
form = EditReviewForm()
review_id = request.form.get("review_id")
perfume_id = request.form.get("perfume_id")
if form.validate_on_submit():
mongo.db.perfumes.update(
{"_id": ObjectId(perfume_id), <I edit my review here> })
return redirect(url_for("perfumes.perfume", perfume_id=perfume_id))
return redirect(url_for("perfumes.perfume", perfume_id=perfume_id))
And this route redirects to my perfume route, which shows the perfume and all the reviews it contains.
This is the perfume route:
#perfumes.route("/perfume/<perfume_id>", methods=["GET"])
def perfume(perfume_id):
current_perfume = mongo.db.perfumes.find_one({"_id": ObjectId(perfume_id)})
add_review_form = AddReviewForm()
edit_review_form = EditReviewForm()
cur = mongo.db.perfumes.aggregate(etc)
edit_review_form.review.data = current_perfume['reviews'][0]['review_content']
return render_template(
"pages/perfume.html",
title="Perfumes",
cursor=cur,
perfume=current_perfume,
add_review_form=add_review_form,
edit_review_form=edit_review_form
)
My issue
To find a way to get the review _id in that process and have it in my perfume route, so I can pre-populate my EditReviewForm with the current value. Otherwise the form looks empty to the user editing their review.
By hardcoding an index (index [0] in this case):
edit_review_form.review.data = current_perfume['reviews'][0]['review_content']
I am indeed displaying current values, but of course the same value for all reviews, as the reviews are in a loop in the template, and I need to get the value each review_id has.
Is there a way to do this, before I give up with the idea of allowing users to edit their reviews? :D
Please do let me know if my question is clear or if there's more information needed.
Thanks so much in advance!!
UPDATE 2:
Trying to reduce further my current template situation to make it clearer:
The modal with the review is fired from perfume-reviews.html, from this button:
<div class="card-header">
<button type="button" class="btn edit-review" data-perfume_id="{{perfume['_id']}}" data-review_id="{{review['_id']}}" data-toggle="modal" data-target="#editReviewPerfumeModal" id="editFormButton">Edit</button>
</div>
And that opens the modal where my form with the review is (the field in question is a textarea currently displaying a WYSIWYG from CKEditor:
<div class="modal-body">
<form method=POST action="{{ url_for('reviews.edit_review') }}" id="form-edit-review">
<div class="form-group" id="reviewContent">
{{ edit_review_form.review(class="form-control ckeditor", placeholder="Review")}}
</div>
</form>
</div>
Currently this isn't working:
$(document).on("click", "#editFormButton", function (e) {
var reviewText = $(this)
.parents(div.card.container)
.siblings("div#reviewContent")
.children()
.text();
$("input#editReviewContent").val(reviewText);
});
and throws a ReferenceError: div is not defined.
Where am I failing here? (Perhaps in more than one place?)
UPDATE 3:
this is where the button opens the modal, and underneath it's where the review content displays:
<div class="card container">
<div class="row">
<div class="card-header col-9">
<h5>{{review['reviewer'] }} said on {{ review.date_reviewed.strftime('%d-%m-%Y') }}</h5>
</div>
<div class="card-header col-3">
<button type="button" class="btn btn-success btn-sm mt-2 edit-review float-right ml-2" data-perfume_id="{{perfume['_id']}}" data-review_id="{{review['_id']}}" data-toggle="modal" data-target="#editReviewPerfumeModal" id="editFormButton">Edit</button>
</div>
</div>
<div class="p-3 row">
<div class=" col-10" id="reviewContent">
<li>{{ review['review_content'] | safe }}</li>
</div>
</div>
</div>
You can do this with jQuery as when you open the form, the form will automatically show the review content in there. It will be done by manipulating the dom.
Also, add an id to your edit button, in this example, I have given it an id "editFormButton".
Similarly, add an id to the div in which review content lies so that it is easier to select, I have given it an id "reviewContent"
Similarly, add an id to edit_review_form.review like this edit_review_form.review(id='editReviewContent')
<script>
$(document).on("click", "#editFormButton", function (e) {
var reviewText = $(this)
.parents("div.row")
.siblings("div.p-3.row")
.children("div#reviewContent")
.children()
.text();
$("input#editReviewContent").val(reviewText);
});
</script>
Don't forget to include jQuery.
Also, you can do it with pure javascript. You can easily search the above equivalents on google. This article is a good start!

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

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?

phonegap chat application user can see others message

I am using phonegap to develop an one to one chat application. My problem is when user click a contact and send a message. Then user click go back button and click another contact it can still see the message which he just sent to the first user.
Here is a part of my code:
Here is using ajax to get contact from server.When it success,it will generate a list view to show all contacts.
$.each(contacts, function(i,item)
{
output += '<li data-name='+item+'>' + item + '</li>';
$('#contacts_list').html(output).listview('refresh');
//Show the contact name on the front of chat page
$('#contacts_list').children('li').on('click', function ()
{
var contact_name=$(this).attr('data-name');
$('#contact_name').html(contact_name);
get_name(contact_name);
});
});
<!--When someone click a user in contacts, it will show the chat page-->
<div data-role="page" id="chat_page" data-role="page" data-theme="a">
<div data-role="header">
<h1 id="contact_name"></h1>
</div>
<div data-role="content">
<div id="incomingMessages" name="incomingMessages" class="msgContainerDiv" >
</div>
<label for="messageText"><strong>Message:</strong></label>
<textarea id="messageText"></textarea>
</div>
<div data-role="footer">
<fieldset class="ui-grid-a">
<div class="ui-block-a">
Go Back
</div>
<div class="ui-block-b">
<button data-theme="a" id="chatSendButton" name="chatSendButton">Send
</input>
</fieldset>
</div>
</div>
And here is part of ajax code where I using ajax to get chat data, then append them in to my chat page.
success: function(data)
{
var get_data = JSON.parse(data);
$("#incomingMessages").append
(
"<div class='message'><span class='username'>" +
(get_data.from || 'Anonymous') +"</span> : " +
(get_data.message || ' ') + "</br>" +
(get_data.message_time || ' ')
+"</div>"
);
}
});
I know the reason is when user click contact it will always go to the same page and that is why message can be seen to all of users.
Is there any solution for this?
Thanks in advance.
A simple solution will be to use local storage to store the history (#incomingMessages) and #messageText for each user.
Then you can clear #messageText and just reload it when the user reopens the chat.
You should clear #incomingMessages when you switch users. You are likely leaving the HTML content in that div when you want to be replacing it with the new user's messages.
Something like
$('#incomingMessages').html('')

Categories

Resources