I have a web app.
It is written in asp.net, javascript and jquery.
I have a timer on the page. It will 'ping' my server every 100ms (I know this is not guarantted due to the nature of timers in javascript).
So, this is my code:
function GetImageStatus() {
var val = url + '/Mobile/isNewFrame.ashx?Alias=' + Alias + '&CamIndex=' + camIndex + '&Version=' + version + '&GuidLogOn=' + guidLogOn;
jQuery.get(val)
.success(function (data) {
//invalid session
if (data == '-2') {
document.location.reload(true);
}
else {
//do something useful
}
})
.error(function (jqXHR, textStatus, errorThrown) {
var ct = XMLHttpRequest.errorThrown;
$("#divVersion").html(ct);
});
}
function Start()
{
if (timer4x4) window.clearTimeout(timer4x4);
timer4x4 = window.setTimeout(GetImageStatus, tmrInterval);
}
var timer4x4;
var tmrInterval = 100;
So, my question is this. If the ping/get call takes longer than my tmrInterval is the call aborted before the next call is initiated?
No. I suggest using jQuery ajax with timeout option such as :
$.ajax({
url: val,
type: 'GET',
timeout: tmrInterval,
success: function (data) {
//invalid session
if (data == '-2') {
document.location.reload(true);
}
else {
//do something useful
}
},
error: function (jqXHR, textStatus, errorThrown) {
var ct = XMLHttpRequest.errorThrown;
$("#divVersion").html(ct);
}
});
Related
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I am trying hard to fix this issue but still didn't get the solution, tried many links and code, but facing a bit problem to fix this.
ISSUE:
I have an input type 'Text' to search the employees name.
When I Start entering characters like 'WY', it shows all the names starting with WY.
Once I get the employee I need, I can move that to other control and Run PDF report (which loads in another Tab).
The issue is when I go back to the page where I should start searching the employees again, it won't search! as shown below:
Here is my ajax code :
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
UI Control :
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
Please let me know, what I should be doing to get it fixed.
This might be the reason for the issue
The $("#EmployeeSearchBox").bind('input propertychange', function () { ..}); might not be available in the DOM.
To ensure whether the EmployeeSearchBox and propertyChange handler are still alive, place an alert inside the propertychange function. If the alert is shown then the issue is some where else.
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
alert("Inside Property Change "); // Add this alert
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
what do you mean by bind it again
This is the function which is binding the EmployeeSearchBox with the DOM $("#EmployeeSearchBox").bind('input propertychange', function () {.... and when you are moving to the PDF tab and coming back again to SearchBox tab the binding of this element is lost, it means the DOM doesnot know what to be done when the property change is fired on the EmployeeSearchBox. Two ways to solve it
1) Ensure that the Event handler is always present in the DOM even when you navigate between tabs.
2) If option 1 is not achievable in your scenario, kindly rebind the event handlers whenever you are coming to the search tab. Explicitly invoke this $("#EmployeeSearchBox").bind when you are in the search tab.
Please check that the ajax call has raised for your second search.. if not there must be a problem in condition checking area or function calling method. I always use this function for searching data
$("input").change(function(){
ajax call.....
})
Am upvoting the suggestion provided from "Clement Amarnath", which helped me to resolve this issue.
I found the fix for this , instead of using .Bind(), I used .on() inside (document), am posting the answer which I have fixed it.
Thanks all!
$(document).on("input propertychange", "#EmployeeSearchBox", function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
//error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
//}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
NOTE :
below line too works :
.live() method
$("#EmployeeSearchBox").live('input propertychange', function () {... });
In my page, I call 15 ajax request. Also I have a button which cancels all the pending ajax requests. As per documentation, abort() terminates the request if it has already been sent.
Now when I check my console, even after I click cancel button, I get some replies from ajax script (I guess those were already sent by the time I clicked that button). So how can I make sure no reply should come once I press cancel button?
You can check the script here (couldn't use jsfiddle as not sure how to make ajax request).
JS Code
var xhrPool = [];
$(window).load(function(){
callAjax1();
});
$.ajaxSetup({
beforeSend: function(jqXHR) {
xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = xhrPool.indexOf(jqXHR);
if (index > -1) {
xhrPool.splice(index, 1);
}
}
});
var abortAjax = function () {
$.each(xhrPool, function(idx, jqXHR) {
if(jqXHR && jqXHR .readystate != 4){
jqXHR.abort();
}
});
console.log("All pending cancelled"); // Should not have any ajax return after this point
$.xhrPool = [];
};
$("#cancel-button").click(function (){
abortAjax();
});
function callAjax2(ajaxcallid){
console.log("Initiate ajax call " + ajaxcallid); // Should not have any ajax return after this point
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
console.log(msg + ajaxcallid); // msg = "Ajax return for "
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
function callAjax1(){
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
for(var i = 0; i < 15; i++){
callAjax2(i);
}
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
Console Output:
try this
$.each(xhrPool.slice(), function(idx, jqXHR) {
I think while you are aborting, some are returning, so the array gets messed up
this way you are working with a snapshot of the array
though, one or two may still sneak through due to timing of course
I have a website where I rely on a lot of custom API call. My API return always an XML.
Currently, at the start of each and every $.get or $.post I call, I have this snippet :
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
However, I feel this code to be much redundant on one of my page, it's used 15 times.
I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here
Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?
I assume that you have something like this in many places in your code
$.ajax({
method: "GET",
url: "someurl.html",
dataType: "xml",
success : function() {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
// ...
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
});
you could create a generic custom ajax function tha you can re-use
function baseAjaxCall(option, sCb) {
var ajaxOptions = {
method: option.method || "GET",
url: option.url,
dataType: option.dataType || "xml",
success : function(data) {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
else {
sCb(root);
}
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
};
//you can check for optional settings
if(option.contentType !== undefined){
ajaxOptions.contentType = option.contentType;
}
$.ajax(ajaxOptions);
}
everywhere in your code you can re-use the baseAjaxCall function
baseAjaxCall({ url: "someurl.html" }, function(root){
// no need to chek for errors here!
});
Hope it's helps!
In as much as I would like someone to say "change this line of code to read....", I really would like to know the solution to the problem of Firefox not reporting broken code. This code block is broken and it causes a previous block of code to break. It's somewhere in the notdupe.live.click function. I can comment out the entire function and the rest of the code works. I've tried commenting out pieces but can't isolate the problem.
<script type="text/javascript">
var SaveDupeGroup = 0;
var DupeCount = 0;
var ReInitAnswer = '';
var RemoveAnswer = '';
$(document).ready(function () {
$('.StartOver').live('click', function () {
ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit(); //return true;
} else {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error
alert(errorThrown);
},
success: function (response1, textStatus, jqXHR)(
if ($(e.target).is(":checked")) {
$firstTD = $(this).parent().siblings().first();
SaveDupeGroup = $firstTD.text();
$.ajax({
type: 'GET',
url: 'cfc/basic.cfc?method=CheckDupeGroup&returnformat=json',
dataType: 'json',
data: 'DupeGroupNumber=' + $firstTD.text(),
error: function (xhr, textStatus, errorThrown) {
// show error
alert(errorThrown);
},
success: function (response, textStatus, jqXHR) {
DupeCount = response.DATA[0];
alert('Dupe Group-' + SaveDupeGroup + ' count=' + response.DATA[0]);
if (DupeCount) {
alert('huh?');
} else {
RemoveAnswer = confirm('All of the names in this group have been checked.\nDo you want to remove them from the lists?');
if (RemoveAnswer) {
alert('continued');
} else {
alert('canceled');
return false;
}
}
}
});
})
});
});
});
</script>
Line 26, you have function()( should be function(){ and because of that you're probably going to have to investigate your closing }'s
have you tried checking the code with jshint or jslint?
You have a SyntaxError.
This...
success: function (response1, textStatus, jqXHR)(
should be this...
success: function (response1, textStatus, jqXHR) {
also the colosing ) should be }.
Not sure why Firefox (Firebug?) doesn't report it.