Display HTML content from Django - javascript

Whenever I receive an IPN in this url: https://www.example.com/payment/notifications, I want to display with JavaScript some HTML content to https://www.example.com/stream/notifications/<token>.
The goal is to display some successful donation message to a streamer whose token is user.stream_token. Then he can take that url and configure the alert with OBS.
This token is unique to every "streamer" and I can access it by doing user.stream_token
I manage the IPN from the server like this:
#csrf_exempt
def notifications(request):
jrequest = json.loads(request.body)
if request.method == "POST":
if jrequest['action'] == 'payment.created':
# some code
return HttpResponse(status=200)
I want to run the JS function that displays the html content inside that block of code, because that's when I can confirm that a payment or donation has been approved.
I know that Django is server-side and JS is client-side so I cannot just run a JS function inside there.
Any ideas on how could I implement this in the simplest way possible? I read about WebSockets but the implementation is way too difficult for me to understand.

If you are okay with your user having to send a request to trigger this change in the document, then you don't need a WebSocket. As we talked about last night on your question, you only need a WebSocket in a situation where you want your server to send your user a message without any prompting by the user.
However, if you are okay with the user having to send a request, you are on the right track. You are going to need to use ajax or fetch, etc. to make a request in your js to this view you are creating now. Then, depending on the data in the response from the view, you can render new elements in the document.
I am having a hard time understanding what the user is doing exactly in the frontend, and what you need to show them based on what event. If you can elaborate more we can keep working this out!

Related

Sending variables inside a response node.js, vainilla js

im trying to learn nodejs and vainillajs for web development, making my first project after some months of tutorials, and im in having some very basic doubts, dont know if im conceptually wrong, if someone can point me in te right direcction ill be very grateful!
1-The user access my main page on route:/ receives the corresponding public html/css /JS and have the option to a fills a form, and send a post request with that data to route /validation.
2-on the server side i receive the post request, with the data provide by the user, i make some validations on that data
and here comes the part im very doubtfull
depending on the validation i want to send to the user a response with data containing reasigning values for existing variables inside the public js file sent in first place, (like setting the value of a variable to block, to open a modal, or just adding some innerhtml)
I believe i cannot modified the public js already sent, but i want to know if i can respond with a redirection to route / again, but adding the reasigned variable inside the response.
and is if that the proper way of doing what i im trying to do.
I know i can redirect my user to another totally diferente route, but in principle that is not how i would like it to be.
any help or guiding material about this topic would be greatly appreciated.

Vue js and favorite/like button

I'm wondering how favorite, subscribe or like buttons work.
I don't understand something.
For exemple:
A user like a post with id 243.
A ajax request is sent to the server with the id of the post (243) [here comes back end stuff, the user's favorite list is updated, including that post] and the server sends back a success response.
Now, how I suppose to deal with modifying the like button to actually display that is liked (permanently, including refresh).
How can I achieve that in Vue JS. How things get updated? I don't understand this part.
If the server sends back a successful response you can increment the number that is already there.
This initial number is something you have gotten either through a prop, directly from the server or through an initial AJAX request.
If you want to "permanently" update the amount of likes on your button you have to persist it to a database(or some other storage medium). On you server you could have a route that accepts a post id as an argument and increment that specific user post:
/incrementlike/243
That is where you would make a POST ajax request to. Most of the time in an MVC framework you would have a controller action/method mapped to this route that holds the logic to respond to this call.
If you are interested in the part that happens after you make an AJAX request to the server to increment your like on the backend side, I suggest you read up on routing or MVC structure.
How you would do this is really done on a case by case basis. It really depends on a number of things, for example what your backend does to a post when it is liked.
If you would like a general 'explanation' to the process I attach it below, this is not really Vue specific, but the general idea is the same:
Frontend side:
Modify the local state of you post to set the proper flag, ex. post1.liked = true immediately when it is clicked, before sending the request to the server.
Make sure your GUI represent this change. ex. Base the color of the button on the property 'liked' of each post.
If a failure response it received from the server, notify the user and allow them to 'try again' or something similar.
When refreshing the page, make sure changes are fetched from the server, If you have done the backend part correctly, the modification of the state of the post will be correct in the data you receive from your backend (post1.liked will be true)
Backend side
When the request comes in, modify the state of the post the correct way and make sure that next time the post is fetched, the new state is sent.

Post to another page without redirecting

I am building a movie recommended system. I want when a user login and rate a movie, the rating and movie name as well as user name will post to another page without going to that page automatically, i mean without pressing anything. How can I do that?
You can do that by executing an ajax request (after clicking the vote-button), which sends data (you can define the data to be what you want - rating, movie and user) to a php script that you will have to create.
the php script will read the posted data that the ajax has sent and can insert/update the database.
This way, the user will not be redirected. he won't even notice.
You can achieve this by using some kind of ajax requests triggered by vote event or callback.

How can I go to an html page while passing a hidden parameter using Javascript or jQuery?

Upon completion of an ajax call I would like to direct the user to an html page, but at the same time passing a hidden variable (this variable contains sensitive information and should not show up in the URL).
How can I accomplish this?
window.location.href = 'userpage.html?id=14253';
But with the id remaining invisible? Can I POST the id somehow while sending the user to userpage.html?
You should not be checking user credentials on the client side of your website. Regardless of how the ID is being passed to your script, it can be replicated without you being able to check if the request is valid.
To start being even remotely secure with what information is granted to a user, you need to be checking it via the server side. With every request, ensure the user is authenticated to view such data.
If I were you, I would look into using PHP sessions as the first line of defense for checking if a user is authenticated. Doing so will at least keep the information about a user out of a replicable space that can be viewed by the user.
Look up 'php session login tutorial' on Google and you will find plenty of simple tutorials which should get you on the right track.
Example Tutorial
No matter what, the information you pass along is insecure. You can submit a post request using XMLHttpRequest objects if you'd like (or use a framework/library to make AJAX calls) -- but the user could still spoof the data and get different results.
ID enforcement should be done in the backend. Does the requested ID match the ID of the user signed in? No? Don't show it. etc etc.

Django/JavaScript: passing hidden variables to a page with window.location.href?

Apologies if this question is a bit convoluted.
I want a Django page to display a banner message sometimes. Sometimes the user will arrive via window.location.href, and then I would like the banner to display, with a message determined by the action the user just performed.
Details:
I have a site-wide javascript listener that listens for scanner input (which presents as keyboard input).
When it triggers, using jQuery I return or check out the item, dependent on its state. I do this via an Ajax POST request.
Then I immediately take the user to the item's page on my site. I do this by setting window.location.href to the item's page, inside the response handler of the POST request. The item shows as available or checked out, but I want to show the user another message too...
...I want to show a banner saying 'Item checked out' or 'Item returned'.
The last item is where I'm having problems: how do I 'tell' the item page what message to show, and when to show a message at all? People will also arrive at item pages not via the scanner.
I could set GET parameters (?t=checked_out or ?t=returned) but that feels messy.
I could use cookies but that feels even messier.
If I POST to the item page (which also feels wrong) with a t=checked_out parameter, wouldn't it be good Django practice to then redirect somewhere else, rather than display the page?
Perhaps I'm just too hung up on the last point.
Anyway, the basic question is: How best can I pass hidden variables to a page via window.location.href?
Thanks for your help. I have the feeling there's something fundamental that I've yet to learn here :)
Why do an AJAX request at all for step 2/3?
You asynchronously POST, then redirect.
Can you do a normal POST with info about whatever the javascript did, add some message in your session in the django backend (and have the item view load it), and do a server redirect to the item page?
The django way would definitely be to do it in django sessions.
If you must, your method should be possible anyways:
pass extra bits of information TO django in your ajax post
set your "hidden variabes" to the django session (request.session['myvar'] = 'ajax_posted_stuff')
javascript redirect (but seriously, it would be best to have the server redirect)
pull "hidden variables" from the django session (ajax_posted_stuff = request.session['myvar'])
Example:
def ajax_view(request):
if successful_response():
request.session['show_banner'] = True
return JSON # or whatever you were doing before
def item_view(request):
context = {}
if request.session.get('show_banner'):
context['show_banner'] = request.session.pop('show_banner')
return render_to_response("mytemplate.html", context)
# item.html
{% if show_banner %}
<h1>Banner shown!</h1>
{% endif %}
Why do you think using a cookie would be messy? I'd say go for cookies if you can. You can read cookies from window.document.cookie.
As an alternative to cookies, the cleanest solution could be to use the URL hash:
http://example.com/page#co
You can easily check for the presence of the hash with window.location.hash.

Categories

Resources