Custom tracking via API - javascript

I was looking to get some opinions on something I am trying to achieve. I have built an API which essentially comprises of GET requests that returns data. A third party have built a frontend that utilizes my API. I am hosting the frontend and backend but they sit on seperate servers. The frontend has no access to the server besides via the API.
Now on a third level, I need to implement some tracking. Essentially, if a button is clicked on the frontend I want to record this. So I thought that I could add a database table to my API database for this. I can then provide a route to record the information I need. With the API set up, I have created my own script which essentially looks something like this
$( ".button" ).click(function(e) {
e.preventDefault();
$.ajax({
url: "https://someurl.com/tracking",
type: "POST",
data: {
"Element" : "Button Click",
"id": someID
},
success: function (data) {
alert(data)
},
error: function(xhr, ajaxOptions, thrownError){
alert("ERROR")
}
});
});
So if any element with the class button is clicked, an AJAX request is made to my API and then the API can put the data into the table.
Now in thoery the above approach should work. I did have a couple of questions however.
I now essentially have a frontend on server A, a backend on server B, and a seperate tracking script which I will place on server A and simply load in the frontend. I am expecting a lot of visitors to this application, so would this tracking and all of the requests it will make cause any issues?
My main question however is this. Is there any way I can implement this tracking without interfering with the application itself, almost making it unobtrusive. Essentially, if something goes wrong with the tracking, I do not want it to have any impact on the application (frontend and backend) itself. Are there any safeguards I can implement to ensure this?
Any advice appreciated.
Thanks

Related

Rails - Call ajax request when database is updated

So I'm creating a basic jackpot betting site for fun and it allows users to put money into a pot and then based on the percentage of money each user puts in it randomly picks a winner. It's working fine at the moment but I feel like the way I'm updating the jackpot page with ajax is really bad. At the moment I have javascript that makes an ajax request each second to get the pot info (size of the pot, players, etc..). I feel like there is a much better way to do this. Is it possible to only make an ajax call when the database is updated? Thanks!
My javascript at the moment:
setInterval(update, 1000);
function update() {
getPotID();
$.ajax({
type: "POST",
url: "/jackpot/update/" + potID,
complete: function(response) {
$('.live-jackpot').html(response.responseText);
getPotInfo();
},
error: function(xhr, status,error) {
console.log("Error");
}
});
}
as said from 7urkm3n, ActionCable has great advantage for this functionality.
Right now you are writing Javascript code that is executed on the client side. Every user that will start a GET http request to your site, will load that javascript files. They will start performing POST request every second to your backend server.
ActionCable is a websocket preinstalled in Rails 5. This means that to configure the notifications with ActionCable and Rails 5, you already have installed everything in your app (if you are using rails 5), you just need to install Redis on your local machine for testing the app in development.
I am not an expert, my understanding is that you use a specific database called redis to store the information about the subscription. I quote a useful article
So PubSub is this concept that Redis and Postgres and a few other things supports, and basically you have this ability to have Channels and the ability to subscribe (and receive those messages) and publish to those channels and anyone listening will then receive those messages.
An example of this is a ChatroomChannel, you could have people publishing messages to the ChatroomChannel and anyone who was subscribed to the ChatroomChannel would receive the broadcast from the channel with the websocket.
This is something you are missing, this way you could only find which users are actually on the playing page and which users are just browsing around, based on this ActionCable creates a channel to communicate between server and client and then creates a subscription to distinguish users that are actually on the playing page and those that left and should not be anymore notified
I quote another useful article
Before we dive into some code, let's take a closer look at how Action Cable opens and maintains the WebSocket connection inside our Rails 5 application.
Action Cable uses the Rack socket hijacking API to take over control of connections from the application server.
For every instance of your application that spins up, an instance of Action Cable is created, using Rack to open and maintain a persistent connection, and using a channel mounted on a sub-URI of your main application to stream from certain areas of your application and broadcast to other areas.
so every user that connects, ActionCable creates a channel that uses a specific url localhost:3000/cable to communicate between server and client (browser)
Action Cable offers server-side code to broadcast certain content (think new messages or notifications) over the channel, to a subscriber. The subscriber is instantiated on the client-side with a handy JavaScript function that uses jQuery to append new content to the DOM.
This means that the server can call the client with parameters and change the page with jquery functions. For ex. appending a div, with a new message.
In my app https://sprachspiel.xyz I do the following in the MessagesController#create
ActionCable.server.broadcast 'messages',
message: message.content,
user: message.user.name,
chatroom_id: message.chatroom_id,
lastuser: chatroom.messages.last(2)[0].user.name
head :ok
so basically, I have my message in my controller and I can update the client by using the ActionCable.server.broadcast function
then in my asset pipeline file /app/assets/javascripts/channels/messages.js I have the following code that trigger the change in the browser adding the message
App.messages = App.cable.subscriptions.create('MessagesChannel', {
received: function(data) {
$('#messages').append(this.renderMessage(data));
},
renderMessage: function(data) {
return "<br><p> <strong>" + data.user + ": </strong>" + data.message + "</p>";
}
});
I build an app called https://sprachspiel.xyz that is an actioncable app, this is the github page for the project, on my portfolio you can read more info about my app, so please ask me anything, I'll be happy to look into it!
Good luck
Fabrizio

http request handling in multiple html pages app cordova

I've a MPA(Multiple page application). published for Android and iOS. It simply changes the page when user want to navigate to other page(view). All things are working fine. I want to implement some backend sync features. Problem is, I make Ajax request silently in background and user can change page anytime so app can lose reference of Ajax call which is highly important for keeping track of synced data.
Is there any plugin that can make http request on native code level or some other work around.
Have a look at cordova-plugin-http, it is a native plugin that executes all HTTP requests on a background thread.
Installation:
cordova plugin add cordova-plugin-http
Example POST request:
cordovaHTTP.post("https://google.com/", {
id: 12,
message: "test"
}, { Authorization: "OAuth2: token" }, function(response) {
// prints 200
console.log(response.status);
try {
response.data = JSON.parse(response.data);
// prints test
console.log(response.data.message);
} catch(e) {
console.error("JSON parsing error");
}
}, function(response) {
// prints 403
console.log(response.status);
//prints Permission denied
console.log(response.error);
});
There is no OOB way to do this. You can use something like the Cordova HTTP plugin to move HTTP requests to the native side, which will continue to execute across multiple pages, but it won't know what to do with the response once the response comes back if the user navigated to another page.
If your processing really is all background and doesn't truly need any JavaScript post-processing, you could try to look into something like the cordova-plugin-background-download - that basically executes a GET request in the background and saves the result where you tell it. It only supports GET, but it can work even if your whole app is put into the background.
If you need post-processing or non-GET requests, you can consider implementing your logic in native code in a plugin (perhaps using one of the HTTP plugins for Cordova to help with the actual network marshalling).
It'd be awesome if Cordova could support something like service workers, and I've been looking into that here and there. There's an old implementation for iOS but it doesn't seem to work anymore (and may not really be workable without extensive changes): cordova-plugin-serviceworker.
One other option would be to make your app a pseudo-SPA with some iframes. Have an iframe doing your requests and processing, and create interaction between the content iframe as needed. But that isn't trivial either.

Extjs 5.0.1 How to send a JSON POST request the proper way

Good day all. I'm totally new to Extjs and I've been inserted into a big project already started and left alone.
I'm studing the framework of course, but I'm getting struck every bit of code.
Now, I'd like to understand the proper way to make a rest call, using JSON parameters in POST.
this is my actual situation:
I have defined a combobox in the view file (called setup.js) and I've put a listener on select like the following
emptyText: 'Select a country',
listConfig: {
itemTpl: [
'<div><span class="" style="margin-right: 10px;"><img src="resources/flags/{id}.png"></span>{name}</div>'
]
},
listeners: {
/*created the after render listener to wait until the store is loaded. then I set the default value*/
select: 'onCountrySelect',
afterrender: 'onAfterRenderCombo'
}
on another file, called setupController.js I've defined all my functions:
onCountrySelect: function(a){
console.log("selected ",a.value);
var controller = this,
userData = controller.getUserData();
console.log("user.id",userData.id);
},
Now, on every country select action, I've to send a JSON to a server, to "set" the country used by the user. The call depends also on the enviroment as the dev one is different from the production one, so I guess that I have to make some sort of proxy, but maybe this is a later issue, now I'd like to setup a call for this selection, so I'll use this logic for all the future calls I have to do.
questions are, is there a proper way to define it? do I need a model? or is good to have al the calls in the store? do I need a... proxy(?) or a store or something "external" so I can use the very same call in some other places? is there an example for this?
Guys/Girls, thanks in advance.
Like written here http://docs.sencha.com/extjs/6.0.2/classic/Ext.data.proxy.Ajax.html
A proxy is made to work with a server on the same domain:
AjaxProxy cannot be used to retrieve data from other domains. If your application is running on http://domainA.com it cannot load data from http://domainB.com because browsers have a built-in security policy that prohibits domains talking to each other via AJAX.
Personally Having a console connecting with more than one server, I use an ajax request like that http://docs.sencha.com/extjs/6.0.2/modern/Ext.Ajax.html#method-request
Ext.Ajax.request({
url:'',
method:'POST',
params:{
json:YOURJSON
},
success:function(response){
},
failure:function(response){
}
});
I'm working on a personal proxy, extended by ajax proxy, to do the ajax call without different domain problems. If you want to do an home made proxy you can read all you want about proxy here: http://docs.sencha.com/extjs/6.0.2/classic/Ext.data.proxy.Proxy.html
or simply you can use an external JS class that do the ajax request for you.

Html cloud storage?

I'm trying to make an app using phonegap, but what I want to know is if it is possible to store information online. For example, say there is a number variable, and it is added to when a button is pushed. Could that value be saved somewhere and then a totally different device can retrieve the variable?
I looked at databases, but I couldn't really understand it. I want something that can be accessed by any device as long as It has a key or something.
Is this possible? If so, how would I do it?
PhoneGap uses JS so you cannot connect to the database directly. You should create a Web service using server side languages like PHP on external server and make ajax request on your web service. This approach is possible using PhoneGap.
Sample Code will look somewhere near:
function FetchData() {
$.ajax({
async: false,
type: "GET",
url: "Your_WebService_URL",
dataType: "json",
success: function(data) {
$.each(data, function(i, object) {
if(i==="title"){
document.getElementById("title").InnerHTML = object;
}
if(i==="home_image"){
document.getElementById("title").InnerHTML = '<img src="'+object+'"/>';
}
});
},
error: function() {
alert("There was an error loading the feed");
}
});
The web service, in this case json will throw the variables. May me somewhere like this :
[{"title":"my application"},{"home_image":"http://link.com/image.png"}]
I think this article is useful to you: Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access. Also see this similar question here:
This is entirely possible.
You essentially need two components: the client interface, and the server.
The client displays the results to the users, and, using your example, waits for a button to be pushed. On the push of that button, the client would send a request to the server to increment the stored value (possibly through a jQuery.post, or get, function call).
The server page, written in php for example, receives this request, and accesses a file, or more realistically a database, to increment the value.
With some Googling, this should be very doable, but post specific questions if you get stuck.

AngularJS and WebSockets beyond

I just read this post, and I do understand what the difference is. But still in my head I have the question. Can/Should I use it in the same App/Website? Say I want the AngularJs to fetch content and update my page, connecting to a REST api and all of that top stuff. But on top of that I also want a realtime chat, or to trigger events on other clients when there is an update or a message received.
Does Angular support that? Or I need to use something like Socket.io to trigger those events? Does it make sense to use both?
If someone could help me or point me to some good reading about that if there is a purpose for using both of them together.
Hope I'm clear enough. thank you for any help.
Javascript supports WebSocket, so you don't need an additional client side framework to use it. Please take a look at this $connection service declared in this WebSocket based AngularJS application.
Basically you can listen for messages:
$connection.listen(function (msg) { return msg.type == "CreatedTerminalEvent"; },
function (msg) {
addTerminal(msg);
$scope.$$phase || $scope.$apply();
});
Listen once (great for request/response):
$connection.listenOnce(function (data) {
return data.correlationId && data.correlationId == crrId;
}).then(function (data) {
$rootScope.addAlert({ msg: "Console " + data.terminalType + " created", type: "success" });
});
And send messages:
$connection.send({
type: "TerminalInputRequest",
input: cmd,
terminalId: $scope.terminalId,
correlationId: $connection.nextCorrelationId()
});
Usually, since a WebSocket connection is bidirectional and has a good support, you can also use it for getting data from the server in request/response model. You can have the two models:
Publisher/Subscriber: Where the client declares its interest in some topics and set handlers for messages with that topic, and then the server publish (or push) messages whenever it sees fit.
Request/response: Where the client sends a message with a requestID (or correlationId), and listen for a single response for that requestId.
Still, you can have both if you want, and use REST for getting data, and WebSocket for getting updates.
In server side, you may need to use Socket.io or whatever server side framework in order to have a backend with WebSocket support.
As noted in the answer in your linked post, Angular does not currently have built-in support for Websockets. So, you would need to directly use the Websockets API, or use an additional library like Socket.io.
However, to answer your question of if you should use both a REST api and Websockets in a single Angular application, there is no reason you can't have both standard XmlHttpRequest requests for interacting with a REST api, using $http or another data layer library such as BreezeJS, for certain functionality included in various parts of the application and also use Wesockets for another part (e.g. real time chat).
Angular is designed to assist with handling this type of scenario. A typical solution to would be to create one or more controllers to handle the application functionality and update your page and then creating separate Services or Factories that encapsulate the data management of each of your data end points (i.e. the REST api and the realtime chat server), which are then injected into the Controllers.
There is a great deal of information available on using angular services/factories for managing data connections. If you're looking for a resource to help guide you on how to build an Angular application and where data services would fit in, I would recommend checking out John Papa's AngularJS Styleguide, which includes a section on Data Services.
For more information about factories and services, you can check out AngularJS : When to use service instead of factory

Categories