I'm using ajax for my form because I don't want the page to reload after submit.
Now is everything working but the only problem is that the ajax script runs everytime I click the submit button.
I thought I could just paste the ajax in my if statement that tells when to run and when not, but it doesn't work.. anyone have any idea why?
theForm.onsubmit = function() {
if (pion == 1 || myName.value.length == 0 || myMessage.value.length == 0) {
if (pion == 1 || emailValid.value.length == 0) {
emailValid.style.border = "1px solid red";
myError.innerHTML = "U heeft geen geldig e-mail adres ingevoerd.";
}
if (myName.value.length == 0) {
myName.style.border = "1px solid red";
myError.innerHTML = "U heeft geen naam ingevuld.";
}
if (myMessage.value.length == 0) {
myMessage.style.border = "1px solid red";
myError.innerHTML = "U heeft geen bericht ingevuld.";
}
return false;
}
else {
// the ajax I found somewhere, that works but not in this if/else statement
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
return true;
}
}
This code block:
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
bound the function that sends the AJAX request to your form element's submit event. Once it did, the function remains bound forever (or at least until you explicitly unbind it). That's why once your code falls in the else statement for the first time, the AJAX request will be sent every time the form is submit.
That said, your if/else logic should be inside the function that is bound to your form's submit event in order to send the AJAX request conditionally. Something like:
$('form').bind('submit', function () {
if (etc etc etc) {
// do other things
}
else {
// send AJAX
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
}
});
return false;
});
// the ajax I found somewhere
Copying/pasting code into your project without any knowledge of what that code does is a famously bad idea.
This code doesn't make an AJAX call:
$(function () {
// anything in here
});
What this code does is tell jQuery to execute that function when the document is ready. But presumably the document is already ready when you invoke this, since it's happening on a form submit event.
At best, depending on how the internals of jQuery works, it might be executing that inner function immediately. But still, you don't need that wrapping call to jQuery.
But then, what is that function doing?:
$('form').bind('submit', function () {
// anything in here
});
Again, it's not actually executing any AJAX code. All this is doing is binding a function to the form's submit event. That function may contain AJAX code (and in this case it does), but that's not being executed here. It will be executed when the form is next submitted.
But, you're doing this every time you submit the form. So what's happening is:
User presses submit, nothing visibly happens. 1 event handler is bound to the next submit event.
User presses submit, 1 event handler (AJAX) is executed, 2 event handlers are now bound to the next submit event.
User presses submit, 2 event handlers (AJAX) are executed, 4 event handlers are now bound to the next submit event.
and so on...
If you want to call the AJAX code in the else block, then just call it in the else block:
if (/* ... */) {
// ...
} else {
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
}
Related
I have a form, on submit of that I am making an ajax request which is sometimes taking time to get the request, so what I am trying to do is whenever user refresh or clicks back button of the browser after form submitting i want to abort that ajax call
What I am doing is
$("#formId").submit(function(event) {
event.preventDefault();
var xhr = $.ajax({
url : "Drilldown",
method : "GET",
success : function(data) {
// here doing ,my stuff
},
complete : function() {
$('.loader').hide();
$('.overlay').hide();
}
});
window.onbeforeunload = function() {
return "some message"; // here when user clicks on leave then want to abort like `xhr.abort`
};
});
whenever the user clicks on leave I want to abort my ajax request
How can I do that?
**I specifically want to do that when ever form submit and once form is submitted,i want to abort that function also onbeforeunload **
You can directly xhr.abort() in "onbeforeunload" event handler method:
// Define xhr variable outside so all functions can have access to it
var xhr = null;
$("#formId").submit(function(event) {
event.preventDefault();
xhr = $.ajax({
url: "Drilldown",
method: "GET",
success: function(data) {
// here doing ,my stuff
},
complete: function() {
$('.loader').hide();
$('.overlay').hide();
}
});
});
window.onbeforeunload = onUnload;
function onUnload() {
if(xhr) xhr.abort();
return "some message";
};
call below method to abort ajax call
xhr.abort()
I want to change the content of an element using .html() to indicate that a process has started.
But the problem is that it won't work no matter what I do. I might be missing something here that prevents the script from working.
Code:
if(counter < 1 && flag == true){
alert("test");
$("#updownform").html("Please Wait...");
// if(confirm("Are you sure you want to proceed?")){
// counter++;
// $.ajax({
// method: "POST",
// url: "index.php?module=Accounts&action=processUpdowngrade",
// data: {form_data: $(this).serialize()},
// success: function (datas) {
// counter = 10000;
// location.reload();
// }
// });
// }else{
// $("#updownform").html("Save changes");
// }
}
In this example where everything is commented out except for the alert and .html(). The .html() works but if I uncomment everything it will only work when AJAX is finished with the request even after the confirm condition was triggered. Which I found weird since I already placed it before the confirm condition. So ideally it would have executed before the confirm condition.
I also tried using beforeSend but it still didn't work. I also tried setting it to asynch:false/true together with beforeSend to no avail.
I would recommend trying the code below to see if it helps.
<script>
if (counter < 1 && flag == true) {
alert("test");
document.getElementById("updownform").value = "Please Wait...";
if (confirm("Are you sure you want to proceed?")) {
counter++;
$.ajax({
type: "POST",
url: "index.php?module=Accounts&action=processUpdowngrade",
data: $("#enter_your_form_id").serialize(), // serializes the form's elements.
success: function(data) {
counter = 10000;
location.reload();
}
});
} else {
document.getElementById("updownform").value = "Save changes";
}
}
</script>
Based on some JSON I recieve from an ajax request, I wish to either allow or deny a submit button press (return true/false).
I've attempted to implement a promise, however, I can still see 'product unavailable' is called before I recieve my ajax response.
Is the issue down to it being a form/submit button? Or is this still possible?
var oAH = {
ValidateSubmit : function(self){
// send request to handler
$.ajax({
type: "POST",
url: "",
data: aData,
cache: false})
.done(function(data) {
var oJSON = JSON.parse(data);
if(oJSON.Status === 1){
// return true to allow form to submit
return true;
}else{
console.log('product unavailable (error message)');
return false;
}
})
}
}
// click handler
$('#submitButton').on('click', function(){
return oAH.ValidateSubmit(this);
}
You have number of issues. The most obvious one is that you can't just return from asynchronous code (promise) to use its return value (it's undefined!).
What you need to do is
prevent form submission by default for all cases.
treat promise properly and check returned flag. If it's true, submit form manually using DOM API (form submit method).
make sure you use onsubmit event instead of button onclick.
All together it would look something like this:
var oAH = {
ValidateSubmit: function(self) {
// send request to handler
return $.ajax({
type: "POST",
url: "",
data: aData,
cache: false
})
.then(function(data) { // <----- make sure you use .then
return data.Status === 1;
});
}
}
// form onsubmit handler, form has id form for example, etc.
$('#form').on('submit', function(e) {
var form = this;
e.preventDefault()
return oAH.ValidateSubmit(this)
.then(function(canSubmit) {
if (canSubmit) {
form.submit();
}
});
});
I think what you try to do is not possible. The UI event must be processed at the moment and the ajax request is async.
You could prevent form submiting when clicked, disable button and wait for ajax to return a value and then submit form or not in a callback, something like this:
var oAH = {
ValidateSubmit : function(self){
// send request to handler
$.ajax({
type: "POST",
url: "",
data: aData,
cache: false})
.done(function(data) {
var oJSON = JSON.parse(data);
if(oJSON.Status === 1){
// return true to allow form to submit
submitForm();
}else{
console.log('product unavailable (error message)');
}
})
}
}
function submitForm() {
$('#myForm').submit();
$('#submitButton').removeAttr('disabled');
}
// click handler
$('#submitButton').on('click', function(e){
//prevent submitting
e.preventDefault();
// Disable, you could show a loading animation/gif
$(this).attr('disabled','disabled');
// call ajax
oAH.ValidateSubmit(this);
}
I wanted to make an ajax call, and then wait for the response from ajax call (Stop form submission till then) and then post the form based on the ajax response that I get. This question is based on Make ajax call and then submit form. So, after putting below script, everything works fine, but I lose the client side validation. Can I make an ajax call and still respect the Client Side validation?
#section scripts {
<script>
var canSubmit = false;
$('form').submit(function (e) {
if (!canSubmit) {
e.preventDefault();
var data = $('form').serialize();
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (response) {
if (response.hasPreviousRequest) {
if (confirm("You've already applied for this job. Apply again?")) {
canSubmit = true;
$('form').submit();
}
}
else {
canSubmit = true;
$('form').submit();
}
},
error: function () {
alert("error");
}
});
}
});
</script>
}
P.S: Kindly note that as soon I as remove the ajax call Client side validation starts working fine. Can some one please explain me this behaviour?
You need to call the .valid() method on the form element (and if not, then cancel the ajax call)
$('form').submit(function (e) {
if (!$(this).valid()) {
return // exit
}
if (!canSubmit) {
....
I have form autocomplete code that executes when value changes in one textbox. It looks like this:
$('#myTextBoxId)').change(function () {
var caller = $(this);
var ajaxurl = '#Url.Action("Autocomplete", "Ajax")';
var postData = { myvalue: $(caller).val() }
executeAfterCurrentAjax(function () {
//alert("executing after ajax");
if ($(caller).valid()) {
//alert("field is valid");
$.ajax({ type: 'POST',
url: ajaxurl,
data: postData,
success: function (data) {
//some code that handles ajax call result to update form
}
});
}
});
});
As this form field (myTextBoxId) has remote validator, I have made this function:
function executeAfterCurrentAjax(callback) {
if (ajaxCounter > 0) {
setTimeout(function () { executeAfterCurrentAjax(callback); }, 100);
}
else {
callback();
}
}
This function enables me to execute this autocomplete call after remote validation has ended, resulting in autocomplete only when textbox has valid value. ajaxCounter variable is global, and its value is set in global ajax events:
$(document).ajaxStart(function () {
ajaxCounter++;
});
$(document).ajaxComplete(function () {
ajaxCounter--;
if (ajaxCounter <= 0) {
ajaxCounter = 0;
}
});
My problem is in IE (9), and it occurs only when I normally use my form. Problem is that function body inside executeAfterCurrentAjax(function () {...}); sometimes does not execute for some reason. If I uncomment any of two alerts, everything works every time, but if not, ajax call is most of the time not made (I checked this by debugging on server). If I open developer tools and try to capture network or debug javascript everything works as it should.
It seems that problem occurs when field loses focus in the same moment when remote validation request is complete. What I think it happens then is callback function in executeAfterCurrentAjaxCall is executed immediately, and in that moment jquery validation response is not finished yet, so $(caller).valid() returns false. I still do not know how alert("field is valid") helps in that scenario, and that could be sign that I'm wrong and something else is happening. However, changing executeAfterCurrentAjaxCall so it looks like this seems to solve my problem:
function executeAfterCurrentAjax(callback) {
if (ajaxCounter > 0) {
setTimeout(function () { executeAfterCurrentAjax(callback); }, 100);
}
else {
setTimeout(callback, 10);
}
}