Add to Apache logfile when user leaves webpage - javascript

I want to time how long a visitor spends on each page of my website by downloading and analysing the "ex" log file created daily by Apache in the logfiles folder.
I can do this when they move from one page to another but if someone visits the homepage and then leaves I have no idea how long they spent on it.
Could I somehow use Javascript's OnBeforeUnload event to request a file from the server, which would then appear in the log?

I am not sure why do you want to request a file from the server. You could just request a blank page:
$(window).unload( function () {
$.ajax({
async: false,
type: 'GET',
url: '/url/to/blank/page'
});
}

Related

I need to send and listen to events from a 3rd party JavaScript API

We are a social start-up and are given a great opportunity by one of the biggest banks in our country. Basically they will feature our website in their Mobile App, and users can access our website via their app in an iFrame. We are currently working on integrating a SSO log in flow between their app and our website, so users are logged in immediately when they open our website in their app.
For this, they have created an API that we're able to use. The API requires 2 main things to get the flow working:
send a pageLoaded() event when the DOM is ready, when this event is sent, we get returned a token to fetch the user's personal information with a public event.
send a pageReady() event when the backend logic processing is done (eg account created and user logged in).
They will show a spinner in their app, until the pageReady event is being sent to them.
My website uses PHP and JS (jQuery) as the main technologies. I am having a number of issues on how to implement this correctly.
This is the code I am using as of now, it works in a certain way, but it's very troublesome for the reasons mentioned below the code snippet:
$(document).ready(function(){
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host;
/*** Mobile App JS Code ***/
var receiver = new PostmessageExternalReceiver();
var sender = new PostmessageExternalSender();
receiver.addTokenEventListener(function (api, token, version){
if (api == 'init') {
$.ajax({
type: 'post',
cache: false,
url: baseUrl + '/login/abc/abcLogin',
data: {
'token': token
},
dataType: 'json',
success: function(response){
sender.pageReady();
window.location.replace(response.redirect_url);
}
});
}
});
sender.pageLoaded();
});
These are the problems that i'm not sure how to get around:
Since the sender.pageLoaded(); is in the jQuery document ready, and after performing the AJAX request, we are redirecting again to the same page (the homepage), because after the redirect, the user will be logged in and some extra blocks will show on the homepage. So if we are on the homepage again, the document ready will fire yet another sender.pageLoaded() event, and we are stuck in an infinite redirecting loop.
Right now I am including all 4 API javascript libraries provided by our third party, and my own javascript file including the AJAX request and the pageLoaded() and pageReady(). This is only applicable for users that come to our website via the 3rd party mobile app. For all other visitors in our website this is not applicable and requires extra resources to be loaded in when they're not used. (the ajax request will never be executed for them because a token will not be sent via the mobile app, but still we do not want to send a pageLoaded() for every visitor on our website, even if he is not from the mobile app.
This is a nice-to-have question: since we need to send the pageReady() after our PHP logic (via AJAX request) is done, we cannot do the redirect in PHP, so I return the redirect_url in my AJAX and then do the window.location.replace() method with the redirect URL. In the 3rd party app, this will cause the app to remove the spinner (on the pageReady() event) and show our website, but immediately afterwards we will redirect the user using the window.location.replace() , this causes a refresh of the page, and thus a small annoyance and not so smooth experience for the user. They expect after the spinner is gone that the website is immediately accessible. How would I go around this?
Thanks a lot in advance!

Why ajax call is very slow?

I was calling an ajax function on load page event. When I load the page, in the server log, There was not existing call log(I log entrance and out on all mvc server method). The request from javascript to server was taking some time, 2 to 3 minutes. The strange thing is when I test it local and test server, it works well. It occurs just when I deploy a project to the real server!
I found some posts about the method to do ajax, xmlhttp, $.ajax(). I already used both. But It still exists.
This is my javascript code.
$(document).ready(function () {
$.ajax({
type: "GET",
url: allservicesUrl,
async: true,
success: function(result, status, xhr){
var services = JSON.parse(xhr.responseText);
for (i in services) {
createServicecard(services[i]);
}
},
error: function(xhr, status, err) {
alert(xhr.responseText);
}
});
})
I wanna execute it immediately. How do I correct this problem?
Thanks for the advice.
I saw an answer and comments. Then, I saw the dev tool(network tab), finally, I found the problem.
Now I correct it, it works well. Thank you very much.
ps. Problem: connecting the internet in closed network.
Use the debugging/developer tools in your browser to trouble shoot this issue.
look in the console and see if you have any JS errors, then look in the network tab. Clear the entries and then reload the AJAX call.
you should be able to see if your script is slow to send the request to the server or if the server is slow to answer.
until you figure out if the bottleneck is in the script or on the server you can't fix it.

PHP Mailer, blocking whole server execution while sending an e-mail

First, I've seen this question: Send mail without blocking 'execution'
But, I need to know why PHP is not a multi-threading process but has no problem if two people try to connect at the same time.
I am calling the mail script by an Ajax call actually :
$.ajax({
url: 'sendMailTemplate.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {}
...
My problem with PHP mailer is that, when I'm sending an email if this takes 10 seconds, then for 10 seconds i can't use any feature of my website ( and the website is like down for everyone for 10 seconds).
Should I try to use cron jobs? Is there any tutorial for PHP mailer + cron jobs? What's the best way other than cron jobs?
Should I try to use cron jobs ?
Yes
Is there any tutorial for PHP mailer + cron jobs ?
I tried my own logic by using multiple reference :
Below logic execute like queue and also sending time base on your cronjob & you hrly mailing limit.
Mailing : when you click on send email that time you have store all emails into "temp_table" of your database with their "to,cc,bcc,suject,body" columns.
Write cron job for hrly(your time) basic which will execute in certain time span.
In cron script you have to write code which will take emails (set query limit to take no of records) from "temp_tables" & send to the recipient. After success full sending, delete those mails from "temp_table" of you database.
Whats the best way other than cron jobs ?
You have contact to your service provider to increase hrly mailing limit, increase your server speed, php.ini : change loading time (this option not works every time), refer different language like python
Just switch to a smtpd that allow placing mails in queue and sending them asynchronously.

Exchange Information between two windows

Im not sure how to explain my problem in short at the title, so forgive me for this. Lets say I opened my website in some random page, and I have a register button. Really simple, but in my case I require the registration form to appear in other tab(or window). Not "RederPartial", nor popup window of some kind, legit new tab. The problem is, I want to be able do detect, from that random page of mine, when the registration completed (ie a new user has been created). How can I pass this information? without reloading the first page
There are various ways to make two windows talk with each other (through server, with cookies, using FileSystem API or Local Storage.
Locale Storage is by far the easiest way to talk between two windows who come from the same domain, but it is not supported in older browsers. Since you need to contact the server anyway to find out when someone has registered, I recommend using the server (Ajax//web sockets).
Here's a somewhat simple AJAX solution which you could use in your random page:
(function(){
var formOpened = false;
var registered = false;
//Change to whatever interaction is needed to open the form
$('#registerbutton').on('click', function(){
if (!formOpened){
formOpened = true;
//Will try to poll the server every 3 seconds
(function pollServer(){
$.ajax({
url: "/ajax/pollregistered",
type: "GET",
success: function(data) {
if (data.registered){
registered = true;
//do other stuff here that is needed after registration
}
},
dataType: "json",
complete: setTimeout(function() {if (!registered) pollServer();}, 3000),
//will timeout if request takes longer than 2 seconds
timeout: 2000,
})
})();
//opens the new tab
var win = window.open('/registrationform', '_blank');
win.focus();
}
});
})();
You can then use the session key of the visitor in the '/ajax/pollregistered' action to write your backend code to check if and when this visitor registered as user to your site.
If you don't mind using the local storage, you could poll the storage instead of the server and have the registration page write to local storage upon registration. This is less stressing for your server, but might not work for users with ancient browsers.
Also worth nothing that this method of opening a new tab is not completely reliable. Technically there is not a sure shot way of opening a new tab with javascript. It depends on browser and the preferences of the user. Opening a new tab might get blocked for users who are using anti popup plugins.
That being said, I strongly recommend revising your design and try finding a way to work with just one window instead. It's probably better for both yourself and your users.

Reloading vs Refreshing page with jquery on shared host

I am working with codeigniter and jquery. I am using ajax to send some info to a codeigniter function to perform a db operation , in order to update the page.
$.ajax({
type: "POST",
url: BASE_URL+"Update/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
},
complete: function() {
alert("REFRESHING..");
window.location.href = "pan_controller/reply";
}
});
After the operation is complete I want to reload the page. This works normally in locally on my WAMP. However when I deploy to a shared host I usually have to reload the page manually, (using the reload button in the browser -- screenshot above). I see no errors in firebug. I've tried a variety of fixes but have recently started to wonder if this is a caching issue on my shared hosting server. If so is there a better way to reload using jquery rather than just redirect so as to avoid a cache on the shared host?
Have you established that the complete function is running in those cases when the page doesn't reload? If so then I think you are right, it's a caching problem.
You can try adding a timestamp parameter to the end of the window.location.href value to make it unique each time and avoid any issues with caching, although a better approach would be to send the correct headers back with the response, so that the browser knows not to cache that page.
window.location.href = "pan_controller/reply?t=" + (new Date().getTime());

Categories

Resources