How to receive data from another server (like push notification) - javascript

When a user scans QR code in our web page and makes purchase with it (using a 3rd party application), I want to hide that QR code and process the purchase.
I got an API to check whether the transaction was successful or not. My first thought was sending a request to that API every 2 seconds to check the transaction (terrible idea?). But they told us to create something called a "hook" and they would subscribe to it. What's that? How should I implement that?

Hook may generally mean webhook, here is the wikipedia description.
Webhooks are "user-defined HTTP callbacks". They are usually triggered
by some event, such as pushing code to a repository or a comment being
posted to a blog. When that event occurs, the source site makes an
HTTP request to the URI configured for the webhook.
Hook/Webhook
Think a hook as an endpoint, where a user can notify you / giving you information.
The way it work is like a user accessing a url and sending params
your-url.com/hook?order_id=123&status=complete
Warning: Example code, generally a good hook should provide authentication method.
That way your server can interpret that information as
order with id 123 has been completed
That was a basic implementation.
Other easier analogy is:
a user accessing a url and input a form and press submit. To which url the data is sent, that url can also be called hook.

Basically they are telling you to implement a service that they would call when a transaction ocurred successfully, instead of you going to them.

Related

Get ajax call progress status in front end

I have a web page which allows users to upload and process specific files. After an user uploads some files, after clicking the 'Process' button an ajax call is being sent to a backend service. In the beforeSend function there is an overlay applied to the screen and a spinner is displayed. When the success function is triggered, then the overlay is removed and a toast notification is being shown like 'Files were processed!'
My goal is to somehow show a progress status for each file based on specific checkpoints in the backend service.
Let's say that the backend service when called does following tasks: parse file, map to specific format, send data to database A.... and in the end it sends back http status 200 and a JSON like
{
"status":"Success",
"message": "File X was processed"
}
Now what I want is that instead of just getting an overlay and disabling the whole page until the success event is triggered, to have a progress bar which is updated for each file based on the exact step where the backend has reached.
For instance, for file A, I would like to see below transitions: 5 % Parsing file, 10 % Mapping file...90% sending data to database, 100% processed.
Is this somehow achievable?
There are few points that you need to look into.
Usually in production code, we need to have timeouts. If you are making an ajax call to the backend API, there will be a timeout associated with that api call. Suppose if the timeout is more than 2 mins, then it will send you a 504 Gateway timeout error.
To overcome this and to implement the functionality which you want, you can have any DB(lets consider SQL server). In your SQL server, make a table:
Process_Table
With schema:
Process_id( Will store the process id/name )
Percentage( Will store the percentage )
At_step ( Parsing, Mapping, Sending to DB etc)
Using Javascript(Or any framework of your choice), use setInterval(), to make check_process() api calls. For check_proceess, you can pass in the process_id, and check against the db. For interval, you can set it to 5 seconds. So that every 5 seconds the call is made.
You can read the response of those API calls and do your processing.
An HTTP request consists of a request and a response. There's no direct way to get status updates beyond the onprogress event which would let you see how much data has been transferred. This is useful for determining how much of the data has been sent to the server, but not so much for how far the server has got with working with that data.
You could store progress in a database and poll a webservice to read the most recent status.
You could also have the server push updates to the client using Websockets for bi-directional communication.
A rough outline for such a system might look like:
Open a Websocket
Send files with Ajax
Get server generated ID back in HTTP response
Pay attention to messages coming over the Websocket that mention that ID
You could also look at doing the whole thing over Websockets (i.e. upload the files that way too). A quick Google search turns up this library for uploading files to a Websocket service hosted on Node.js.

Ajax Post request get converted to GET [duplicate]

I am having a very hard time understanding the exact process of "post/redirect/get".
I have combed through this site and the web for several hours and cannot find anything other than "here's the concept".
How to understand the post/redirect/get pattern?
Wikipedia explains this so well!
The Problem
The Solution
As you may know from your research, POST-redirect-GET looks like this:
The client gets a page with a form.
The form POSTs to the server.
The server performs the action, and then redirects to another page.
The client follows the redirect.
For example, say we have this structure of the website:
/posts (shows a list of posts and a link to "add post")
/<id> (view a particular post)
/create (if requested with the GET method, returns a form posting to itself; if it's a POST request, creates the post and redirects to the /<id> endpoint)
/posts itself isn't really relevant to this particular pattern, so I'll leave it out.
/posts/<id> might be implemented like this:
Find the post with that ID in the database.
Render a template with the content of that post.
/posts/create might be implemented like this:
If the request is a GET request:
Show an empty form with the target set to itself and the method set to POST.
If the request is a POST request:
Validate the fields.
If there are invalid fields, show the form again with errors indicated.
Otherwise, if all fields are valid:
Add the post to the database.
Redirect to /posts/<id> (where <id> is returned from the call to the database)
I'll try explaining it. Maybe the different perspective does the trick for you.
With PRG the browser ends up making two requests. The first request is a POST request and is typically used to modify data. The server responds with a Location header in the response and no HTML in the body. This causes the browser to be redirected to a new URL. The browser then makes a GET request to the new URL which responds with HTML content which the browser renders.
I'll try to explain why PRG should be used. The GET method is never supposed to modify data. When a user clicks a link the browser or proxy server may return a cached response and not send the request to the server; this means the data wasn't modified when you wanted it to be modified. Also, a POST request shouldn't be used to return data because if the user wants to just get a fresh copy of the data they're forced to re-execute the request which will make the server modify the data again. This is why the browser will give you that vague dialog asking you if you are sure you want to re-send the request and possibly modify data a second time or send an e-mail a second time.
PRG is a combination of POST and GET that uses each for what they are intended to be used for.
Just so people can see a code example (this is using express):
app.post('/data', function(req, res) {
data = req.body; //do stuff with data
res.redirect('public/db.html');
});
So to clarify, it instantly refreshes the webpage and so on refresh of that webpage (e.g. if you updated an element on it) it won't repost the form data.
My code used to look like this:
app.post('/data', function(req, res) {
data = req.body;
res.sendFile('public/db.html');
});
So here the response is sending the html file at the /data address. So in the address bar, after pressing the submit button it would say for me: localhost:8080/data.
But this means that on refresh of that page, if you have just submitted the form, it will submit it again. And you don't want the same form submitted twice in your database. So redirecting it to the webpage (res.redirect) instead of sending the file (res.sendFile) , stops the resubmission of that form.
It is all a matter of concept, there is no much more to understand :
POST is for the client to send data to the server
GET is for the client to request data from the server
So, conceptually, there is no sense for the server to answer with a resource data on a POST request, that's why there is a redirection to the (usually) same resource that has been created/updated. So, if POST is successful, the server opiniates that the client would want to fetch the fresh data, thus informing it to make a GET on it.

Should I use an API for this simple event (Express JS)

I havebeen having trouble with backend for a while now and Express JS has made it especially hard. However, I think I am to blame, because I've been going at with the approach that it was an MVC framework generator or maybe it was a framework that helps with authentication. But if I am correct, Express JS should reflect a RESTful API for everything. Not just for user sign up (POST) and loggin in (GET).
This is where I am kinda need clarification. From now on, is it best practice to always use RESTful API when interacting with a database? A real issue I had was with a user table and a likes table.
If a user clicks a like button on a photo, I want to do something like:
INSERT INTO likes (user_id, photo_url) VALUES (current_user, url);
What would the approach be to do this? How do I tell the like button to refer to the API? It's not like a signup form, where we give them names. Or do I just go into the Express file and start defining routes?
Yes, you create an express route for each ajax call that you wish the client to be able to make.
Here's the general sequence of events for a Like button on a photo:
User logs in. That creates some sort of state in the cookie that identifies the user (either an ID or more likely a server-side session).
User presses Like button on a photo.
Javascript attached to the Like button in the browser, gets the current photo ID and makes an Ajax call for "likePhoto" with the current photo ID as a parameter for the Ajax call.
The Ajax call hits an Express route that you have previously set up to handle this Ajax call.
If there is no logged in user session associated with this request, then the request is probably denied (probably returns some error code associated with unauthorized).
The Express route uses the cookie to identify the user making the request so it now has the photo ID and the user so it can make the database call to add the Like to the DB.
After the DB operation completes, the ajax call can return a 200 status and whatever response is appropriate.

How to receive Brain Tree payment_method_nonce without a form post back?

I am new to Brain Tree. I want to accept payments on my web site using Brain Tree. On client side I use javascript and on the server side C#. I use their drop in form in order to collect card information. All the examples I saw on Brain Tree developer side instructs me to do a form submission in order to receive payment_method_nonce on the server. In my web site I handle interactions through callbacks in order to avoid full page refresh. They let me define a callback method in the setup for receiving payment_method_nonce, but is there a way to initiate call to brain tree server through their client side javascript api in order to request payment_method_nonce by avoiding form postback?
I work as a developer for Braintree. There are global configurations that can be used with the Drop-in integration to do this.
The onPaymentMethodReceived callback halts the form submission after the payment method is tokenized. You can use it to capture the payment method nonce and insert your own code to do what you want in place of the form submission.
Add the callback to your global setup like this:
braintree.setup(clientTokenFromServer, "dropin", {
container: "checkout",
onPaymentMethodReceived: function (obj) {
// Insert your code here to capture and use the payment method nonce
// console.log(obj.nonce);
}
});
See more details about the onPaymentMethodReceived callback and the object it returns here. Hope that helps!

passing arguments to python function by javascript

Since mostly a backend guy, I am not sure how can I achieve the following since it
requires some interaction with the browser.
So, I have a the following things so far.
A communication protocol where server is in python and client is in javascript code.
Ultimately, I want my data to reach to that javascript code.
Now, this data is being captured from browser.
As a practice.. what I am trying to do is.. have two radio buttons on my browser and a submit button
*radio A
*radio B
* Submit
Now, when the user presses submit, I somehow want to create a query "user submitted: A (or B)" and this query i am able to capture on python script.
I am at lost on how to do this.
My guess is that "submit" invokes a python script.
But what if my python server is always on .. how do i parse that response from the click of browser to this python server?
This is the way it usually works:
Client (browser) visits webpage and initiates request to server
Server (in your case, Python) handles request and writes HTML response, including the radio-button form
Client fills out form and hits Submit, triggering another request to the server
Server handles the second request and writes another response (e.g. "Purchase successful", "message posted", etc.).
Note that the second request is a brand-new request. You may want some way of linking the first request to the second one unless the second request is anonymous. Some frameworks will do that for you, but if you are making the server from the ground up you'll want some kind of session mechanism to keep track of state.
To get the client to make the second request, the simplest is to add appropriate action and method attributes to the form element in your HTML. action specifies the URL to access for the form request, and method is either GET or POST. (More advanced usage, e.g. on this site, typically uses AJAX to make the submissions instead).

Categories