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

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

Related

How can I conditionally allow or prevent submission execution?

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

Prevent multiple Javascript execution for submit function

I am using the following code to allow users to submit content to an online board:
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
Unfortunately, if a user rapidly presses enter or rapidly clicks the send button, the code will execute multiple times and their message will be sent multiple times.
How can I modify my code to prevent this multiple execution?
A simple client-side fix would be to create a local variable that tracks whether or not anything has been submitted and have the function only execute if false.
var submitted = false;
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
if (submitted)
return false;
submitted = true;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
A better solution would be to send a unique token for the transaction to the client and have the client send it along with the request.
You could have server-side coded to verify that the token has only been used once.
found this solution here
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});

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/

Don't submit form until image is uploaded

I have got a validation script which validates my form first, if everything is okay it will return true (obviously PHP checks will be done as well after).
I have also got a JavaScript function which uploads the image and displays a progress bar, this is where things seem to be going wrong, the form is still submitting whilst the image is being uploaded, if it's uploading it should return false.
Form onsubmit call:
<form action="php/submitMessage.php" onsubmit="return !!(validation(this) && submitFile('image','reviewUpload'));" method="post" id="submitMessage">
Validation Script:
function validation(form) {
var inputs = form.elements;
var errors = Array();
for(var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("rules") != null && inputs[i].getAttribute("rules") != "") {
var re = new RegExp(inputs[i].getAttribute("rules"));
var OK = re.test(inputs[i].value);
if (!OK) {
inputs[i].style.backgroundColor = "#e39d9d";
errors.push(false);
} else {
inputs[i].style.backgroundColor = "#6dcd6b";
errors.push(true);
}
}
}
//Check array for any errors
if (errors.indexOf(false) == -1) {
return true;
} else {
return false;
}
}
This is my image upload script, people are not required to add an image, so I have made it return true IF NO image has been selected.
function submitFile(fileId,buttonId) {
//Has a file been selected
if (doc(file).value != "") {
//Generate a new form
var f = document.createElement("form");
f.setAttribute("method", "POST");
f.setAttribute("enctype", "multipart/form-data");
//Create FormData Object
var formData = new FormData(f);
//Append file
formData.append("image", doc(file).files[0], "image.jpg");
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
if (xhr.responseText == "true") {
return true;
} else if (xhr.responseText == "false") {
return false;
}
} else {
console.log("error!");
console.log("Error " + xhr.status + " occurred when trying to upload your file");
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
document.getElementById(buttonId).innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById(buttonId).style.backgroundSize = (currentPercentage+1) + "% 100%";
if (currentPercentage==99) {
document.getElementById(buttonId).innerHTML = "Processing image";
}
}
};
//Send data
xhr.send(formData);
} else {
return true;
}
}
Edit:
function handleSubmit() {
//Validate the form
var valid = validation(this);
var formElement = this;
//Check if validation passes
if (valid == true) {
//code here...
} else {
return false;
}
}
Even when validation() returns false the form is still submitting.
Form opening:
<form action="php/submitMessage.php" method="post" id="messageForm">
Writing this as answer as said by #Martin Ball
You can write single submit handler to do both validation check and image upload to get a better control of situation. Coming to your question, since image upload is asynchronous call submit functionality will not wait for completion of upload. You should handle success callback and submit after upload success and a separate submit handler will help in it.
e.g.
function handleSubmit () {
// validate your form
validation(this);
var xhr = new XMLHttpRequest();
// code to build XMLHttpRequest
var formElement = this;
xhr.onload = function (e) {
// code to handle success
// on success
// submit form
formElement.submit();
};
}
function validation () {
// logic to validate form
}
// attach submit to handler
var formElement = document.querySelector('submitMessage');
formElement.addEventListener('submit', handleSubmit);
Edit
In case you want to stop form from submitting you need to tell the event to stop doing the default action i.e. preventDefault.
see this jsbin for demo and code sample.
TLDR;
function handleSubmit (ev) {
var isValid = validation(this);
if(!valid) {
ev.preventDefault();
return false;
}
// further handling of submit action.
}

how to get response from a function and validate another function in jquery

when i click a button i want to validate two functions one by one and my functions are
validateEmail(email);
validatemobile(mobile);
what i am trying so far and my code is
when i click getotp button
$('.getotp').click(function(e) {
e.preventDefault();
var response;
var email=$('#email').val();
validateEmail(email);
if(response=true){
var mobile=$('#mob').val();
validatemobile(mobile);}});
my emailvalidation function is
function validateEmail(email){
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if(!valid)
{
$('.errornotice').text('Email Address Is Not Valid');
response=false;
}
else
{
response=true;
}
}//email validate function
and my mobile validation function is
function validatemobile(mobile){
//CHECK MOBILE NUMBER
if(mobile=='')
{
$('.errornotice').removeClass('nodisplay');
$('.errornotice').text('Mobile Number can not be empty');
e.preventDefault();
}
else if(mobile.toString().length>10 || mobile.toString().length<10 )
{
$('.errornotice').removeClass('nodisplay');
$('.errornotice').text('Mobile Number Must be 10 Digit');
e.preventDefault();
}
//send OTP
else
{
e.preventDefault();
$.ajax({
type:'POST',
url:"otp.php",
data:{mob:mobile},
success: function(data){
e.preventDefault();
$('.errornotice').text('check your mobile and enter OTP');
}//success
})//ajax
}//else
}//mobile validate function

Categories