I have created a chat room which uses ajax request to check for new message every second by using setTimeOut function, I achieved this but my only question is that, is it okey to request data from server after every second? or it may cause some problems? below is my code:
function refresh(){
setTimeout(function(){
$.ajax({
type: 'POST',
url: 'checkNewMessage.php',
data: { sender:$sender, recipient:$recipient},
success: function(response) {
$('#newComm').val(response);
if($('#newComm').val()>$('#oldComm').val()){
$.ajax({
type: 'POST',
url: 'appendNewMessage.php',
data: { sender:$sender, recipient:$recipient},
success: function(response) {
$("#chatRoom").prepend(response).fadeIn(4000);
$('#oldComm').val($('#newComm').val());
}
});
}else{}
}
});
refresh();
},1000);
}
Well, this is a question with a depends on answer.
Polling the server with timed requests is not the best way of achieving what you would like to achieve. At this place I recommend using WebSockets: https://developer.mozilla.org/en-US/docs/Glossary/WebSockets
But back to your question. It depends on your server and the load it is going to take. Lets say you have ten active users. So your server would take about 10 requests per second - not too much.
You could run a benchmark and see how many requests per second your server can handle. But handling requests is not the same like answering each request.
If you don't have so many users on your chat, you might be ok with this approach. For bigger loads I highly recommend to switch to WebSockets.
Related
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).
I am loading a large (~300 MB) JSON file by using the following code:
$.ajax({
type: 'GET',
url: path,
dataType: 'json',
data: {},
async: false,
success: function(json_object) {
console.log("success!");
} error: function(request, error) {
console.log(request["statusText"]);
}
});
Running it outputs "InternalError: allocation size overflow". Is there any way to get around this that does not involve making the file smaller?
You'll need to set up a buffer. However, why on earth are you passing so much data? That would be an extremely unreasonable wait for any user.
EDIT
Buffering isn't really something you can do from the ajax side (according to How to buffering an Ajax Request?). However, you can set something up server side (if it's your server returning the data) to send it in pieces, then use ajax to request each piece.
If it's not your server, or your requesting from an API or something, then look and see if they accept any parameters to define the size of the return object - this way you can request it in chunks.
I m trying to convert the following code to another AJAX call, in order to not have cross-domain problems!
This is my original code:
<script>
$(document).ready(function() {
$("#os").load('http://www.a.gr/os #livesos');
var refreshId = setInterval(function() {
$("#os").load('http://www.a.gr/os #livesos');
}, 60000);
$.ajaxSetup({ cache: false });
});
</script>
And here is a sample code for what i want to do, but i dont know how...
$.ajax({
type: "GET",
cache: false,
url: 'http://www.a.gr/os',
dataType: "???",
.
.
.
.
});
Can someone help me please?
Your best bet to avoid cross-domain issues is to have the phone call your server, and the server can call the other servers to get the data needed.
There are a couple of benefits to this, one being that you can cache recent calls, if it doesn't change often, and more quickly send it back to the client.
Also, if you want to later change the url or make additional calls to return richer data, you can do that without affecting the client.
I have to query (via Ajax) 2 scripts at the same time.
I know for sure that one is really quick, it just displays some html, the second is doing some query using a WebService.
The quick request, is always sent after the first one. But with all my attempts, the fast/quick one, never completes before the slow one.
The code use to call the first long ajax request:
$.ajax({
type: "POST",
url: '/fr/ajax_flight_get_other_oneway',
cache: false,
dataType: 'json',
success: function(data) {
// some treatment
}
The code for the second faster ajax request:
$.ajax({
type: "POST",
url: '/fr/load_back_forflight?id=SN4422_23',
cache: false,
data: "comps="+compSelectedCodes+"&escale="+escale,
dataType: 'json',
success: function(data) {
// some treatment
}
Is it something in Apache that should be changed or is it in jQuery?
I found the solution to my problem, it was linked to the session.
the session was based on file system. So the first (long query) is lock the session file, and then the second one is forced to wait for the long query to finish.
by using session in DB, I've resolved the problem.
thanks for your help
Put the slow one in the success callback of the fast one. This will guarantee that the fast request will finish first before starting the second request.
It's possible that the browser decided to use the same HTTP connection for both (using the HTTP header Keep-alive) and thus it appears queued. This is not a jQuery thing -- it's something that browsers can opt to do.
Use your browser's HTTP network traffic debugger to see if that's the case.
If not, then your web-server may be only allowing one connection per client and is queueing them. See this:
How do I configure Apache2 to allow multiple simultaneous connections from same IP address?
Try this:
$.ajax({
type: "POST",
url: '/fr/ajax_flight_get_other_oneway',
cache: false,
dataType: 'json',
success: function(data) {
// some treatment
//The code for the second faster ajax request:
$.ajax({
type: "POST",
url: '/fr/load_back_forflight?id=SN4422_23',
cache: false,
data: "comps=" + compSelectedCodes + "&escale=" + escale,
dataType: 'json',
success: function(data) {
// some treatment
}
});
}
});
I have two Ajax requests that I am wanting to combine together into one. I'm having trouble figuring how to do this as one is using $.ajax() and another is using $.get().
As I'm fairly new to Ajax, this is causing me much pain. If you could help, it would me much appreciated.
Ajax Request #1
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: "page="+page,
success: function(msg)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
}
});
Ajax Request #2
$.get("new_arrivals_data.php",{imgs: value}, function(data){
$("#gallery_container").html(data);
});
Thanks for any help you can offer.
They are actually both GETs $.get is short hand for $.ajax({ type:'GET'.
So combining them might work depending on your server's response:
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: {page:page, imgs: value},
success: function(msg)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
}
});
Not sure what you're looking for, but Ajax Request #2 is equivalent to:
$.ajax({
type: 'GET',
url: "get_images.php",
data: {imgs: value},
success: function(data){
$("#imgTray").html(data);
}
});
Hope this helps.
You can't just 'combine' requests - you'll still need to make two separate requests to each of these URLs. Since by default, ajax requests are asynchronous, you can fire them both almost simultaneously (if one doesn't depend on the other. As marko points out in the comments, if they are dependent, you could force the requests to be synchronous. $.ajax has an async property.).
if(condition){
makeRequest1();
makeRequest2();
}
Also $.get() is simply a convenience method for $.ajax() with certain options preset (such as using GET as the request type).