Ajax call opening too many connections? - ajax

I've got a small problem concerning my webpage that I'm updating using ajax. When I stay on my page for a while (an hour or so) it will stop loading and I can't display any of my pages in the browser. I've only started having this problem since I added this (simplified) javascript to my page:
var interval;
interval = setInterval('UpdateComs()',5000);
function FuncGo() {
$.post('data.php', { profile: pid }, function(data) {
$('.holder').html(data);
});
}
Since my server isn't down and this can't be the problem, I was thinking that this might be caused by too many connections? Could the above be opening more than one connection?
And if it does should I somehow close them?
Sorry for all the questions but I'm not too familiar with how connections work.. Thanks for any help or ideas

I suspect a random error (connection gets behind due to network traffic, maybe a timeout) that stops the setInterval. Always pass an annonomus function (not a string) to setTimeout or setInterval and only call the next function after the completion of the prior one.
function UpdateComs() {
$.ajax({
type: "POST",
url: 'data.php'
data: {profile:pid},
async: true,
cache: false,
timeout: 10000,
success: function(data){
$('.holder').html(data);
setTimeout(function(){UpdateComs(); },5000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//do what you want with the error
setTimeout(function(){UpdateComs(); },5000);
}
});
}

Related

SSE stays on pending while AJAX is running

In my project, I have a long-running process which is called by AJAX. Duration can be 1 to 15 mins.
While AJAX is running, I want to give updates to users. It just should show simply how many rows left to add into the database.
I found out that there are a few different options to realize this. Polling, SSE or WebSockets. I never worked with WebSockets, and I couldn't find a good example.
I'm trying now with SSE which I quite understand, and it is working properly.. but when the AJAX start running the connection to the eventSource will be pending. So while AJAX is running, there are no updates received.
Code:
<script type="text/javascript">
var es;
function checkProgress(id){
es = new EventSource('checkProgress.php');
es.addEventListener('message', function(e) {
console.log(e.data);
}, false);
}
checkProgress(1);
$(function() {
$('.submit').on('click', function() {
var form = $('form')[0];
var form_data = new FormData(form);
$.ajax({
type: 'POST',
url: 'submit.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
console.log(response);
}
});
return false;
});
});
</script>
Screenshots:
Network log
Now actually I still didn't find any reference or example of how to implement SSE while there is an AJAX process running. All reference or examples give examples to let the getProgress file to do something.
I see you're using PHP. My best guess would be that you're also using the built-in PHP session management. The problem with this is that accessing the session is an exclusive operation. I would guess that your AJAX operation has opened and locked the session, preventing your SSE script from also opening the session. You might consider not opening the session or opening it read-only(Dead Link) (Archived).

issue with Ajax dispatcher in typo3

I'm trying to grab some data from the database on a page in typo3 using Ajax . So after a long time looking for the appropriate way to do it , I got convinced that The Ajax Dispatcher is the best tool to do the job . So I created the file following the instructions to be found here.
Now when I make an Ajax call on my page , the console displays a 500 (Internal Server Error).
joined is a snapshot of my console tab.
and this is the jquery function that gets run on an onchange event .
function getContent(id)
{
console.log("Start process ...");
$.ajax({
async: 'true',
url: 'index.php',
type: 'POST',
data: {
eID: "ajaxDispatcher",
request: {
pluginName: 'listapp',
controller: 'Pays',
action: 'getMyCos',
arguments: {
'id': id,
}
}
},
dataType: "json",
success: function(result) {
console.log(result);
},
error: function(error) {
console.log(error);
}
});
}
Could someone please help me , I just started developing with this CMS of shit :p
If you indeed followed the tutorial step by step, and you use TYPO3 V6.2, you would get errors cause of depricated function calls to t3lib_div (as the title of the blog item says, it is for version 4.x)
Always keep your error.log open, it's your best friend in times of coding stress
You can also use typenum for ajax calls
http://lbrmedia.net/codebase/Eintrag/extbase-60-ajax-bootstrap/
I can imagine that starting with TYPO3 can be frustrating, but calling it a 'CMS of shit' does not seems to be a smart strategic move if you need help from people who think differently about it.

Jquery AJAX for fetching JSON, affected by URL prefix (www vs. no www)?

I have come across a peculiar item in JQuery that I am hoping somebody can help me to understand.
I've spent much of the day trying to get JQUERY's AJAX 'success' function to be raised when returning JSON from the server.
I checked the JSON # JSONLint to ensure validity, checked encoding, tried different headers, but still PROBLEMS.
After a couple hours, I switched the url (by accident!)
from
http//www.testing.com/_r4444/myfile.php
to the exact same thing WITHOUT the www... and it suddenly worked.
I have no clue why this would be the case - any ideas?
the snippet follows
$(document).ready(function() {
$.ajax( {
type: "POST",
contentType: "application/json",
url: "http://testing.com/_r4444/getter.php",
beforeSend: function(x) {
if(x && x.overrideMimeType) x.overrideMimeType("application/json;charset=UTF-8");
},
data: "pass=TEST",
dataType: "json",
error: function (xhr, status) {
alert(status);
},
success: function (result) {
alert(result);
}
});
});
Are you using "www" on the page in the browser?
Try switching the call to not include the domain, like:
"/_r4444/getter.php" instead of the full domain.

Check status of a jQuery ajax request

It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.
So if I shut down the server the following error callback is not executed and the request fails silently.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
What's the best way to throw an error when the server can't be reached at all.
Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.
Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.
There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.
You can use a setTimeout, and clear it with clearTimeout in the complete handler.
var reqTimeout = setTimeout(function()
{
alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
},
complete: function() {
clearTimeout(reqTimeout);
}
});
jQuery.ajax already has a timeout preference and it should call your error handler should the request time out. Check out the fantastic documentation which says — I’d quote it here, emphasis mine:
timeoutNumber
Set a local timeout (in milliseconds) for the request…
and:
error (XMLHttpRequest, textStatus, errorThrown) Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.
error: function (jqXHR, textStatus, errorthrown) {
if (jqXHR.readyState == 0) {
//Network error, i.e. server stopped, timeout, connection refused, CORS, etc.
}
else if (jqXHR.readyState == 4) {
//HTTP error, i.e. 404 Not found, Internal Server 500, etc.
}
}
Use readyState of XMLHttpRequest to determine the status of the ajax request.
'readyState' holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
If I remember correctly, jQuery throws exceptions. Thus, you should be able to work with a try { ... } catch() { ... } and handle it there.
You can use Jquery's AjaxSetup to handle your error handling.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function () {
alert("success");
}, error: function () {
alert("error");
}
//AJAX SETUP "error"//
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ' ' + textStatus + ' ' + errorThrown); //however you want
}
});
in ie8,can use:
success: function(data, textStatus, XMLHttpRequest) {
if("success"==textStatus&&XMLHttpRequest){
alert("success");
}else{
alert("server down");
}
}
but it's can't work on chrome,firefox...
i tried

Ajax request data is cached

I have an ajax function that loads within a setInterval as follow :
setInterval(function(){updateChart()}, 5000);
var updateChart = function(){
$.ajax({
url: './script.php',
type: 'post',
dataType: 'json',
cache: false,
data: {'candlesData':candlesData},
success: function(data) {
//alert(data);
//console.log("two");
//console.log(data);
gotData(data);
delete data;
delete candlesData;
},
error: function(xhr, desc, err) {
//console.log(xhr);
//console.log("Details: " + desc + "\nError:" + err);
}
}).done(function() {
});;// end ajax call
}
My browser memory gets SIGNIFICANTLY bigger over time. I tried to diagnose and found out that the POST request in the AJAX data (candlesData) is cached everytime... You can see this in the screenshot (retained data column).
I tried everything to clear the cache but it is not working.
Snapshot of retained data
I fixed this problem.
And I confirm that ajax post doesn't store cache...
The problem was that I had a javascript object which was recreated every time with setInterval function. I used :
objectName.destroy()
that get triggered everytime it reload the function and it resolved the problem.

Resources