Basically, I have a form that is handled by a CMS which I cannot edit it's javascript, but I more or less want to add in a "Loading" or "Sending" message to my users. For example.
Currently, the default form once submitted, will append a html success message to a div called 'success' once sent, but basically, I want to run a function on the submit button that keeps checking the 'success' for anything other than '' and once it isn't empty, turn off the loading symbol.
Something like this perhaps:
$('#submitBtn').click(function(){
$('#loadingDiv').show();
while (!$('#success').html() == ''){
$('#loadingDiv').hide();
}
});
Any help would be greatly appreciated. I'm just not quite sure how to write it, I'm not great with jquery or javascript
You may do this with setInterval. Something like this:
$('#submitBtn').click(function(){
$('#loadingDiv').show();
var intervalId = setInterval(function() {
if($('#success').html() != '') {
clearInterval(intervalId);
$('#loadingDiv').hide();
}
}, 100);
});
while (!$('#success').html() == '') will freeze all other operations and will last forever.
But still - it is better to double check if you really can't add some code into success callback. Possibly ajaxComplete may help you.
Maybe you could send the form's data manually with something like this?
(In this case, maybe make sure that "submitBtn" is a simple button and not a submit button to prevent the default submit)
$('#submitBtn').click(function(){
$('#loadingDiv').show();
// Send the data with post - To complete
$.post('/your_post_addr', {data_1: my_data_1, ...},
function(data) {
$('#loadingDiv').hide();
}).error(function() {
// Your error message
alert('Error');
});
});
Related
Can anybody provide me an custom alert box saying "you are about to leave page and changes will be discarded" Yes/no.
I tried with following code but its giving me default message saying "Changes you made may not be saved"
here is my javascript code
unsaved=true;
window.onbeforeunload = function() {
if (unsaved)
{
var _message = "You currently have unsaved changes!!!\n\nAre you sure you want to exit without saving.\n\nChoose ‘Leave this page’ to exit without saving changes.\nChoose ‘Stay on this page’ to return to the billing profile.";
return _message;
}
}
Also I have no form but simple button which I can't include in form, on click of that button also it giving me warning. Here is Fiddle to try, any help really appreciated thank you. I know there are questions asked on this topic earlier but believe me none are working now.
update there are some methods explained in previous StackOverflow examples but they dont work now in modern browsers.
There's a method in JavaScript called window.confirm(): https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
if (window.confirm("Question"))
console.log('clicked OK');
else
console.log('clicked cancel');
Try this Jquery
$(window).bind('beforeunload', function(){
return 'Your message here';
});
Javascript
window.onbeforeunload = function(){
return 'Your message here';
};
I've put the function into form validation part, so that only when form is valid, the beacon would be sent. I am sure I am missing something. See code below.
function checkForm() {
var error = "";
if($("#first_name").val()=="") { error+="- Enter your first name.\n";};
if(error=="") {
_gaq.push(['_trackEvent','Form','Submit','Newsletter']);
return true;
} else {
alert("Please correct these form errors before you submit the form:\n\n"+error)
return false;
}
}
EDIT: Thanks everyone for their help! Tested this one, and 100ms doesn't seem to be enough.
Now I am thinking to do this a little more clever way. It would make sense to submit it, once all required fields have text in it, but it should be clever enough to submit more than once and submit only when data is valid!
Try to give a delay (may be about 100 miliseconds or less) using setTimeout() or setInterval() and let the GA datato be submited. Worked for me.
function gaSubmit(param){
_gaq.push(param);
}
function checkForm() {
var error = "";
if($("#first_name").val()=="") { error+="- Enter your first name.\n";};
if(error=="") {
setTimeout(gaSubmit(['_trackEvent','Form','Submit','Newsletter']),100);
return true;
} else {
alert("Please correct these form errors before you submit the form:\n\n"+error)
return false;
}
}
Are you sure if it's not fires? Probably there is some delay in analytics data refresh. If you develop your app on localhost, then you should set _setDomainName property to 'none'
_gaq.push(['_setAccount', 'Your-account-id']);
_gaq.push(['_setDomainName', 'none']);
#see:GA Event Tracking from localhost
I'm trying to check the CSS of an element every time a new entry is added to the FireBug console with jQuery.
I have the CSS checking working fine, but not the event for triggering the check.
I think I'm looking for something like "ajaxComplete" or "ajaxStart", but neither of those are getting triggered.
Example:
$(document).live("ajaxComplete", function() {
if($('#foo').css('display') == 'none') {
alert("no!");
} else {
alert("yes!");
}
});
Thanks in advance
Based on your comment
Everytime an AJAX GET request is sent, I want to check the CSS of an element.
It looks like you want the global ajaxSuccess event. The second parameter to the handler is the xhr object, which will give you a responseText property containing the result of the ajax load.
$(document).ajaxSuccess(function(e, xhr) {
alert("I just got back " + xhr.responseText);
});
Hello stackoverflow users and readers,
I am programming a quite easy thing with JS for Firefox/Gecko 2.x and have reached a problem that is a little far away from my knowledge.
The thing is: I read a the content of a file to a string using the following code:
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
]);
And right after reading the file I evaluate the following condition:
if (my_string.length == 0) {
//do something...
} else {
//do something else...
}
OK, so the problem is, although there are some characters in the file, if it's the first run of the script, it will always go to the first condition because it hasn't got time enough to read the file and load the characters into the string. On a second run, the global variable my_string has the previously acquired value, so it will go into the "else" condition.
The question is: How can I listen to a "file finished loading" event in JavaScript to prevent this behaviour?
Thank you very much.
as far as fetch is async it's normal my_string to be empty. You need to subscribe for some custom event or pass a callback somehow.
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
var evt = document.createEvent('Event');
evt.initEvent('inputReady', true, true);
evt.my_string = my_string;
document.dispatchEvent(evt);
});
and then subscribe for this event
document.addEventListener('inputReady', function(e){
alert(e.my_string);
});
P.S. Not tested
hello i am not familiar with NetUtil of Firefox/Gecko 2.x but the concept look familiar.
i assume that is because the
NetUtil.asyncFetch
call to your callback function after the
if (my_string.length == 0) {
//do something...
} else {
//do something else...
}
why not you try using the data in correct place
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
alert(my_string.length); //is here is also be 0 ???????
//do some stuff with the data
]);
I'm trying to send data from a form to an external script prior to submitting the form, yet I cannot seem to get the data to reach the external script unless I return false; on the form itself.
$(document).ready(function () {
// Handle Form-Submission
$("#mainForm").submit(function () {
// Reset Error Array
errors = new Array();
/* Validation Code Removed - Not Relevant */
// Check if errors exist
if (errors.length > 0) {
return false;
} else {
$("div.errors").html("");
$.post("post.php",{
"First Name": name_first.val(),
"Last Name": name_last.val(),
"Home State": home_state.val(),
"Primary Email": email_primary.val()
});
}
return false; /* Remove this line, and the $.post won't work. */
});
});
I ran into the exact same problem today. Like Marc says, it's because the ajax call is asynchronous. The simplest fix is to make it synchronous.
Use .ajaxSetup() before any ajax calls like such:
$.ajaxSetup({async: false});
Sending to two end points
I would try something like this instead of using async: true. Though it is notably more complicated, it would not freeze the interface.:
$(document).ready(function(){
// Handle Form-Submission
$("#mainForm").submit(function(e){
e.preventDefault();
var $form = $(this);
if($form.data('submitting')) return; // Avoid double submissions
$(':submit').attr('disabled','disabled'); // Disable the submit button
// Reset Error Array
errors = new Array();
/* Validation Code Removed - Not Relevant */
// Check if errors exist
if (errors.length > 0) {;
$(':submit').removeAttr('disabled'); // Enable the submit button
return false;
} else {
$("div.errors").html("");
$form.data('submitting',true); // Flag that a submission has started
$.post("post.php",{
"First Name":name_first.val(),
"Last Name":name_last.val(),
"Home State":home_state.val(),
"Primary Email":email_primary.val()},
function(){
// remove our special handler and submit normally
$form.unbind('submit').submit();
}
);
}
});
});
Original Answer
It seems your hangup is that you want to use $.post if JavaScript is enabled, but let the form function normally with JavaScript disabled.
However, since none of your JavaScript will run if it is disabled you don't have to worry about altering behavior in the submit function.
You can just leave your return false; statement, or use
$("#mainForm").submit(function(e){
// all your existing code
e.preventDefault();
}
That will keep the form from submitting normally and will instead using your $.post method when JavaScript is enabled. If it is disabled it will submit normally.
preventDefault is preferred to return false if you want event bubbling to continue as normal, but keep the default browser action from continuing. return false is the equivalent of calling e.preventDefault(); e.stopPropagation();