Wordpress Registration - javascript

My site uses (a customised) Login with Ajax plugin, which simply redirects users to the referring page upon signup/log in. Is there some way that I could hook into the registration javascript event and call Google Analytics manually to trigger the goal, or otherwise create a conversion event for when users register (but one that is not triggered by logging in)? Any help would be appreciated!

I see at least two options. Both would work by registering a "virtual URL" (and address that does actually exist in your website) for the confirmation page. You do this by adding the (virtual) page location to a pageview call:
ga('send','pageview','/thankyou.html');
One way is to edit your plugin code and add the above directly to the ajax success handler (the bit where the redirection happens after a successfull ajax response).
If for some reason you rather want to add tracking via a global js file you can (at least if you are using jQuery, although undoubtedly other libraries have similar mechanisms), a global ajax sucess handler that hooks into all ajax events on your page and check if the called ajax url is that for your confirmation page:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "ajax/thankyou.html" ) {
ga('send','pageview','/thankyou.html');
}
});

Related

How to enable all authenticated routes to show the Devise ajax Login form?

I have implemented devise to accept Ajax Login and have created a form to login via ajax which I have put up in a modal. However, only when I set up event binders for specific buttons, which trigger the modal ( Such as "Login now Button", am I am able to see the form and login. However, I want the modal to appear for any restricted route. ( For example, if I click on : "Add review" button, the modal should appear for login( If the user is unauthenticated ). How do I achieve this ? )
Can I add a specialized class to all the links which require authentication so that I can target them?
This sounds like you need a handler for your ajax authentication in your JS.
The problem you have is that Rails does not invoke JS unless you explicitly define it. Especially with the likes of user authentication, your application will do nothing unless you tell it to:
#app/assets/javascripts/application.js
$(document).on("ajax:error", function(xhr, status, error){
if(xhr.status === "401") {
// invoke modal
}
});
Devise returns a 401 - Unauthorized error whenever you hit an action without the right credentials:
This means that if you send an Ajax request (with remote: true etc), you'll be able to capture this response and use it to invoke the modal.
I don't know how you're invoking your modal form; the code above will give you the ability to put your own functionality into the function.
--
We've done something similar (just click "login" at the top):
We had to change the Devise::SessionsController a little to get it working. I can do the same if you need it; I think sending a standard request, as above, will work as reqired.
Update
Okay this is a head-burner.
I'm sure there has to be a way to send the request to the server & evaulate the response.
The most basic implementation of this would be to make every link go through ajax, although this would kill a lot of the Rails convention...
#app/assets/javascripts/application.js
$(document).on("click", "a", function(e){
e.preventDefault();
// send via ajax & then monitor the response
});
I've been trying to find a way to fire the link, capture the response in JS and then show the modal if the response is 401 etc...
There has to be a way to do it. Let me keep checking

How to perform an ajax call on page unload?

I have a dashboard where users can toggle some input values in order to configure the appearance of the page.
I want to store those changes in a DB table, so when user comes back, the dashboard appears according to the specific user configuration retrieved from the DB.
I know how to send those values to DB and how to retrieve them
I don't want to make ajax calls every time the user changes a configuration.
Instead, I think this senario would be better:
Page load (retrieve DB configuration if exist)
User toggles the configuration ui items (e.g. checkboxes, select etc) and the appropriate client side changes take place (some divs get hidden, some others are shown etc and the config input values are stored to a hidden field), but no ajax call takes place.
When user clicks a link to another page, the configuration input values (which have been stored to the hidden field) are sent to the DB via ajax call.
MY QUESTION
One solution(?) would be the use of onbeforeunload event like this:
window.onbeforeunload = function(e) {
// Perform the ajax call
return 'Do you want to save the configuration changes?';
};
But, if the user's browser prevent popups, the function will not get executed?
Is there a way to perform an ajax call on onbeforeunload event, without calling a dialog box?
No. During unload, the browser will kill all pending requests. So the AJAX might or might not arrive at the server. You also can't do it inside the handler of the beforeunload event because the first A in AJAX means: Asynchronous -> Just put the request on the stack and eventually execute it. So the request will be looked at only after the handler returns. But very soon after that, the browser will kill anything related to the page.
The solution is to always send updates to the server while the users makes changes. Put those into a special "temporary" table from which you can restore the state later.
You could also use something like localStorage in the browser but then, the data wouldn't move with the user. For example if they were working on an tablet and that broke or had a power loss, they could move to their PC to continue where they left off.
You can't guarantee that an Ajax call will complete in this way, see Aaron's response. My suggestion would be to use something like localStorage to read / write the user's settings instead.
If you need a user's appearance to persist across multiple devices, add a periodic request to read / write the recent updates from localStorage to the central DB.
Try using Navigator.sendBeacon on the visibilitychange event.
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
navigator.sendBeacon("/ajaxUrl");
}
});
Regarding Navigator.sendBeacon(), MDN details that when leaving a page,
the browser may choose not to send asynchronous XMLHttpRequest requests.
With the sendBeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. This means:
The data is sent reliably
Regarding the visibilitychange event, MDN recommends:
Web sites often want to send analytics or diagnostics to the server when the user has finished with the page. The most reliable way to do this is to send the data on the visibilitychange event

How to remove event listeners bound by external script

I have 'black-box' type ASP framework, let's say I cannot modify it. But I can add HTML modules to it. I've made HTML module using AJAX for user logon and fetching data. The problem is I need to intercept submit event of the logon form. Then it has to call web service, return token and store it in a cookie before the page reloads.
First I need to stop the page from reloading. So I need to unbind events which cause the reload. But how? I don't have access to code which bound the events. It's not mine.
I was able to attach my own event handlers to submit button, login and password fields. They do their job - they start the AJAX request which should perform my logon procedure. Well, at least they try, because almost always my AJAX call is killed before it can finish, the page reloads, and my module has no token it should have by then. 1 in about 20 calls - it succeeds, so it looks like possible to do.
If there was a way to prevent page from reloading until the AJAX callback completes, it would probably be enough for it to work.
Is there absolutely no way of killing events which I din't bind in my code?
Well, I've found the way to achieve the goal without actually unbinding any events.
I needed to replace the form action attribute with '#', the same with special submit link href ('#'), and... DONE! After my AJAX call completes (or fails), it restores original hrefs and submits the naughty form.
So the question I asked was wrong - my fault. I needed to prevent a form from being submited and this is way easier than removing alien events!
TL;DR - kill hrefs first, then restore them :)

With the Javascript event onbeforeunload, is it possible to do anything other than an alert dialog?

In all of the sample code I have seen, it appears that the only function of onbeforeunload is to serve up an alert dialog box prior to the person leaving the page. Is that the only thing that can be triggered by the event or is it possible to do something else, like an unobtrusive function that sends off partial form data?
I am trying to capture abandoned shopping carts in Yahoo! Small Business and unfortunately I do not have access to any server side scripting, so I'm forced to work client-side only.
I was also thinking of doing an ajax posting of data after the email field was changed, and then comparing the list of all forms partially submitted against completed carts to determine which were incomplete.
You can save the partial form data in localStorage. Then, when another page is loaded, you could check for the presence of that data and AJAX it to the server, deleting it from localStorage on success. Or you might be able to just use that data in JavaScript, without involving the server, but that depends on your setup.
<body onbeforeunload="return ('You will lose all your data')" onunload="alert('You have gone away!')">
</body>
Onbeforeunload uses for alert box. Onunload for anything else.
You can technically fire off an ajax event, but there is no guarantee that it will complete before the page is actually reloaded.

Is it a good idea to make an AJAX call on <a> click before taking the user to the href location?

I have a few scenarios where on a click of <a> element on a page I need to send some data to the server with AJAX and if everything is fine take the user to where <a> is pointing.
Here is the flow:
User does something on the page.
User clicks <a> element.
AJAX call goes to the server, server processes the request, sends the response.
If response is all good -> navigate, if some error -> return false from JavaScript, thus abort navigation and display error message.
So, I'm just wondering, is this generally a good or a bad practice and why?
Thank you.
There are no hard and fast rules regarding such issues, but one common rule of thumb is that <a> links shouldn't be used for POST-like actions such as updating a database. So ask yourself what the AJAX call does: if it simply requests some data from the server, it is okay to do this with an <a>; if it causes some sort of update to occur, consider using a <button> instead.
In the past, if a link has an onClick method, I've always done away w/ the href altogether. In your AJAX onClick method, just handle the logic within the method and, when needed, call Window.Location inside the method to load a new URL.

Categories

Resources