Can I speed this $.post callback somehow? - javascript

I'm using a $.post callback in the following to redirect the page after the data has been posted. Sometimes the page redirects pretty fast, but other times it can take a good 3-5 seconds.
I'm a novice, so not sure why it's taking so long. Is it waiting for the php to end? Anything here I can change to speed this up?
On another note... encodeURIComponent doesn't seem to be working. The URL always has a space in it like ?fbname=John Doe" which I am trying to remove withencodeURIComponent`
Thanks!
FB.api('/me', function(response) {
$.post("addtodb.php",
{fbname:response.name},
function(data) {
window.location.href = "step2.php?fbname="+encodeURIComponent(response.name); //redirect after post callback
})
});

If you use're using a tool like Firebug or Google Chromes inbuilt tools you can view network activity. This will give you an idea of where the holdup is. The wait time could be due to the responsiveness of the server, or even something within your JavaScript.
Example:
I can see that on my personal website Facebook's like.php had a fairly slow transfer time..
http://i.imgur.com/pApRt.png

Related

Ajax read HTML after fully processed

I am trying to load the HTML content of a webpage outside of my domain, which I can do just fine using functionality provided by this jQuery plugin: http://www.ajax-cross-origin.com/. However, when I print out the HTML there are pieces missing, which I assume is because the ajax request gets the HTML before the page is fully loaded. When I say "pieces missing," I mean that some tags that should have innerHTML in fact have none. Here's my code:
$.ajax({
crossOrigin: true,
url: "http://siriusxm.com/bpm",
success: function(data) {
console.log(data);
},
timeout: 5000
});
The crossOrigin attribute is from the plugin I mentioned. I get the same behavior with and without the timeout (and strangely, it doesn't seem as though the timeout is doing anything at all--when I check the console, it logs data pretty much immediately).
Is there a way to wait until the page is fully loaded before getting the content? For what it's worth, this is all part of a chrome extension I'm developing, so if there's anything else code-wise you might need just ask.
Thanks!
So according to your comments, the information you're looking for is just the Now Playing artist and Song, which you won't be able to get by loading just the source of the main page.
To find the data you're looking for just open up your Chrome DevTools, go to the network tab, and Refresh to see all requests on the page.
It looks like this is the request you want, you just need to update the timestamp every minute:
http://www.siriusxm.com/metadata/pdt/en-us/json/channels/thebeat/timestamp/08-12-03:48:00
Just parse that json and grab what you need. Of course they can always change the location or format of the file, but for right now that's what it is.
If the console log is showing all of the data you're looking for then the ajax call should be fine.
Any code in the success callback will be ran after the ajax call, so just use JQuery in the success callback function to insert data into the html. All I see there now is the console.log(data) unless you've removed some code.
The timeout just gives the ajax call a set amount of time to complete before it "times out", in other words it tells it to stop waiting after the set amount of time.

On click, redirecting to another URL if server slow?

Is it possible (in Javascript, ajax, other e.g. on the client site) to redirect the user to another URL if first URL slow to answer (when he clicks on a link) ?
A href=URL1 but if no answer from server1 after 1 second, redirection to URL2 (another server)
I was thinking about something like on event onclick :
redirection to URL1, timer, redirection to URL2 but if server 1 is not responding, the code after won't be executed...
Or then using AJAX, but I don't see how
The case ; a click on a page (a href=urltracking), urltracking redirect to URL2, but urltracking server can be slow...
I'm afraid it's not possible in this way. You can measure the response time by "timeout check" with a dummy AJAX call, if the target URL lays in your domain. Something like "send test GET, if server doesn't respond in XX secs then rewrite URLs to backup sites". But it's not suitable for general use.
Are both these sites your own? Maybe you should buy a load balancer. This is essentially a server that monitors performance of two webservers and redirects requests to the one that is least busy.
I always try to avoid situations where a 3rd party site can slow down my own site.
Perhaps you can make the call in some asynchronous form instead? Have a piece of javascript fire within the DOM ready event that makes the call to the tracking server instead, something like (in jQuery):
$(function(){
var tracker = new Image();
tracker.src = "http://tracker.com/path/to/tracker
});
other methods that can work are just a plain old tag, or an , etc. The key being that this loads after your page, and not before it. The tracking server will never know the difference.
Pay more money for a better server(s) and in extreme case with a load balancer. You should never need to do something like this client side.
You can use setTimeout Function of javascript.
setTimeout("function()",1000);
here in function you need to write code for redirection.
Also see this question for complete reference.
Correct me if I am wrong.

Alternatives to using meta-refesh for updating a page

In the past, when I've covered events, I've used a meta-refresh with a 5 minute timer to refresh the page so people have the latest updates.
Realizing that this may not be the perfect way to do it (doesn't always work in IE, interrupts a person's flow, restarts things for people with screen readers, etc.) I'm wondering if there's any other way to do handle this situation.
Is it possible to have something like ajax check every few minutes if the html file on the server is newer and have it print a message saying "Update info available, click here to refresh"?
If that's crazy, how about a javascript that just counts down from 5 minutes and just suggests a refresh.
If anyone could point me to tutorials or code snippets I'd appreciate. I just play a programmer on TV. :-)
Actually, your thought on a timed Ajax test is an excellent idea. I'm not sure that is exactly what StackOverflow uses, but it checks periodically to see if other answers have been posted and shows the user, on an interval, if there are updates.
I think this is ideal for these reasons:
It's unobtrusive - the reader can easily ignore the update if they don't care
It won't waste bandwith - no reloading unless the user chooses to
It's informative - the user knows there's an update and can choose to act on it.
My take on how - have the ajax script send off the latest post id to a script that checks for new scripts. This script can query your database to see if there are any new posts, and how many there are. It can return this number. If there are new posts, show some (non modal) message including the number of updates, and let the user decide what to do about it.
setInterval(function() {
if (confirm("Its Been 5 Minutes. Would you like to refresh")) {
window.location.reload(true);
//Or instead of refreshing the page you could make an ajax call and determing if a newer page exists. IF one does then reload.
}
}, 300000);
You can use the setInterval function in javascript.
here's a sample
setInterval("refresh function", milliseconds, lang);
You will use it passing a name to a function that actually refresh the page for the first param and the number of milliseconds between refresh for the second param (300000 for 5 minutes). The third parameter lang is optional
If the user would be interacting with the scores and clicking on things it would be a little rude to just refresh the page on them. I think doing something like a notification that the page has been updated would be ideal.
I would use jQuery and do an ajax call to the file on the server or something that will return the updated data. If it's newer than throw up a Growl message
Gritter - jQuery Growl System
Demo of what a Growl is using Gritter
A Growl message would come up possibly with whatever was changed, new scores and then an option within that message to refresh and view the new results.
jQuery Ajax information

Forcing Google Analytics Tracking Code to Sleep

To use Google Analytics, you put some JavaScript code in your web page which will make an asynchronous request to Google when the page loads.
From what I have read, this shouldn't block or slow down page load times if you include it directly before the end of your HTML Body. To verify this, I want to make the request after some period of time. The user should be able to log into my site regardless of the time it takes for the request to Google or if it comes back at all (the tracking code is on the login page).
There is a 'pageTracker._trackPageview()' function call in the Google Tracking code. Is this where the request is sent to Google?
If so, should I just do:
window.setTimeout(pageTracker._trackPageview(), 5000);
any help is appreciated, especially if you have worked with Google Analytics and have this same problem.
window.setTimeout(pageTracker._trackPageview(), 5000); will call the code immediately - what you want is
window.setTimeout(function() { pageTracker._trackPageview(); }, 5000);
This should work:
window.setTimeout(pageTracker._trackPageview, 5000);
That should do it. Put some quotes around the call:
window.setTimeout("pageTracker._trackPageview()", 5000);
You can check this using Firebug if you want to see the request go through.

Show animation in a jsp page while waiting for server to respond

What would be the best way to display an animation while waiting for server-side processing of a jsp page to complete.Basically, the server side request can take more than a minute to process and until then I would like the user to have some way to get an update of how his request is getting along.I require an animated gif and a line stating that x% has been completed.
One of the methods I came across while surfing the net was to have an intermediate page that shows the animation while loading the actual page using javascript (location.href).So ,I figure use a couple of ajax calls from the intermediate page to a servlet to get the feedback.Problem is it works fine in IE 6/7 and Firefox 3.But the ajax callbacks dont seem to be getting executed in case of Chrome and Opera (The location.href part seems to mess it up and the callbacks never get executed).
If this approach is flawed how should I go about it?.And if not how can i fix this issue?
Thanks in advance
The simple way I've done this is to go to a JSP that displays a "X % completed" page (image, whatever) that reloads periodically. And when the request is complete, it redirects to an appropriate page to indicate completion. A lot simpler than AJAX, if not as fancy, and requires nothing that is browser-specific.
Try window.location='URL'. Also document.location='URL' works, but I think is deprecated.
Also to be opinionated I do think that a non-reloading web page is much saucier than just being forwarded.

Categories