cancel ajax() success - javascript

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.

Related

AJAX delaying the execution of next lines

Given the following code, can anyone help me understand why the first alert is executed after the second one? I believe this happens because ajax has a small delay untill it fetches the data, correct me if i am wrong.Thanks in advance.
Javascript code:
window.onload = function() {
arry = new Array();
jQuery.ajax({
type: "GET",
url: "index.php?op=17&id=##postID##&action=fetch",
dataType: "text",
success: function(response){
var e = response;
console.log(JSON.parse(e));
arry = JSON.parse(e)
alert(e); //1st alert
}
});
alert("test") //2nd alert
}
The first "A" in AJAX stands for asynchronous. That means that it is not blocking in your code, so the alert('test') is called immediately after your AJAX request, whereas alert(e) is only called once the AJAX request has received a successful response from the server.
The 'small delay' that you mention is not such, but rather the time it takes for the server to execute whatever code and return a response.
If you absolutely need the request to be handled synchronously, you can pass the async property to the AJAX call as follows:
window.onload = function() {
var arry = [ ];
jQuery.ajax({
type: "GET",
url: "index.php?op=17&id=##postID##&action=fetch",
dataType: "json",
async: false
}).done(function(response) {
arry = response
alert(response); //1st alert
});
alert("test") //2nd alert
}
Notice that I have updated the code somewhat to use the done() promise. Also, specifying dataType: "json" negates the need to call JSON.parse() on the response text.
yous first array is inside the success event of the AJAX call which (the success function) gets registered, skipped and called back only when the response of the ajax call is ready..

Firing click event before ajax call

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

jquery doesn't work after an ajax call (response in a pop up window)

I've a jsp page with a form and some jquery code. Jquery code works perfectly, but if I return that page in a popup window by using an ajax call, the jquery code doesn't work any more.
I tried also to use delegation, that is:
$('select[name=myElementName]').on("change", function() {
// some code
});
or
$(document).on("change", 'select[name=myElementName]', function() {
// some code
});
instead of
$('select[name=myElementName]').change(function() {
// some code
});
Ajax call:
var preview = function () {
$.ajax({
type: "POST",
url: myAction.do,
data: "id=" + myid,
success: function (response) {
// some code
var x=window.open('', '_blank', 'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
x.document.open();
x.focus();
x.document.write(response);
return false;
},
error: function () {
return false;
},
});
};
EDIT
On Firefox 26.0 and Chrome 32.0.x, I resolved by using
x.document.close();
after
x.document.write(replace);
Instead, on IE, all the .js included scripts are ignored (for example the jquery-ui-1.9.1.js).
EDIT 2
I resolved with
<body onload="myload()">
and in my jsp I've myload() definition in which I call the scripts.
It is because you are creating new DOM structure but it doesn't have the event handlers attached. The easiest way is to run the event handler in the ajax callback:
$.ajax({
...
success: function (response) {
// some code
var x=window.open('', '_blank', 'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
x.document.open();
x.focus();
x.document.write(response);
// now, place the event handler here
$('select[name=myElementName]', x.document.body).change(function() {
// some code
});
}
});
Don't use document.write it completely overwrites whatever is on the page at the time of writing and leads to race conditions (e.g. the external scripts might have already been loaded, but they also might not, leading to unknown order of the write and script loads). Also, I believe documnt.write is putting serialized text into the document, not DOM objects so it may not trigger events.
Instead, you can open the new window and then manipulate the DOM objects there directly (assuming it's on the same server as your main page):
//Open a new window for the success info
var newWindow = window.open(newUrl);
//Now grab some element
var someItem = newWindow.document.getElementById( "someId");
//Manipulate dom either by "someItem.innerHTML" or "someItem.appendChild(...)"
If you are calling an AJAX server routine and putting the entire response w/o processing it on the client in to a new window, why not opening the window directly with the URL of that AJAX routine and skipping all stuff:
....
var x=window.open(myAction.do + "?id=" + myid,
'_blank',
'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
....
The only diff here is, that the request is a GET and not a POST request, but the data is just one id, which is acceptable, probably?
I had a similar problem in on of my projects. I solved it by writing a success method after the ajax call.
{
$.ajax({
type: "POST",
url: "/abc/",
data:{<data>},
async:false,
dataType:'json',
success: function(response)
{
success=1;
Id=response;
return;
}
});
if (success)
{
#your code here
var a='/xyz/?Id='+Id
window.open(a,'_blank');
window.location.href='/registration/'
}
return false;}
instead of using document.write, try fetching your success data(records arrived in success function) in a hidden DIV and clone it into your popup that should work

Ajax with Jquery - Callback not executing

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.

Executing JavaScript after Ajax-call

I want to execute javascript for creating calendar using "calendarDateInput.js". Is it possible to execute javascript after an ajax call page using ajax tabs ?
I am not using any of the ajax libraries, only direct ajax call.
Here I want to call the function in an ajax returned page like DateInput("smsDate",true, "YYYY-MM-DD");
Usually this is done by Callback functions. If you use libraries like jquery they usually provide hooks for callbacks.
check out jQuery.ajax() for doing the ajax call and then onsucess you can run additional javascript code...
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.post/
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
I hope this is what you were asking for... otherwise please add some additional information to your question...
if you would not like to work with libraries like jquery ....
you have to check for the request status of you ajax call....
req = new XMLHttpRequest();
and then you have to check the response for following values
// IF completed
if (req.readyState == 4) {
// Server HTTP Code
if (req.status == 200) {
but jquery did all the work for you...
yes.
for non jQuery:
var httpRequest = new XMLHttpRequest(); //your AJAX object
httpRequest.onreadystatechange = AJAXhandler; //your ajax handler function
function AJAXhandler() {
if (httpRequest.readyState === 4) { //if success
//process..
//"YOU CAN CALL OTHER FUNCTIONS HERE"
}
}
When using jQuery or normal javascript, callbacks are THE way things like this are handled. For example, using jQuery:
$.ajax({
type: 'POST',
url: 'PathTOMyUrl.html',
success: function(data)
{
// This Callback will be invoked on successful call
},
error: function(data)
{
// This callback will be invoked on an error
}
});
The callbacks can then contain code you find useful. In normal javascript, you would attach to the onreadystatechanged event on your AjaxRequest. You can find more information here.

Categories