Jquery asynchrone requests - javascript

I have implemented comet client in jquery as following:
$(document).ready(function () {
comet();
});
function comet(){
var cometJSON = {
'comet': 'id'
}
$.ajax({
type: "POST",
url: "http://localhost:8080/comet",
data: JSON.stringify(cometJSON),
async: true, /* Set async request*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
console.log('suc');
eventReceived(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error: "+textStatus);
},
complete: function(jqXHR, textStatus){
console.log("Send new comet!");
comet();
}
});
};
Everything works fine, but I have always noisy spinner in my browser tab and my status pannel always shows: Waiting for localhost, how can I fix that?

The spinner indicates a connection in progress, which is exactly what is happening - after you receive an answer, in complete section you instantly trigger a new request, hence there is a connection in progress most of the time (pretty much always). To avoid it, you need to do a delay before a new request - setTimeout(comet, 1000) sounds like a good alternative to the last comet();

I implemented the same thing a while back and ran into the same problem:
https://github.com/tenorviol/cometjax
To solve the problem of the forever spinner, put a timeout on your initial ajax call, e.g.:
$(document).ready(function () {
setTimeout(function() {
comet();
}, 10);
});

Related

MVC javascript ajax call results in xmlhttprequest warning

When running the following code I get the desired results updating my view on success, but I also get a warning in the console and certain items on the page don't work any more. I though putting the async option in would have sorted it but obviously not.
Can anyone suggest how I should change this?
xmlhttprequest on the main thread is deprecated because of its
detrimental effects to the end user's experience
$("#addSelectedModules").on("click", function () {
event.preventDefault();
$('#createLearningPathForm').validate();
if ($('#createLearningPathForm').valid()) {
var request = $.ajax({
async: true,
type: "POST",
url: "/umbraco/Surface/CreateLearningPath/SetSelectedList",
data: $('#createLearningPathForm').serialize(),
success: function (data) {
$("#top").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
);

Using clearTimeout(x) in ajax call

I am writing codes where the code will do some polling for statistics to the server using AJAX. My web application is getting data from the server every 3 seconds once the server returned the data. It is working good but however, I want to apply clearTimeout(x) function to stop the execution and print something to user when any error occur like "timeout" or "error" triggered by error setting. I managed to search the similar case with me here and this also link. But for some reason my code does not do what I want. Here is what I have so far
var timeoutid = 0;
var myfunc = function() {
$.ajax({
type: "POST",
url: "pull.php",
error: function(xhr, status, error){
if( status==="timeout" || status==="error") {
alert("Timeout or unable to receive statistics!");
clearTimeout(timeoutid);
}
},
success: function(msg){
$('#res').val(msg);
//timeoutid = setTimeout(poll, 3000);
},
complete: function(){
timeoutid = setTimeout(myfunc, 3000);
},
timeout: 5000
});
}
myfunc();
The result of the above when I disable my Internet adapter is it keeps looping and alert me the error without stopping the execution. I don't really know how or where do I put my clearTimeout due to localized variable issue based on what I have read. Not really a master in jQuery in detailed though. Appreciate your kind respond and thank you in advance.
It is because you are again creating a new timer in the complete callback which will get executed in the case of error also
var myfunc = function () {
$.ajax({
type: "POST",
url: "pull.php",
error: function (xhr, status, error) {
if (status === "timeout" || status === "error") {
alert("Timeout or unable to receive statistics!");
}
},
success: function (msg) {
$('#res').val(msg);
},
complete: function (jqXHR, status) {
if (status !== "timeout" && status !== "error") {
setTimeout(myfunc, 3000);
}
},
timeout: 5000
});
}
myfunc();

AJAX request not working on remote host

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

javascript frameworks prototype to jquery

I have found the following script which is apparently written using the javascript framework prototype.
Event.observe(window, 'load', function() {
Event.observe( 'btnSubmit', 'click', purchaseCD);
connectToServer();
});
function connectToServer()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
onSuccess: function(transport)
{
if (parseInt(transport.responseText)) connectToServer();
}
});
}
function purchaseCD()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
parameters: { num: $('txtQty').getValue() }
});
}
Is anyone here able to convert this script to use jQuery instead of prototype? I don't know prorotype at all so I don't understand it.
Ajax.Updater takes, as parameter 1, two containers into which it will update the successful or failed response of a request to the URL given in parameter 2.
What this script does is that upon page load (I translated it below to DOMReady which is not exactly the same, but jQuery convention) an AJAX request is sent to server_side.php. If it gets a response that it understands, it immediately sends off another request, in order to keep the session alive.
This looks like a terrible design. If you're going to do something like that, you definitely want a timeout between the requests.
Another thing that's not very neat with this script is that every AJAX request is handled by the same page - server_side.php - relying on different parameters for instructions on what action to perform. It would appear cleaner to simply request different pages for different actions.
$(function() {
$('#btnSubmit').click(purchaseCD);
connectToServer();
});
function connectToServer() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
if(parseInt(res))
connectToServer();
},
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}
function purchaseCD() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
},
data: { num: $('#txtQty').val() },
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}

Categories

Resources