First ajax request is triggered after mouse click of Button A. Based on response received another ajax request is fired. This another request is fired in ajaxComplete event handler.
So my continuous ajax request chain works well.
Now I have a condition, if Button B is clicked, I need to break ajax chain.
Code worked in Chrome browser. In case of Firefox, Button B's onclick is not getting triggered. Also generic $(document).on('click'.. event is not getting catched.
$.ajax({
url: url,
async: false,
type: post,
dataType: dataType,
data: data,
success: xyz,
error: abc
});
...
xyz = function() { binded = true }
...
$(document).ajaxComplete(function() {
if(binded || binded=='true') {
//fire ajax requests again and again till server gives timeout
}
});
$(document).on('click', 'input[id=openApplication]', function(event) {
binded = false;
alert('Breaking ajax loop');
// do form submit using Input - Sumbit type
});
Related
I have an ajax call on click of anchor tag in WordPress and I have not control over this. But before this ajax call I want to fire click event.
This click event is firing sometime but not every time. So I am not getting consistent results. Is there any way so that I can get correct results and get this click event fire before ajax call. I have tried putting my code in header and in footer as well.
Here is my code that i am using for click event.
jQuery(document).ready(function(){
jQuery("#addbtn").click(function(){
});
});
Any suggestion about this will be much appreciated.
you can use befor beforeSend
This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
source: https://api.jquery.com/Ajax_Events/
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
/*using a loader while waiting or fire an event or execute a function */
},
success: function(data) {
//execute a function on request sucess
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
},
complete: function() {
//execute a function once the call completed
}
});
I hope this will help you slove the issue
I am firing an ajax call on a signup form wherein i am checking whether the email id entered by the user has already been used or not.
Ajax Function :
<script>
$( "#becomesignup" ).submit(function( event ) {
$.ajax({
url : 'login', // Your Servlet mapping or JSP(not suggested)
data : {"email":$("#becomeemail").val()},
type : 'GET',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
if(response == "true"){
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
event.preventDefault();
}else{
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
}
$('.black-screen').hide();
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
</script>
In the above ajax function, if the response is true then the email id is already been used and i need to show an error div($('#emailerrorbecome').slideUp();) and then prevent the form to get submitted. But even event.preventDefault() is not working causing the emaild id to be registered again.
Please help me with this. TIA
You should submit the form programatically and always preventing default behaviour in jq submit handler. E.g, using context and calling submit() DOM API method:
$("#becomesignup").submit(function(event) {
event.preventDefault(); /* prevent form submiting here */
$.ajax({
context: this, /* setting context for ajax callbacks*/
url: 'login', // Your Servlet mapping or JSP(not suggested)
data: {
"email": $("#becomeemail").val()
},
type: 'GET',
dataType: 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success: function(response) {
if (response == "true") {
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
$('.black-screen').hide(); /* hide it here */
} else {
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
this.submit(); /* 'this' refers to the FORM, and calling submit() DOM native method doesn't fire again jq handler */
}
},
error: function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
For explanation of the why, see Quentin's answer
You cannot prevent the submit long after the submit function has returned. The Ajax result occurs much later.
You can instead flag the submit (e.g. use a sentinel variable) and cancel it unless allowed. Then trigger a submit from code in the Ajax callback.
Example:
var allowSubmit = false;
$( "#becomesignup" ).submit(function( event ) {
if (!allowSubmit){
$.ajax({
url : 'login', // Your Servlet mapping or JSP(not suggested)
data : {"email":$("#becomeemail").val()},
type : 'GET',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
if(response == "true"){
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
// Enable next submit to proceed
allowSubmit = true;
// And trigger a submit
$( "#becomesignup" ).submit();
}else{
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
}
$('.black-screen').hide();
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
// return false does e.preventDefault(), and true allows it to proceed
return allowSubmit;
});
You are calling preventDefault to late.
Order of execution is this:
Event handler fires
HTTP request is sent
Event handler finishes
Prevent Default was not called so the default behaviour occurs
HTTP response is recieved
Success handler fires
Prevent Default is called … too late to have any effect
You can't wait for the HTTP response to come back before preventing the default behaviour.
You either need to always prevent the default behaviour and then conditionally resubmit the form with JS in the submit handler, or move the logic for when you use Ajax to perform your tests so it doesn't depend on the form submission event in the first place (e.g. run it as soon as the data has been entered and be prepared for the possibility that the form might get submitted before your JS has finished running).
you can make use of return false instead of eventPreventDefault.
I had been using the location.reload() as a dirty hack to refresh the page to prevent submission, but return false works well even without a refresh, it doesn't submit the form.
I want to make an AJAX request when the user attempts to submit a form. However, I don't want to wait for the response (I just want to trigger a script) and still submit the form immediately (or redirect the user).
I tried to to it this way (via jQuery):
$(document).ready(function()
{
$("#form").submit(function(e)
{
// save object reference
var form = this;
// prevent form submit
e.preventDefault();
// trigger ajax request
$.ajax({
url: 'ajax.php',
data: { ... },
cache: false
});
// submit form
form.submit();
// return false just in case
return false;
});
});
But this won't work, because the AJAX request will in fact not be sent by the browser, if the form is submitted immediately afterwards (via form.submit() ).
I am a bit puzzled here... is there really no way to fire an AJAX request and redirect the browser immediately afterwards?
It seems you create an infinite loop here. You are preventing the submit event and submitting it again at the end, but when you bind your function to the form's submission it will be called over and over. Instead, try to use Ajax states like success and complete; on success you submit data and on complete you redirect the page.
I want to trigger this function, which uses the jquery's post method, when a form is submitted:
function update_point_session(){
$.post('/update_point_session/',
{session: true},
function(data){}
);
return true;
}
I uses the onsubmit to trigger it.
The problem is that it won't send it when the form is submitted. But if I return false; it will (though the form itself, of course, will not). It looks as if the $.post is not send before the page is directed to another one by the form..
So I think I somehow have to return true; AFTER the $.post. I tried to do this by putting it inside function(data){} but it did not work..
How can I send BOTH the post from jquery and from the form?
There are a couple of things you can do.
Make the AJAX synchronous
Since $.post is, according to the documentation, equivalent to
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
You can simply replace $.post with the equivalent $.ajax call, and also add async: false to the options. This will submit the form with AJAX and then, due to the return true; from the function, will also let the browser post the form normally.
Submit the form only after the AJAX completes
This involves some event handler juggling:
// attach submit event handler to the form
$("#myform").submit(function() {
// Handler immediately detaches itself, so that
// we don't have an infinite loop when we call
// $(this).submit() ourselves below
$(this).unbind('submit');
// Do the AJAX
$.post(
'/update_point_session/',
{session: true},
function(data){
// When the AJAX completes, tell the browser
// to re-submit the form
$(this).submit();
}
);
// Prevent the browser from submitting it NOW,
// because the AJAX is still running
return false;
});
You must wait for the asynchronous post to complete before unloading the page. You can send back a redirect url from the server as json something like this:
$('form').submit(function(e){
$.post(this.action || '/update_point_session/', $(this).serialize(), function(data){
// send back a redirect url from the server
if(data.url) location.href = data.url;
});
e.preventDefault()
});
I would do something like this.
$('form#myFormId').submit(function(evt){
var form = $(this);
evt.preventDefault(); // Prevents default submission
$.post('/update_point_session/', {session: true}, function(data){
form.unbind('submit'); //Unbind js submit event
form.get(0).submit(); //submit the form
});
});
I have the following code:
<div id="parentDiv">
...
</div>
HTML inside the div comes from the external source and I don't know it's structure and can't control it.
I need to post some data when this link has been clicked. So I added an onclick event handler on the div element, hoping event will propagate, and posted data with jQuery ajax function.
This worked fine in all browsers but Safari - it doesn't return any errors, calls the callback function but doesn't reach the server for some reason. I write to database every time I get a request. Tried to manually load the post url in browser - works fine and record in db is created. Also tried FF and Chrome - works as expected.
When put an alert into callback function it's being called but in Safari data = null.
$('#parentDiv').delegate( 'a', 'click', function()
{
$.post('posturl',
{ param1: 'test'},
function(data)
{
alert('data = '+data);
},
"json"
);
});
Is it correct to expect AJAX working in this situation at all? And is there a better solution to this problem?
Thank you!
This sounds like you need to combine delegate with the asynchronous AJAX. Note that this is almost never a good thing -- the only real exception is when you want to do an AJAX request immediately before leaving a page.
Your code might look something like this:
$('#parentDiv').delegate( 'a', 'click', function()
$.ajax({
type: 'POST',
url: 'posturl',
{ param1: 'test'},
dataType: 'json',
async: false
});
});
This waits for the POST request to finish before continuing to follow the link. Note that this is superior to using location = url in a success callback as this solution allows normal browser action like middle-clicking to be followed as normal.
You want to look at jQuery's .delegate() method. It tells an element to listen for certain event bubbling up from a certain element and to execute behavior when it is observed. You also want to prevent the default action of the link, and send the browser to the link when the ajax operation is complete.
Docs: http://api.jquery.com/delegate/
Sample code:
$( '#parentDiv' ).delegate( 'a', 'click', function( e )
{
var url = this.href;
e.preventDefault();
$.post(
'posturl',
{
param1: 'test'
},
function(data)
{
alert('data = ' + data);
window.location = url;
},
'json'
);
} );
This:
delegates the event
prevents default
awaits ajax response
sends browser to link
Demo: http://jaaulde.com/test_bed/dasha_salo/