AJAX GET race condition? - javascript

I am attempting to track events when links are clicked on my site in a method similar to the following.
Example
<script type="text/javascript">
jQuery(function($) {
// track clicks on all anchor tags that require it
$('a.track').live('click', function(e) {
// send an AJAX request to our event tracking URL for the server to track it
$.get('/events/track', {
url: $(this).attr('href'),
text: $(this).text()
});
});
});
</script>
The problem that I'm having is that a new page load interrupts the AJAX request, and so sometimes these events aren't being tracked. I know Google Analytics has a _trackPageview function that can be attached to onclick events though, and this doesn't seem to be an issue for that. I'm wondering what's different about their call vs. mine that I'm seeing this race condition, and GA isn't. e.g.:
Example
Note that I'm not worried about the result of the AJAX request...I simply want it to ping the server with the fact that an event happened.
(Also, I expect I'll get at least one answer that says to simply track the new page load from the server side, not the client side. This is not an acceptable answer for this question. I'm looking for something like how Google Analytics' trackPageview function works on the click event of anchor tags regardless of a new page being loaded.)

Running Google's trackPageview method through a proxy like Charles shows that calls to trackPageview( ) request a pixel from Google's servers with various parameters set, which is how most analytics packages wind up implementing such pieces of functionality (Omniture does the same).
Basically, to get around ansynchronous requests not completing, they have the client request an image and crunch the parameters passed in those requests on the server side.
For your end, you'd need to implement the same thing: write a utility method that requests an image from your server, passing along the information you're interested in via URL parameters (something like /track.gif?page=foo.html&link=Click%20Me&bar=baz); the server would then log those parameters in the database and send back the gif.
After that, it's merely slicing and dicing the data you've collected to generate reports.

Matt,
If you just want to make sure that the tracking pixel request is made and you don't depend upon response then just doing document.write for the tracking pixel image will do the work.
And you can do the document.write in your onclick handler.
AFA race condition between href and onclick handler of anchor element is concerned the order is well defined.
the event handler script is executed first
the default action takes place afterwards (in this case the default handler is href)
(Source : Href and onclick issue in anchor link)
But yes, if you depend upon the response of the tracking request to the server then you will have to make it synchronous.
Suggested option would be to call some javascript function to wrap the already defined onclick handlers and then in the order make the calls. Make sure that your tracking request is not asynchronous.
Though it is suggested that you should not be dependent upon the response of the tracking pixel request.

Related

Simple web development concept I can't find any info on +update

Let's say we have a web app that only has one element, for example an image IMG1 and if an user clicks on it, it will change to another image IMG2 (this change should be visible only to the users that clicked and triggered the event).
Then, I have another event that triggers when a total of 100 users clicked on the image (or any other back-end related event), and this time I want to dynamically change the image to IMG1 (but now I want the change to happen and be visible to all the users of the website).
The confusion starts when I realise that for both events the function would be the same (changing the src of that HTML img element) yet I want it to have a different effect:
on the event of a user click change it for that user only.
on an outside event that doesn't involve a specific user, change it for all the users to see the same image.
How does this work? what is the thing that makes the difference between a HTML change that only affects the users locally (on their actions) and a change that has a global effect (to all the users).
UPDATE !!!
I should have been more specific with what I don't know.
I'm familiar with AJAX request and I already have the backend sorted.
In the frontend script I have an event listener for the event from the backend, and all my questions are actually about 'what and how to do it' after the event listener is triggered.
Now, what I want to do when this happens is to make some changes, the main one being to change that image IMG1 to IMG2 for all the users (as it would be a dynamic update to the website) but also:
I need that change to be permanent, so in a case of users reloading the page or new users coming in, they all should still see IMG2. (And the only time the image would change would be when the event listener on the frontend script will trigger again on the same backend event to change the image again (to IMG3) for example. And yes, in this example there is NO 'on click' request for the users to change the image, so ignore my example previous to the update.
Now to address your answers, I checked the web sockets stuff and it seems to be doing what I need if I run that 'on event' change of image to all sockets. Which only leaves me with 2 questions now:
1) Will this change that occurs on all sockets to change the image be permanent, so in a case of users reloading the page or new users coming in, they will all see the new image (IMG2) as a permanent change to the webpage ?
2) Regarding these type of permanent changes, isn't reactJs a way of doing such changes dynamically?
What would actually happen if on that event listener (for the backend event) I simply ignore all the web sockets stuff and run the same code of changing the src of the image ?
2.5) Because from how I see it, that event in the backend fires without any specific user input, thus is not linked with any user. So if I simply run the code on that event without websockets It should either do absolutely nothing (so no change for anyone) OR do the change for all the users (acting simply as a dynamic update to the webpage). How does this work?
I'm looking forward for your answers, and thank you all in advance!!!
The click event needs to be handled by an AJAX request, sending a message to the server and the server will handle that and respond. Upon the response, the first type of event is executed for the user.
On server-side you will need to have an event queue somewhere, maybe in the database. If you are using WebSockets, then you will have to execute the second type of event for all users if the request is met via WebSocket channels. If you are not using WebSockets, you will need to do polling from the browser. Anyway, you will need a counter on the server-side to be able to determine when the second type of event is met.
EDIT
Yes, WebSockets are the way to go unless there is a strong reason not to do so, like a boss saying he or she does not want the server to use WebSockets. With WebSockets you have a live channel between the server and the client browsers. You can use this channel to send the URL change to the client. On the other hand, the client will have to handle the change with Javascript, gathering the tags where the src is to be changed and change them. If you happen to have a class of changable for all such tags, then executing the change can be done with a function like this:
function changeSources(newSrc) {
var items = document.getElementsByClassName("changable");
for (var index = 0; index < items.length; index++)
items[index].src = newSrc;
}
However, this change will be effectuated only for the loaded page which was initially loaded and upon new loads, this, by itself will not use the new src. So you will have to solve that problem as well. A neat way to do it is to store the new src on the server before you send it out to the client via WebSocket and use this stored src as the src of those tags when the client requests for the HTML. So, your problem has two parts, the first is changing the src on already loaded pages and the second is making the change permanent.
ReactJS is a Framework. At this point we need to define the technical background, since ReactJS will use a possible solution from these.
WebSocket
https://www.npmjs.com/package/react-websocket
This is a WebSocket implementation. The best technical background here is to use WebSockets unless there is a very good reason not to do so.
Server notification system
https://www.npmjs.com/package/react-notifications
Server notification systems in general are one-way ticket roads. The server may send a notification, but the client has no such possibility.
Polling
The browser may periodically send HTTP requests to the server and this way it can receive the src change response. This is a good solution if WebSockets and server notification systems are not an option.
Forever frame
You can use an invisible iframe to be loaded forever, which will provide you with the possibility of sending real-time messages from the server to the client, but this is very hacky.
The difference may be between a front end, running in the browser, or the mobile app, of each user, which is local, and the back end, where you can share data between all users.
This can be implemented by, for example, firebase. Here is an example: Firebase - Multiple users simultaneously updating same object using its old value
This does not mean, obviously, that back end data is always shared... In many cases each user accesses his own copy of back end data that is stored in a database.

Chrome extension manage webRequest lifetime

I am making an extension that needs to capture POST data directed to a site and once the site response confirms success, change some local data to reflect it.
The issue is, the POST data is located in requestBody from the onBeforeRequest event, while the success confirmation is in the onCompleted event. I understand that the lifetime of a webRequest should be managed using its unique requestId, but I am using an Event Page and therefore trying to avoid the use of global variables.
eventPage.js:
function continueListening(requestDetails){
function finishListening(completeDetails){
if (completeDetails.requestId === requestDetails.requestId){
doStuff(requestDetails, completeDetails);
chrome.webRequest.onErrorOccurred.removeListener(finishListening);
chrome.webRequest.onCompleted.removeListener(finishListening);
}
}
chrome.webRequest.onErrorOccurred.addListener(finishListening,{urls:["*://site*"]});
chrome.webRequest.onCompleted.addListener(finishListening, {urls:["*://site*"]});
}
chrome.webRequest.onBeforeRequest.addListener(continueListening, {urls:["*://site*"]});
I decided to try nesting listener registrations for the finalized request in order to provide them with the scope to compare requestIds with the initial request containing the form data. This appears to work, but I am concerned about a potential race condition between the resolving of the webRequest and the registration of the nested listener intended to listen for it, leading to any number of useless unremoved listeners.
The other option I see is to store the requestDetails in chrome.storage.local and check them against the completeDetails once they arrive. My main hesitation there is that if for whatever reason execution is interrupted the local disk space could be polluted with unresolved requests.
Is there a better way of doing this?
EDIT: Unfortunately although I believed I was making an Event Page, I did not have persistent:false in my manifest. As I learned when I added it, Event Pages do not even support webRequests. The Event Page equivalent, declarativeWebRequest, seems to have died in the beta channel. So making it a Background Page seems to be the necessary solution.

How do you make a link perform an action without reloading a page?

The clearest example of this I could think of is the Reddit Upvote/downvote buttons how when you click the button, the value for upvotes is updated, the upvote button lights up, and the page DOES NOT reload, you just stay exactly where you are on the page.
I am trying to make a feature similar to this and I can totally figure out how to do it with reloading, but I want it to not reload so the user experience isn't disrupted.
Is it possible to do this with php? or would I need to use javascript or something?
The action I would need it to perform would be a basic update query in the database.
This would be done with an Ajax call to your php script. Ajax is designed for these asynchronous updates and/or reloads.
Another way you can do this is with HTML5 WebSockets. You could have the client send a trigger to the server when the user clicks the upvote, and then the server could update and push back the data. It would, however, be a bit overfill for this.
If what you want to do is to contact a server to either send it some state or to retrieve some state from the server (or both), then you would use AJAX with javascript in order to contact the server without reloading the page. You can then also use javascript to update the state of your page after the operation. That is generally what the Reddit page you refer to is doing.
Conceptually, you'd set up your page like this:
Put the link on the page.
With javascript install an event handler so you are notified of a click on the link.
When the link is clicked, your event handler will be called.
Prevent the default behavior of the link so the browser doesn't navigate to a new page.
Then, in the event handler, send your data to the server using AJAX. You will obviously need a URL on your server and server process that can accept and process the data for you and return a value if you need to.
If you need the response from the server, then set up a callback function for when the AJAX call completes (this will be some indeterminate time in the future).
Then, if you need to change the current page in any way (like show one more upvote), then you can modify the current page with javascript to show that new state.
Ajax is easier to use with a library (like jQuery) that contains some ajax support code, but you can certainly implement it in plain javascript too.
Here's one example of ajax with plain javscript. You can find many other examples with Google.
This MDN tutorial on AJAX seems pretty helpful too to show you how it works.
You could use JavaScript to do this. Here's a quick sample:
Vote Up
Simple solution in JavaScript:
var el = document.getElementById("upvoteBtn");
el.addEventListener("click", onVoteClick);
function onVoteClick(e) {
e.preventDefault();
// do something
}
Here's a fiddle.
NOTE: I see you'd be updating the database. In that case, you would have to use AJAX in the onVoteClick function (or use XMLHttpRequest) for this. JavaScript is a client-side programming language and will not be able to communicate to the server without the use of AJAX or XMLHttpRequest. Using the jQuery library, you should be able to write AJAX pretty easy.
It's called AJAX.
With AJAX you can send a request in the background.
The easiest way is to use the jquery libary for this.
You can also output some data as JSON back to the script if you want to take some other actions depending on the result from that query.
A good tutorial is this one.
It also explains how this requests (called: XMLHttpRequest) work.
You need to use Javascript's XMLHttpRequest
You can use AJAX...
It allows you to use JavaScript (client side) to call server side functions. Here's a good example.

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.

JavaScript/jQuery: How to make sure cross-domain click tracking event succeeds before the user leaves the page?

I'm implementing click tracking from various pages in our corporate intranet in order to add some sorely needed crowd-sourced popular link features ("most popular links in your department in the last 24 hours", etc.)
I'm using jQuery's .live() to bind to the mousedown event for all link elements on the page, filter the event, and then fire off a pseudo-ajax request with various data to a back-end server before returning true so that the link action fires:
$("#contentarea a").live("mousedown", function(ev) {
//
// detect event, find closest link, process it here
//
$.ajax({
url: 'my-url',
cache: false,
dataType: 'jsonp',
jsonp: 'cb',
data: myDataString,
success: function() {
// silence is golden -- server does send success JSONP but
// regardless of success or failure, we allow the user to continue
}
});
return true; // allow event to continue, user leaves the page.
}
As you can probably guess from the above, I have several constraints:
The back-end tracking server is on a different sub-domain from the calling page. I can't get round this. That's why I am using JSONP (and GET) as opposed to proper AJAX with POST. I can't implement an AJAX proxy as the web servers do not have outbound network access for scripts.
This is probably not relevant, but in the interest of full disclosure, the content and script is inside a "main content" iframe (and this is not going to change. I will likely eventually move the event listener to the parent frame to monitor it's links and all child content, but step 1 is getting it to work properly in the simplified case of "1 child window"). Parent and child are same domain.
The back-end is IIS/ASP (again, a constraint -- don't ask!), so I can't immediately fork the back-end process or otherwise terminate the response but keep processing like I could on a better platform
Despite all this, for the most part, the system works -- I click links on the page, and they appear in the database pretty seamlessly.
However it isn't reliable -- for a large number of links, particularly off-site links that have their target set to "_top", they don't appear. If the link is opened in a new tab or window, it registers OK.
I have ruled out script errors -- it seems that either:
(a) the request is never making it to the back-end in time; or
(b) the request is making it, but ASP is detecting that the client is disconnecting shortly afterwards, and as it is a GET request, is not processing it.
I suspect (b), since latency to the server is very fast and many links register OK. If I put in an alert pop-up after the event fires, or set the return value to false, the click is registered OK.
Any advice on how I can solve this (in the context that I cannot change my constraints)? I can't make the GET request synchronous as it is not true AJAX.
Q: Would it work better if I was making a POST request to ASP? If (b) is the culprit would it behave differently for POST vs GET? If so, I could use a hidden iframe/form to POST the data. however, I suspect this would be slower and more clunky, and might still not make it in time. I wouldn't be able to listen to see if the request completes because it is cross-domain.
Q: Can I just add a delay to the script after the GET request is fired off? How do I do this in a single-threaded way? I need to return true from my function, to ensure the default event eventually fires, so I can't use setTimeout(). Would a tight loop waiting for 'success' to fire and set some variable work? I'm worried that this would freeze up things too much and the response would be slowed down. I assume the jQuery delay() plugin is just a loop too?
Or is something else I haven't thought of likely to be the culprit?
I don't need bullet-proof reliability. If all links are equally catchable 95% of the time it is fine. However right now, some links are catchable 100% of the time, while others are uncatchable -- which isn't going to cut it for what I want to achieve.
Thanks in advance.
I would try a different approach. You can bind to a different event like:
$(window).unload(function(event) {
// tracking code here
});
I would try to return false from the link event handler, remember the URL and navigate away only when JSONP request succeeds. Hopefully it shouldn't add too much latency. Considering you are on the inranet, it might be OK.
Solved!
The short answer is: there is no reliable way to do this cross-domain with a GET request. I tried all sorts, including storing the event and trying to replay the event later, and all manner of hacks to try to get that to work.
I then tried tight loops, and they weren't reliable either.
Finally, I just gave in and used a dynamically created form that POSTed the results, with the target set to a hidden iFrame.
That works reliably -- it seems the browser pauses to finish its POST request before moving on, and ASP honours the POST. Turns out it's not 'clunky' at all. Sure, due to the browser security model I can't see the result... but it doesn't matter in this case.
I am now kicking myself that I didn't try that option first.

Categories