How can I conditionally allow or prevent submission execution? - javascript

The situation
I have a page in which I have multiple forms keeping track of the attendance and one progress_update.
On submit of the progress_update form I have got it so that ajax sends the attendance form submissions separately having used the preventdefault() method to stop the original submission, however I would like to on the condition that no errors were returned by the ajax methods allow the original submission that was originally prevented.
What I have so far:
The ajax function:
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
$.ajax({
type: "POST",
url: url,
data: {
attended: $('#attended' + i).val(),
score: $('#score' + i).val(),
writing: $('#writing' + i).val(),
speaking: $('#speaking' + i).val()},
success: function(data) {
if (data.data.message == undefined) {
allow=false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
}
The Intention:
The intention behind this ajax is to send the forms to a separate route for validation and then on success "receiving data.data.message == 'submitted'" pass to the next form in the loop, while on error set the allow variable to false and display the message in hopes to prevent the final form being submitted at the same time.
The call:
$('#update_form').submit(function (e) {
var allow = true;
for (var i = 0; i < studentcount ; i++) {
send_attendance(name=st[i], lesson=lesson, form_id='attendance-' + i, i=i)
}
if (allow == true){
} else {
e.preventDefault();
}
});
The Problem
In doing what I have done I have ended up with a situation of it either submits the ajax submitted forms and that is that preventing the submit form or it submits the form whether errors occured in the ajax that need to be displayed, now how do I get this to work in the way expected? I have tried the methods involved in these previous questions:
How to reenable event.preventDefault?
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
which revolve around using bind and unbind but this doesn't seem to work as needed and results in a similar error.
Any advice would be greatly appreciated.
Edit:
I have adjusted the code based on the comment below to reflect, however it still seems to be evaluating the allow before the ajax have completed. either that or the ajax function isn't changing the allow variable which is set in the submit() call how could i get this to change the allow and evaluate it after the ajax calls are complete?
The Ajax call
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
var form = $('#' + form_id)
$.ajax({
type: "POST",
url: url,
data: $('#'+ form_id).serialize(),
context: form,
success: function(data) {
console.log('done')
if (data.data.message == undefined) {
allow = false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
The function is being called here:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when(...deferreds).then(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});
I also tried:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when.apply(deferreds).done(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});

Related

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

render Django HTML tag using JavaScript

I have installed in my project django-contib-comments and I have an HTML that displays the list of comments and also displays the form to enter a new one.
I now want to use Ajax to submit the form without a page refresh and on success to add the submitted comment to the list.
I have done most of the work, but I'm sure there must be an easier way to achieve this.
my question is if there is a way for me to render a Django HTML tag within a javascript something like this:
document.getElementById("comments").innerHTML = {% render_comment_list for obj %}
so far this is the code I have done:
1) I don't want to change anything in the django-contrib-comments project (i am avoiding to override methods.
2) I used the standard tags in django-contrib-comments to render a list of comments.
{% render_comment_list for obj %}
3) Created a JavaScript that handles the submit of the form and then creates a new entry in the list.
function submit_comments(event) {
event.stopPropagation();
$.ajax({
type: $('#comment_form').attr('method'),
url: $('#comment_form').attr('action'),
data: $('#comment_form').serialize(),
cache: false,
dataType: "html",
success: function (html, textStatus) {
var comment_count_btn = document.getElementById('comment-text-vertical-btn');
if (comment_count_btn != null) {
if (!isNaN(parseInt(comment_count_btn.innerHTML))) {
comment_count_btn.innerHTML = parseInt(comment_count_btn.innerHTML) + 1 + " Comments";
}
}
var comment_count_head = document.getElementById('kapua-comments-header');
if (comment_count_head != null) {
if (!isNaN(parseInt(comment_count_head.innerHTML))) {
comment_count_head.innerHTML = parseInt(comment_count_head.innerHTML) + 1 + " Comments:";
}
}
if (document.getElementById("comments") != null){
submitted_timestamp = getQueryParameter("timestamp", this.data);
submitted_date = new Date();
if (submitted_timestamp == null) {
submitted_date = new Date(submitted_timestamp);
}
submitted_comment = getQueryParameter("comment", this.data);
if (submitted_comment == null) {
submitted_comment = "No value entered"
}
html_comment = "<div class=\"right-aligned\"><div class=\"comment-date\">" + submitted_date + " - " + "</div>" + submitted_comment + "</div><br><br>";
current_html = document.getElementById("comments").innerHTML;
document.getElementById("comments").innerHTML = html_comment + current_html;
}
if (document.getElementById("comment_form") != null){
document.getElementById("comment_form").reset();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.');
}
});
return false;
};
Thanks in Advance
Yes there is way in django, You can use [escape][1] to render HTML tag. Here is an simple example -
from django.utils.html import escape
def example(request):
return "%s<div><i>%s</i></div>" % (escape(text), escape(other_text)
For more explanation you can refer to documentation.
https://docs.djangoproject.com/en/2.1/ref/utils/#django.utils.html.escape
Still have any doubts comment it out.

Prevent sending data to DB/server if form validation is false (VueJS)

I want to stop sending information if form validation is false.
I have a button Save with two functions in it:
<span class="logInBTN" v-on:click="validationFields(); function2(model)">Save</span>
The form validation is being proccessed in validationFields():
validationFields() {
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
}
So if it's not chosen a type from the input field, function2() must not continue.
Update1:
<script>
export default {
components: {
},
data(){
return {
errors: [];
},
},
methods: {
validationFields() {
this.errors = [];
var falseValidation = false;
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
if(falseValidation == false){
this.createEori(eoriData);
}
}
createEori(eoriData) {
eoriData.state = '1';
eoriData.username = this.$session.get('username');
console.log("updateEori state: " + JSON.stringify(eoriData));
const url = this.$session.get('apiUrl') + 'registerEORI';
this.submit('post',
url,
eoriData
);
},
submit(requestType, url, submitData) {
this.$http[requestType](url, submitData)
.then(response => {
console.log('EORI saved!');
console.log('Response:' + response.data.type);
if("E" == response.data.type){
alert(response.data.errorDescription);
} else {
alert("Saved!");
}
})
.catch(error => {
console.log('EORI rejected!');
console.log('error:' + error);
});
},
},
}
</script>
createEORI is the function2
Update2
Now it works, but the data from the fields it's not send to the server. That's all fields from the page, some are datepickers or an ordinary input text field. Before the change in the browser console show this, if I write a name in the first field it will show up in c1_name etc:
{"state":"1","c1_form":"","c1_identNumber":"","c1_name":"","c1_shortName":"","c1_8_street":"","c1_8_pk":"","c1_8_name":"","c1_8_city":"","c1_8_codeCountry":"","c1_identNumber1":"","c3_name":"","c3_nameShort":"","c3_city":"","c3_codeCountry":"","c3_street":"","c3_pk":"","c3_phone":"","codePerson":"","codeActivity":"","c1_date":"","c5_date":"","c7_date":"","dateFrom":"","dateTo":"","c8_date":"","c1_numberVAT":"","c8_provider":"","c8_number":"","codeMU":"","agreed1":"","agreed2":"","username":"testuser"}
However, after the change the sent data or at least the seen data is only:
{"state":"1","username":"testuser"}
The log is from
console.log("updateEori state: " + JSON.stringify(eoriData));
from createEORI() function
I think it would be better practice to only call one function from the HTML. Something like this:
<span class="logInBTN" v-on:click="submit(model)">Save</span>
submit(model) {
if (this.validateForm(model) == true)
{
// submission process here (maybe call function2())
}
}
validateForm(model) {
if (this.model.codePerson == ''){
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
this.handleFalseValidation();
return false;
}
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
return true;
}
handleFalseValidation() {
alert("Form validation:\n" + this.errors.join(""));
}
Ok I fixed the problems with sending the data.
It was my fault.
I will copy the Chris answer. That worked.
When you call this.createEori(eoriData);, eoriData is undefined. It doesn't exist. Use this.createEori(); instead, and in the createEori function, remove the parameter and add var eoriData = {}; as first line. (note this is very basic javascript, how functions and variables work, and completely unrelated to Vue or server requests)

jQuery $.getJSON example fails when part of a function [duplicate]

I have a page with a single form on it. The form contains a text box and a submit button.
When the form is submitted, either by clicking the button, or by pressing enter in the textbox, I want to do a lookup (in this case, geocoding a postcode using Bing Maps), and then submit the form to the server, as usual.
My current approach is to add a handler for the submit event to the one-and-only form, and then call submit() when I've finished, but I can't get this to work, and haven't been able to debug the problem:
$(document).ready(function () {
$("form").submit(function (event) {
var postcode = $.trim($("#Postcode").val());
if (postcode.length === 0) {
return false;
}
var baseUrl = "http://dev.virtualearth.net/REST/v1/Locations/UK/";
var apiKey = "myKey";
var url = baseUrl + postcode + "?key=" + apiKey + "&jsonp=?";
$.getJSON(url, function (result) {
if (result.resourceSets[0].estimatedTotal > 0) {
var location = result.resourceSets[0].resources[0].point.coordinates;
$("#latitude").val(location[0]);
$("#longitude").val(location[1]);
$("form").submit();
}
});
});
});
event.preventDefault() is your friend here. You are basically experiencing the same problem as here. The form is submitted before the actual ajax request can be done. You need to halt the form submission, then do the ajax, and then do the form submission. If you don't put some stops in there, it'll just run through it and the only thing it'll have time to do is to submit the form.
$(document).ready(function () {
$("form").submit(function (event) {
// prevent default form submit
event.preventDefault();
var postcode = $.trim($("#Postcode").val());
if (postcode.length === 0) {
return false;
}
var baseUrl = "http://dev.virtualearth.net/REST/v1/Locations/UK/";
var apiKey = "myKey";
var url = baseUrl + postcode + "?key=" + apiKey + "&jsonp=?";
$.getJSON(url, function (result) {
if (result.resourceSets[0].estimatedTotal > 0) {
var location = result.resourceSets[0].resources[0].point.coordinates;
$("#latitude").val(location[0]);
$("#longitude").val(location[1]);
$("form").submit();
}
});
});
});
Howevern, when you put the preventDefault in there you can't continue the form submission with $('form').submit(); anymore. You need to send it as an ajax request, or define a conditional to the preventDefault.
Something like this perhaps:
$(document).ready(function () {
var submitForReal = false;
$("form").submit(function (event) {
var postcode = $.trim($("#Postcode").val());
if (postcode.length === 0) {
return false;
}
// prevent default form submit
if(!submitForReal){
event.preventDefault();
}else{
var baseUrl = "http://dev.virtualearth.net/REST/v1/Locations/UK/";
var apiKey = "myKey";
var url = baseUrl + postcode + "?key=" + apiKey + "&jsonp=?";
$.getJSON(url, function (result) {
if (result.resourceSets[0].estimatedTotal > 0) {
var location = result.resourceSets[0].resources[0].point.coordinates;
$("#latitude").val(location[0]);
$("#longitude").val(location[1]);
submitForReal = true;
$("form").submit();
}
});
}
});
});

Not able to send form parameters to the server

We are getting a issue wherein while submitting a form via javascript one of the parameters (invoiceCodes) is not sent to the server. Below is the snippet of the javascript code.
The flow is as follows. When user clicks on "Print" button validateTransition() method is called in which we make a ajax call. After response of that ajax we call couponPopup(url, invoiceCodes). In this function we submit newWinForm but sometimes invoiceCodes parameter is sent empty.
Also checkForInvoiceCode is true in this case which require user to input invoice codes
Is there anything wrong in the manner in which we are putting values in the form which may lead to invoiceCodes being not sent sometimes.
function couponPopup(url, invoiceCodes)
{
var selectedOrders = '';
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
});
var frm = document.forms["newWinForm"];
frm.action = url;
frm.selectedShipments.value= selectedOrders;
frm.invoiceCodes.value = invoiceCodes;
console.log("Selected orders are "+selectedOrders);
console.log("Invoice codes with them in order are "+invoiceCodes);
document.getElementById("hiddenInvoiceCodes").value=invoiceCodes;
document.getElementById("hiddenselectedShipments").value=selectedOrders;
frm.submit();
return false;
}
function validateTransition() {
$('#statusChangeSuccess').hide();
$('#statusChangeFail').hide();
var selectedOrders = '';
var invoiceCodes = '';
var flag = 0;
var spaceError = 0;
var commaError = 0;
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
<c:if test="${checkForInvoiceCode}">
var emptyPattern = /^\s*$/;
var commaPattern = /,/;
var inv_code = $("#invoice-code-" + $(this).val()).val().trim();
if (emptyPattern.test(inv_code)) {
spaceError = 1;
flag = 1;
}
if (commaPattern.test(inv_code)) {
commaError = 1;
flag = 1;
}
invoiceCodes += inv_code + ",";
</c:if>
});
if(selectedOrders=='') {
alert('Please select at least one order');
return false;
}
if ( flag ) {
if ( commaError ) {
alert('One or more specified codes have comma, please remove comma from them');
}
if ( spaceError ) {
alert('One or more specified codes has been left blank, please fill them up');
}
if ( !commaError && !spaceError ) {
alert('Please contact tech');
}
return false;
}
var inputdata = {"selectedShipments" : selectedOrders,
"statusCode" : "PRINT"
};
//this is where we are making an ajax call
jQuery(function($){
setTimeout(function(){
var ajaxUrl = '/product/update/';
$.ajax({url:ajaxUrl, type: "POST", dataType: 'json', data:inputdata , success: function(data) {
if(data['status'] == 'success') {
//couponPopup function is called where form is submitted
couponPopup("${path.http}/product/print/", invoiceCodes);
$('#statusChangeSuccess').html(data['message']).show();
$(".selectedOrder:checked").each(function() {
$("#row-" + $(this).val()).remove();
});
} else{
$('#statusChangeFail').html(data['message']).show();
}
}});
}, 10 );
});
return false;
}
<form id="newWinForm" name="newWinForm" action="" method="post" target="_blank" >
<input type="hidden" id="hiddenselectedShipments" name="selectedShipments" value="" />
<input type="hidden" id="hiddenInvoiceCodes" name="invoiceCodes" value="" />
</form>
Controller for the form. Invoice codes is sometimes empty even when we are sending it from client side.
#RequestMapping("/product/print")
public void printSelectedPendingOrders(#RequestParam("selectedShipments") String selectedShipments,
#RequestParam(defaultValue = "", value = "invoiceCodes", required = false) String invoiceCodes, ModelMap modelMap, HttpServletResponse httpResponse)
throws IOException, DocumentException, ParserConfigurationException, SAXException {

Categories