I am making ajax request to a particular server and getting the response also. I am doing cross domain request so using jsonp. Is there a way to get the server time to which i am making the request. Will it be better to write php script or doing just ajax request is good. Suppose if i make the following request :
$.ajax({
dataType: 'jsonp',
data: 'jsonp=date',
jsonp: 'jsonp_callback',
url: 'http://www.google.com',
success: function (data) {
}
});
How can i get the server time from this request? Please help if any suggestion. Also after getting the time if i use setInterval method to update time every second will it be a costly operation or better to make the same ajax request after a particular time to update time. I have real time data to update with the time.
You can't get the server's time if it doesn't explicitly provide it to you.
You can read its HTTP headers, but that's not a good thing since the headers may not provide this information every time, or their format may not be the same all the time.
Also, I don't see the point of asking it every second.
Ask it one single time, calculate the difference between its time and yours, and here you go: you got the difference of time and you can use it wherever you want.
Keep in mind that even if you get the time, there probably will be a difference between the one you got and the server's real time because of the network's latency.
The answer to part 1 is that you will need to output the server time in the response in order for your javascript to read it. For part 2, I would wait for the response to load, and then use setTimeout. Using setInterval means that you might fire the ajax call twice before the first response returns.
When you suggest server time do you mean the script that is executing the call or the actual time on the server?
What is the need for this, are you trying to figure out time between calls to automate calls every 5 secs for example?
If you are then just simply getting a locale time from javascript and comparing that from when you get a response in ajax would suffice?
Otherwise javascript isn't going to be able to get server time, due to its 'clientside' nature.
Related
I have a chat on my website, and it runs on AJAX calls. Knowing that the PHP script is being ran 2-3 times per second, is it a bad idea to connect to a database and pull / insert data? I am wondering if it will slow down my PHP significantly, or not change it much at all.
Sorry I can't comment yet, so i don't know if that's your answer..
So basically of course this will cause all lot of traffic on your database. Depending on Webserver this might not be that big of a deal. But if a Clients physic computer is just from 2000, his side will just lag out the tab because his browser is sending all the time requests to your database and is trying to get the answer.
But i think this is the easiest method to get live data, which you need for your chat. But in my opinion I would suggest you to run the AJAX-Request like every 2 Seconds. I don't know what's exactly your purpose. But for a normal chat (not real time data exchange) this will last.
By the way: I am also not sure how you are initializing your AJAX-Request. But i would suggest doing this with jQuery:
$(document).ready(function(){
call_php_ajax()
});
function call_php_ajax(){
$("#div_toinsert").load("ajax.php");
setTimeout(call_php_ajax, 3000) // 3 Seconds
And in your MySQL-Query-File (ajax.php) you perform your queries
As I'm currently in the process of making a forum system which is loading new posts/edits without having to refresh the page. Now, for the older browers which don't have an implentation of EventSource/WebSocket, I'd like to offer another option:
Every X seconds I'm GET'ing a PHP site which is echoing the five latest news. Afterwards, I'm simply checking which of those news weren't seen by the client yet and applying the changes to the page.
Now, my problem is: How would you determinate the X interval in which the client is retrieving new updates? I'd like to base it up the user's connections so that it isn't killing off his connection completely.
What would be your attempt at accomplishing this?
I would use long polling technique through AJAX in your case:
1) The client sends the AJAX HTTP-request to the server.
2) If there is an available data, server sends HTTP-request to client, otherwise instead of sending an empty response immediately, server holds the request and waits for information to become available (or for a suitable timeout event - for example, in every 25 seconds), after which a complete response is finally sent to the client.
3) After recieving the HTTP-respose, client immediately sends other HTTP-request to server.
I would do the following (code not tested, but you should get the idea). Use jQuery for simpler code.
function refreshNews() {
$.ajax({
url: "ajax-url"
}).done(function(data){
/** add code here */
setTimeout(function(){ refreshNews(); }, 30000); // 30 secs should be enough to read some headlines
});
}
refreshNews();
This way the refreshNews() function is only called after the data is received and shown to the user.
Just an idea: make a HTTP request and see how much it will take long and use it as the base! I'd repeat it, let say each 10 minutes to show how much I'm thinking about my clients!
I think it will be more resource-friendly on the server-side comparing to the long polling, especially for scripts like forums where people won't left the page for less than 10 hours. :)
Well I dont know which is the most efficient way to do. Could someone help me in finding out a better algorithm.
okay let us take some example like facebook when user posts a post, it will be updated to his friend without any page refresh and we know its by ajax request . But how can we know that some one has posted a new thing? may be like putting a timer for every 2 seconds and sending an ajax request for some table and checking if some user posted something.right? but is there a way to do without setting a timer because performing the operation for every 2 seconds may cause severe server issue i think so ? just wanna know if there is a better way instead of setting a timer?
Any help is greatly appreciated.
Currently what Facebook and Google employ, is a technique called long polling.
It's a simple system whereby the client makes an AJAX request to the server. The server takes the request and checks to see if it has the data the request needs. If not, the request is left open but deferred by the server. The second the server has the data, the request is handled and returned to the client.
If you open up facebook, you'll see requests being posted to Facebook which take around 55 seconds to complete. Same goes for Gmail and a few other web applications that seem to have some kind of push system.
Here's a simple example of how these requests might be handled:
Client:
Initial AJAX request which has the timestamp 0
Server:
Compare request with timestamp 0 by checking the timestamp of the data on the server. Lets say the data on the server has the timestamp 234.
The client stamp is different from the current stamp on the server data so we return with the new data.
Client:
Client gets the data and immediately posts a new AJAX request with timestamp 234.
Then we process the new data and update the web page appropriately.
Server:
Compares request with timestamp 234 with the current stamp of the data on the server.
The stamp values are the same so we go to sleep.
Server data is update and stamp value is now timestamp 235.
Sleeping requests are woken up and returned with update value.
You can read a more in-depth explanation of more modern mechanisms for live updates.
Just my two cents but I have previously solved a similar problem by having 2 webservices. Basically one with a method along the lines of HaveNewData() and another GetData() (In my case I had a number of webservices I wanted to call).
So basically call HaveNewData() on a regular basis (I think in any case every 2 seconds is a bad design and unnecessary) and return a simple 0 or 1 for this method (minimal data). If HaveNewData() returns 1 then make your expensive webservice call. Alternatively you could also just return a null value in the primary webservice when no new data is available and in my experience this scales at least "pretty" reasonably.
Long polling is a great technique but as with any solution the efficacy depends on many variables including hardware setup and hence there are no absolute solutions.
Please be aware that Long polling you are keeping the connection alive which may cause performance issues with many clients.
You solution should take into account :-
Does it need to be almost realtime (for example a stockticker)
How often the ajax data/output changes (chat vs new comment)
How often does the event that causes changes to ajax data/output triggers. This will dictate how the cache is generated.
You should be a frugal when it comes to ajax. Request & response should be done on a need basis. The success of a ajax implementation will be incomplete without a well thought out caching solution which is more event based rather than request based.
Below is a simplified version of one of the techniques we found useful in a project:-
Every Ajax poll request that is made will contain output_hash which is the digest of the data returned by the server previously.
Server checks this output_hash against the recent hash of the output it will have generated, from data source preferably stored in cache.
If it is different then it will serve the new content along with new output_hash. Else a small response / Not modified to indicate there is no new content.
In our solution we also did dynamic calculation of the interval of the next poll. Keeping the interval dynamic allows the server to control the request. For example let's assume most comments / answers happen in the first 1 hour, beyond that there is no point having the interval time as 1 sec, so the server can increase that to 2,3 or even 5 sec dynamically as the time increases, rather than hard coding the interval as 2 sec. Similarly the interval time can be decreased if there is flurry of activity in an old post.
We also checked for idle clients and other things.
At the moment I’ve got one function to check, if a webpage is reachable. I’ll call this function at about 100 times in a while-loop, which means it sometime lasts 5 minutes to check all these 100 webpages.
I never before used ajax but I would think that it would be a good idea to solve this problem with ajax, but I never used ajax before and have no idea, how to start. Could you give me a good hint? Thanks for every answer!
I would use jquery-ajax, makes it simpler.
So put jquery on your site to start.
This is how jquery ajax works:
$.ajax({
type: 'POST',
url: '--LINK TO PHP/ASP...---', // Place the link that has the command
data: dataString, // dataString is a json encode of the data that is sent to the file
dataType : 'json',
beforeSend:function(){
// Before you send the info, do what you want here (ie loading gif...)
},
success:function(data){
// If it is successful, then it will do what you want here.
}
});
I hope this helps.
I would suggest you use JQuery Ajax, easier to implement.
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
From your (somewhat ill-defined) description, I'd say that using AJAX to control the web site verification would be a deeply in-appropriate approach.
Instead, a more sensible approach would be to "batch process" the web site data via the use of a cron triggered PHP cli script.
As such, once you'd inserted the relevant domains into a database table with a "processed" flag set as false, the background script would then:
Scan the database for web pages that aren't marked as checked within your required time period.
Carry out the CURL lookup, etc.
Update the database record accordingly with the current timestamp.
...
To ensure no overlap with an existing executing batch processing script, you should only invoke the php script every five minutes from cron and (within the PHP script itself) check how long the script has been running at the start of the "scan" stage and exit if its been running for four minutes or longer. (You might want to adjust these figures, but hopefully you can see where I'm going with this.)
By using this approach, you'll be able to leave the background script running indefinitely (as it's invoked via cron, it'll automatically start after reboots, etc.) and simply add web pages to the database/review the results of processing, etc. via a separate web front end.
You could of course use AJAX to get a regular summary of the current status from the database for the purposes of client-side display.
I am wondering if anyone could show, or explain with examples, how facebook checks its database for new messages? It seems to do it periodically, without loading the page. What would be the best way to achieve this in a PHP/MySQL/Jquery script?
Any help is always appreciated!
Cheers, Lea
you can do this: usign periodical updater
<span id="inbox-title"></span>
<script>
$.PeriodicalUpdater('/path/to/service', {
method: 'get', // method; get or post
minTimeout: 1000, // starting value for the timeout in milliseconds
maxTimeout: 8000, // maximum length of time between requests
}, function(data) {
$('#inbox-title').html('you have ' + data + 'new messages');
});
</script>
another option is to bind the onmousemove event and make the ajax call when than happes
There is actually a "page load", but it's a hidden request that doesn't reload the displayed page. Take a look at the jQuery Ajax command documentation for more details on one of the simplest ways to accomplish this (especially since you already mentioned using jQuery).
Have a look into reverse ajax with the COMET technique, this is a perfect use for it.
The idea behind it is to start an ajax request and let it timeout which could be 60 seconds, when it times out, start it again, here the browser has a (nearly) persistent connection to the server, if (for a simple example) a message gets created for a user. the server can reply to one of the hanging ajax requests that have been made (in this case by the recipient of the message).
No data is transfered while the xmlhttprequest and the server are waiting, but closing and reopening connections might be a burden on your server.