How to make $.get call during form submission? - javascript

I don't want to submit my form with AJAX, but I want to make a progress bar by making a couple of GET requests to the server during form submission, since the submission might take a while with multiple file uploads. I've found that in webkit browsers, I can't make GET requests while the form is submitting and I was seeing that submitting the form to an iframe would allow me to do it.
The markup looks like this:
<form action="/my-action" target="target-iframe">
...
</form>
<iframe name="target-iframe"></iframe>
And the JavaScript:
$(document).ready(function() {
$("form").on("submit", function() {
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
I'm still not getting data back on the GET request--how can I get this to work?

$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault(); //stop the form from submitting
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
EDIT
Set a flag that won't allow the form to submit until you've received your response form your get request. Once you've received your response, set your flag to allow your form to submit and then resubmit it programmatically.
$(document).ready(function() {
var canISubmit = false;
$("form").on("submit", function(e) { //add a parameter e - the event object
var el = $(this);
if(!canISubmit) {
e.preventDefault();
$.get("/other-action", function(data) {
canISubmit = true;
el.submit();
});
}
});
});
The only way to be certain that your $.get request was completed is to make sure that the form doesn't submit and redirect the page until your $.get request completes.
EDIT #2
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault();
$.post("url",$(this).serialize())
.done(function(response,status,jqXHR) {
$.get("/other-action")
.done(function(response,status,jqXHR) {
//other stuff done
//refresh the page or do whatever....
})
.fail(function() {
//$.get failed
});
})
.fail(function() {
//$.post failed
});
});
});

Related

Refresh page after Ajax call

I have two pages, on the first page you can select an item with a <select> </select>. When you select an item, a form is automatically displayed through an AJAX Call. In this form, data is automatically loaded from a mysql db in a <textarea> </textarea>. The moment you submit your form, I want the new data to be added to the <textarea> </textarea> I just can't manage this, who can help me?
$(document).ready(function () {
$("#btnAdd").click(function (e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
$.post("save.php", {
besproken: besproken,
}, function (data) {
$("#autoSave").html("Coaching ");
$("#btnAdd").attr("disabled", true);
});
return false;
});
});
If all you want to do is insert the data into the textarea just use jQuery to selected the element $("textarea") then call the text method and pass in your data .text(data). The result call will look like $("textarea").text(data)
$(document).ready(function() {
$("#btnAdd").click(function(e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
$.post("save.php", {
besproken: besproken,
}, function(data) {
$("#autoSave").html("Coaching ");
$("#btnAdd").attr("disabled", true);
$("textarea").text(data);
});
return false;
});
});
You can take a div. When you click submit you will get a ajax response, load this inside the div.
success: function(data){
$("#status").load("url of the php-file");
or
$("#status").html(data);
}

JQuery function POST on the same page works only twice

The function below allows me to use an href link to POST request to the same page. It works for the first 2 times I click on the link, but this function doesn't seem to be recognized after a third POST request.
$(function() {
$('.sort-link').on('click', function(e) {
e.preventDefault();
$.post(this.href, function(data) {
$('.container').html(data);
});
});
});
I need to modify the function to have it work even after a POST request has been submitted.
As per #Elvin85's advice, I revised my function as follows:
$(function() {
$(document).on("click", '.sort-link', function(e) {
e.preventDefault();
$.post(this.href, function(data) {
$('.container').html(data);
});
});
});
It was a DOM-related issue.

Interplay between <form> and .ajax()

Folks,
I'm learning Ajax by tinkering. At first, I had a form with button, which made an Ajax call to a dummy controller action. The HTML and JavaScript on the client side.1
<form method="post">
<button name="btnSaveProject" title="When you save this project, it willl be available for 30 days.">
Save
</button>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("button[name='btnSaveProject']").click(function () {
console.log("make ajax call");
$.ajax({
url: "/Project/Save",
type: "GET",
timeout: 8000,
cache: false
}).done(function () {
console.log("ajax call successful");
}).fail(function (jqXHR, textStatus) {
console.log("something went awry. " + textStatus);
}).then(function () {
console.log("always just in case");
});
});
});
</script>
A strange thing was happening when I clicked the button. The Ajax call would reach the server (I know thins because I had a break point in the controller action, which triggered). But neither neither .done(), nor .fail(), nor .always() was getting called back on the client-side.
Then I have moved the <button> out of the <form>, and now .done(), and .always() get called back as expected. There seems to be some interplay between the can Ajax call. What is this interplay? Where can I learn more about it? What do I have to do to be able to use Ajax inside a <form>?
Here's the server-side code, but I suspect that it's a non-factor.
// AJAX: /Project/Save
public ActionResult Save() {
System.Threading.Thread.Sleep(600); /// <bring-up>A bit of latency to make the Ajax call more noticeable.</bring-up>
return Json("lorem ipsum", JsonRequestBehavior.AllowGet);
}
1 I have stripped down the code and kept only the parts that I think are applicable to the question. If I have stripped down too much, please let me know: I'll post more code.
You can add a type to your button:
<button type="button" name="btnSaveProject"
or just prevent the defaults of button to submit the form with event.preventDefault():
$("button[name='btnSaveProject']").click(function (e) {
e.preventDefault();
// other code as is
});
Since the button is in a form its default click action is to submit the form, So in your case as soon as the ajax request is sent the actual page is submitted which I think is reloading the page causing the callback handler to unload that is why those are not getting called
One solution is to prevent the default action of the click event by calling event.preventdefault()
$(document).ready(function () {
$("button[name='btnSaveProject']").click(function (e) {
//prevent the default action of the button click which is to submit the form
e.preventDefault()
console.log("make ajax call");
$.ajax({
url: "/Project/Save",
type: "GET",
timeout: 8000,
cache: false
}).done(function () {
console.log("ajax call successful");
}).fail(function (jqXHR, textStatus) {
console.log("something went awry. " + textStatus);
}).then(function () {
console.log("always just in case");
});
});
});
But since you are using a form, instead of a button click event it will be better to use a form submit event like
$(document).ready(function () {
$("form").submit(function (e) {
//prevent the default action of the button click which is to submit the form
e.preventDefault()
console.log("make ajax call");
//your ajax code
});
});
Another option is to set the type of the button to button so that the form submit will not be triggered like
<button type="button" name="btnSaveProject" title="When you save this project, it willl be available for 30 days.">Save</button>

Prevent click before AJAX response

I'm submitting a file with ajax.
Until I get the answer from the request, I show a modal window, but if my users click on the modal before it get the answer, the AJAX request gets canceled. I'm looking for a way to prevent that.
I'm using https://github.com/malsup/form/ to post with ajax
Full code is here : http://jsfiddle.net/WC9xn/4/
Thanks
$('form').on('submit', function (e) {
// Show loading modal popup
$("#dialog-modal").dialog({
height: 140,
modal: true
});
$(".ui-dialog-titlebar").hide();
e.preventDefault();
// prevent native submit
$(this).ajaxSubmit({
url: '/unitary/import_ajax',
type: 'post',
dataType: 'json',
iframe: true,
success: function (data) {
$('#dialog-modal').hide();
if (data == 'error') {
alert('error, invalid file');
} else {
var event = jQuery.Event;
submitForm(event, data);
}
}
})
});
function submitForm(event, data) {
//Do some stuff
}
$('form').off('submit').on('submit', function (e) {
// Show loading modal popup
$("#dialog-modal").dialog({
height: 140,
modal: true
});
havent tried, but see if it works, just add the off('submit').
I tried everything without success...
Remember that I'm using ajaxSubmit() with iframe option on. (for compatibility with IE).
Apparently, clicking on the modal actually clicks on the iframe witch cause the POST ajax request to get canceled.
I decided to recreate a modal on my own without jquery. Here's what I'm using now
var loading = $('<div>').prop('id', 'loading');
loading.html('<div id="loading_box"></div><span id="loading_txt"><span id="loading_txt">Import...</span>');
$('form').on('submit', function(e) {
loading.appendTo('body');
// disable left click
var event = $(document).click(function(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
});
// disable right click
$(document).bind('contextmenu', function(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
});
$(this).ajaxSubmit({
[...]

How can we check postback occur before postback to server by javascript

I Want to Show Loading Image during post back.
When submit event occur it's OK but i want to show for all post back
event.
Problem is I need to check post back occur or not before post back
to server.
jQuery
$("#form1").live("submit", function () {
$('#dvLoading').fadeIn(2000);
});
$("#form1").live("click", function () {
if( **// here I need to check postback occur or not before postback**) {
$('#dvLoading').fadeIn(2000);
}
});
$(document).ready(function () {
$('#dvLoading').hide();
});
HTML
<div id="dvLoading">
<img src="Styles/images/Processing.jpg" />
</div>
From what I understand, you want to check if the postback has already occurred in your 'click' handler. You could do this by defining a variable to check if the postback has already occurred.
var postbackCalled = false;
$("#form1").live("submit", function () {
$('#dvLoading').fadeIn(2000);
postbackCalled = true;
});
$("#form1").live("click", function () {
if(!postbackCalled) {
$('#dvLoading').fadeIn(2000);
}
});

Categories