cancel page loading state in ajax - javascript

I have a script which handles post form and uses document.write with event.preventDefault
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function(event) {
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).success(function(result) {
document.write(result);
});
event.preventDefault();
});
});
</script>
After I press submit and call document.write - my browser enters in infinite loading page state. If I remove preventDefault() - it works, but I need it for other script part to work..
Is there a way to cancel page loading state right after document.write ?

I can't see why event.preventDefault would be a problem here... Try the following code :
$(document).ready(function () {
$('#myForm').submit(function (event) {
event.preventDefault();
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).complete(function (result) {
$("body").html(result);
});
});
});
with complete instead of success to be sure that you haven't an error in your AJAX.

Related

AJAX Submitting Single Forms on Page

I have 2 forms on the same page and want them to submit independently of each other using AJAX. The code I currently have is:
<script type="text/javascript">
$("#form_tab").on("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(data){
$('#ResponseDiv').html(data);
}
});
});
</script>
When I put both form id's to form_tab they both submit when the other is. How Can I make they both submit interdependently with the same code? Thanks!
ID's must be unique or else you will have problems with JavaScript. You can use
$('form').on('submit', function() {
var formID = $(this).id; // get this form's id
Then you can use the ID, if you need to, to handle processing for each form.

javascript don't show alert when I use a javascript:window.location.reload()

I m trying to create a link that when clicked won't redirect but will perform an action and then refresh the page using jquery.
Click Me
<Span id="updateMe">1</span>
Jquery
$('#btnClick').click(function(e){
url = $(this).attr('href');
$.ajax({
url: url,
success: function(){
alert("succes alert 1 worked");
}
});
$.ajax({
url: "another_url.php",
success: function(data){
$("#updateMe").html(data);
}
});
javascript:window.location.reload();
});
Do these:
Add e.preventDefault(); to stop reload.
Move reload() to the success callback.
Get rid of javascript:. You are already inside it.
Corrected Code:
$('#btnClick').click(function(e) {
e.preventDefault();
url = $(this).attr('href');
$.ajax({
url: url,
success: function() {
alert("succes alert 1 worked");
window.location.reload();
}
});
$.ajax({
url: "another_url.php",
success: function(data) {
$("#updateMe").html(data);
window.location.reload();
}
});
});

AJAX/JQuery: Submit form and call function without refreshing page

I'm attempting to use ajax/jquery to submit a form comprised of dropdown menus, with the intention of displaying information from a MySQL database based on the form input. Without ajax/jquery, the page functions properly. However, I don't want the page to refresh once the form is submitted, so that the selected dropdown options remain showing. My ajax/jquery is not very good, and I know this is where I'm having trouble. my code is as follows:
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(){
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
the function displayResults is the function that I want to call when the form is submitted, but as of right now, when i click submit, the form refreshes and no results are displayed. Any help would be greatly appreciated. Thanks in advance.
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(e){
e.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
This prevents the form from submitting by preventing the event from firing. In vanilla javascript you could return false on submit and it would be the same.
Try this way to submit your form and prevent default behavior of form submit using e.preventdefualt() which will prevent event from firing,To serialize form data use serializeArray() ,use success and error to debug ajax call.
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
console.log(data); //display data Results
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(errorThrown); // dispaly error
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
The .submit() it will be the same as use the submit button. You have to use a button with the click event.
<script>
$(document).ready(funtion(){
var data1 = $('#field1').val();
// the same with all the values
$('#button').click(function(){
$.ajax({
type: "POST",
data: ({dat1: data1} ),
cache: false,
success: function(data) {
displayResults();
}
});
});
});
</script>

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

Looped ajax only submits sometimes

I am working on a dynamic page with multiple forms that can be added and removed by the user. My jquery script goes and finds all 'form' elements and submits them with jquerys ajax method. Here is the script
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
}
});
}
});
window.location.replace('/campaign');
});
})(); //end SIAF
});//end document.ready
The problem occurs that only sometimes the form submits, I can get it to if I click the save button a few times or if I remove the window.location.redirect that runs at the end, I suspect it is something to do with the redirect occurring before the submit, but I am not sure of a solution after going through some of the documentation
You are being caught out by the asynchronous nature of Ajax. Ajax does not work in a procedural manner, unfortunately. Your success method is called as and when the Ajax request has completed, which depends on your internet connection speed and how busy the server is.
It is entirely possible, the javascript completes its each loop and the first ajax request is still sending or waiting for a response. By when the javascript is ready to do a window.location call.
Edit:
Added code to check the number of forms, and the number of ajax requests, once they have all run, it will redirect
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
var numForms = $('form').length;
var numAjaxRequests= 0;
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
numAjaxRequests++;
if(numAjaxRequests == numForms) {
window.location.replace('/campaign');
}
}
});
}
});
});
})(); //end SIAF
});//end document.ready

Categories

Resources