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
Related
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
});
I have a button click event that initiates an ajax call, and I need the ajax call to be synchronous so I set async:false. I want to provide feedback to the user so they know that the ajax call is happening in the back. So I have the following:
$('#ajaxBtn').on("click",function() {
$('#ajaxBtn').html("processing ...");
$.ajax({
type: "Get",
url: "example.php?data=test",
async: false,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
})
}
On Chrome (haven't tested on other browsers) When I click the button, everything freezes while the ajax call completes, however the text on the button doesn't update until the success alert pops up. If I step through the code in the debugger it works as I would expect. The text on the button changes before the ajax call initiates.
If I set Async: true it also seems to work as expected. The text changes immediately and then I get to the success function.
Is Chrome reordering the ajax call to happen before the changing of the text? Why am I seeing this?
What about something like this.
$('#ajaxBtn').on("click",function() {
$.ajax({
type: "Get",
url: "example.php?data=test",
//note that I have removed the async: "false",
beforeSend:function(){
$('#ajaxBtn').html("processing ...");
},
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
}).done(function(data){
//submit your form here depending on which data is returned
});
}
I'm using dynamic pagination.
I need to cancel the success event in jQuery ajax before starting another.
I've set a variable equal to $.ajax(), and before doing so, I call abort no matter what.
The problem is that success still fires.
The answer for Ajax: How to prevent jQuery from calling the success event after executing xmlHttpRequest.abort(); is wrong, or at least it doesn't work for me because if I fire abort right after the ajax nothing ever happens.
I just want the success of the ajax variable not to fire if another one is about to start.
Code Snippet:
if(updatePageAJAX){
updatePageAJAX.abort();
}
updatePageAJAX = $.ajax({
});
I can provide more detail if you like, but updatePageAJAX works. I couldn't tell you if abort works. I put an alert in the if to see if it fires; it does.
If I put abort right after setting updatePageAJAX = $.ajax, nothing ever happens.
Have you tried saving your xhr object in a variable so that you can check in the success callback if it is the right xhr object?
For example:
$(function() {
var xhr = null;
$('.link').click(function() {
var page = $(this).text();
if(xhr != null) {
xhr.abort();
}
xhr = $.ajax({
type: 'GET',
url: 'index.php',
data: 'js=true&page=' + page,
success: function(data, responseCode, jqxhr) {
if(xhr == jqxhr) {
$('#page').text(data);
xhr = null;
}
}
});
});
});
This way, the success callback won't execute if this is not the right request.
I have tried so many things, cannot figure this out, I am using this code, and I know that the start is working, because the script it connects to sticks some info in the db, but the callback never runs.
<script type="text/javascript">
$(document).ready(function() {
$(document.body).on('click', "#reply_submit", function() {
var formData = $('#reply').serialize();
$.post("newpost.php",formData, function(data){
alert("hi");
}, "json");
});
});
My form's id is "reply" and the button I am using to submit it is "reply-submit", just to make sure those things are clear.
It also doesn't work if I remove that last "json" thing btw.
If you read the docs for jQuery.post(), it says this about the callback:
success(data, textStatus, jqXHR)
A callback function that is executed if the request succeeds.
If it's not getting called, it means that request did not succeed. There is probably an error in newpost.php (sometime after the data insert, but before it would normally exit).
You can also catch error conditions by using the long-form jQuery.ajax() instead of the post shorthand:
$.ajax({
url: 'newpost.php',
data: formData,
type: 'post',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error!');
}
});
When you click, the form is also being submitted the standard way. Modify your click handler like this:
$(document).on('click', "#reply_submit", function(e) {
e.preventDefault(); // prevent the default submit event
var formData = $('#reply').serialize();
// ...
});
Although I think document.body should be a valid node to wrap in jQuery, I've also modified it to the more commonly used document.
On that note, if the form is never destroyed by an Ajax event or other DOM modification, you could bind to #reply instead of document (or body).
I'm simply assuming that you want to submit a form without reloading the whole page.
Based on that assumption, following code will serve the purpose.
$(document).ready(function(){
//on form submit event
$('form#reply').submit(function(){
$.post('newpost.php',$(this).serialize(),function(){
alert("Message or do something with the response data if you are expecting one");
});
//prevent default action
return false;
});
});
Please ignore the post if this is not the functionality you are looking for in your project.
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/