Write into database before redirecting - javascript

There's a button, when it is clicked(html onclick) it redirects to another page. In javascript there's a function, that writes some new values into a database table when this button is clicked. My problem is: redirecting takes place before the data is written into the database, so on the new page i still have the old values. Is there an easy way to invert these steps(redirecting, writing into database)? Thanks for your advise

just move the redirection into the callback of an ajax call, say you have
Save data
<script type="text/javascript">
$(document).ready(function() {
$("#savedata").click(function() {
$.post('/savemydata/', { mydata: 'data' }, function(data) {
window.location.href = '/newpage/'
});
return false;
});
});
</script>
if the button actually submits the form, then you might probably want to hide the button instead and then just trigger it after your post simply by adding:
$("#buttonID").trigger('click');

Use ajax to write the data, then in the callback of the ajax throw in the redirect. This will ensure that the redirect does not happen until the information is written to the database. It would help to see some of your code to make a better answer. Also, this would most likely be best done with jQuery if you are new to ajax.

Move the code that redirects to a new page into the callback for your ajax save request.
Something like this:
$.post('/savemydata/', { my: 'data' }, function(data) {
//the Ajax post has been completed successfully, so now we redirect
window.location.href = '/newpage/'
});

That depends on how you are writing to the database. But the usual and recommended way to transport data to your server when loading a new page is the use of URL parameters. If you use something like
<form action="/next.php" method="POST">
<input type="hidden" name="data" value="values" />
<button type="submit" value="Next Page" />
</form>
or
Next Page
// also simply usable with
window.location = "/next.php?data=values";
you can be sure that
the data reaches the server,
can be processed (written to the database) before
the requested page is returned.
You could also make use of cookies. Just write your data values into document.cookie, and they will be transported to the server with the same request that asks for the new page.

Related

Include two https requests in Node js via the same html button

I have an HTML button that sends a POST request and would like to do some kind of verification before making the request here.
The verification involves a GET request, where I make sure that a certain table contains a certain value or not. After that, if the condition is valid I make the POST request else I use the value I fetched from the GET request.
Even though this sounds basic I'm not sure how to do this in Nodejs.
Here is how code is organized now,
Her is the HTML button:
<form action="/generate_survey" method="POST" id="gen_survey">
<button type="submit" class="btn btn-primary my-3">Get Survey Link</button>
</form>
And I have a router.js that includes all the routes:
route.get('/generate_survey', controller.test)
then here in the controller.js, I have the db and other call functions.
So here is the test function where I want to make the request
exports.test = (req, res)=>{
.....
}
Should I put the GET request results in a variable and then depending on that I make the POST request?
If so I'd like to see an example of how to something similar in Nodejs
Thanks
In Angular we can do this way. so hope same applies to Nodejs as well. adding form method just for ref. you can check the actual one.
form onsubmit="do_something()"
do_something(): boolean{
// do get operation here
return true; // submit the form
return false; // don't submit the form
}

Can I do DOM manipulation within an Express POST request?

I'm working with basic HTML/CSS frontend, I currently have a landing page with a form on it that sends some data to a database. When the request is done, it is expecting some sort of response. In this case, I am re-rendering the page, however, I want to replace the form with some sort of a thank you message, something so the user knows that it has sent correctly. I have tried the solution of simply having a separate near identical page with the form removed and replaced, however, this kind of code cloning seems like an inefficient way to do it. Is there a way I could do some sort of front-end DOM manipulation from within my node app instead?
Generally, if you want to manipulate how the DOM looks server side you would need to render your entire page server side and then send it to the front end.
If you want to simply manipulate the DOM after a request is received on the front end, whic is a pretty regular practice for this type of stuff; regardless of the back end language(s) used, you can:
Submit form
Let user know form is submitting to server (Best practice for UX)
Once you receive your response, manipulate the DOM however you would like
For this use case, I've taken advantage of the async/await syntactical pattern which will allow you to wait for a response while not ending up in a nested callback pattern.
The attached snipped will fake a request to the server through a set timeout value, and echo what you put into the form back to the page. It's on a three second delay and uses AJAX to make the request.
*You can simplify this code by removing some logging and comments, but I've made it more verbose than necessary for learning purposes.
**I've purposely put the submit button outside of the form element so that it does not auto-post on submit. If you want to submit this way, you can use event.preventDefault() within the function, catch the event before it bubbles, and do this instead. Either way will work fine.
async function getDataAsync0(data) {
return new Promise(async (res) => {
setTimeout(()=>{
res(data);
},3000)
});
}
$(`#submitButton`).click(async () => {
// Create div to display what's going on
let statusAreaElement = $(`#statusArea`);
// Submit Event
statusAreaElement.html(`Submitted... Waiting for response...`);
// Cache input element
let inputElement = $(`#input01`);
// Cache form element
let formWrapperElement = $(`#formWrapper`);
// Cache success message div
let successMessageElement = $(`#successMessage`);
// Get value
let value = inputElement.val();
// Send value, await response;
let response = await getDataAsync0(value);
statusAreaElement.html(`Response returned -> ${response}`)
// Clear input element
inputElement.val(``);
// Hide form, show success message
formWrapperElement.hide();
successMessageElement.show();
})
#statusArea {
position: absolute;
left: 0;
bottom: 0;
}
#successMessage {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formWrapper">
<form>
<label for="input01">Form Input</label>
<input id="input01" type="text">
</form>
<button id="submitButton">
Submit Form
</button>
</div>
<div id="successMessage">
Thanks for your submission!
</div>
<div id="statusArea">
</div>
JSFiddle offers an echo service so I've also written the same code into a fiddle so you can see it actually call the server and echo back the response.
Here is that link:
https://jsfiddle.net/stickmanray/ug3mvjq0/37/
This code pattern should be all you need for what you are trying to do. Again, this request is also over AJAX so the DOM does not need to completely reload; if you are actually going to be making a regular post (without AJAX) to the server and then reload the page afterwards, you can do the same thing - or simply construct the new page you wanted to send to them server side and then redirect them from there.
I hope this helps!
Can I do DOM manipulation within an Express POST request?
No. The server builds up a response (a big chunk of html), that gets sent to the client which parses it and builds up the DOM. You cannot directly work with that from the server.
However you can:
1) Modify the html the server sends (have a look at express.render)
2) Run a clientide script that opens a connection to the server (websockets, AJAX) and then mutate the DOM there when the server sends something.

Conceal URL in javascript code ( URL generated by PHP )

I am looking for a solution to the following:
I have a piece of JS code, that performs a redirection to a URL that is constructed with PHP, and that redirection is only done when the user presses a button on a confirmation dialog.
The code is, as follows:
function one() {
window.location.replace("<?php
if($new_redir == "1") {
echo "$new_second_redirect_URL/?token=$hash";
}
else {
echo "$second_redirect_URL/?token=$hash";
}
?>");
}
It works perfectly fine. What I wanna do is conceal the URL that is displayed in the source code when a user opens the page.
What would be the best way to do that?
You're thinking too much into this to be honest.
If they want to avoid the confirmation screen and get the URL from the source, there's not really much you could do.
The best really is possibly performing an AJAX request on confirmation and getting a CSRF token based URL from the response and using that, but that could end up being overkill as well.
You could also make it into an actual <form></form> form with a few hidden fields (again, such as a CSRF token), and perform the post validation onclick. If it a success - redirect them.
UPDATE:
Use robots.txt to stop bots
Build the QS with JS to stop most bots, something like:
var csrftoken='XJIWHEOU324uipHFOFUHR';
var url="http://url.com/page.php?token=";
url=url+csrftoken;
What you could also do, is something like us actually, although for your use case it could be too much.
Log every single page load into the DB, and check if if they're a first time visitor to the page after confirmation.
AJAX call (jQuery example):
$.post( "url_to_backend_page_to_get_url", {hasSubmittedForm:"true"}, function( data ) {
window.location.href = data;
});

Pass Dynamic Javascript Variable to Django/Python

I have looked at a number of answers and other websites, but none answer my specific question. I have a webpage with "+" and "-" buttons, which should increment a variable called "pieFact". This variable must be updated dynamically without having to refresh the page. It should then be passed to my Django view each time the value is changed. This will be used to update the size of pie charts in a web map. I have the following:
<button type="button" id=bttnMinus onclick="pieFact=pieFact*0.9">-</button>
<button type="button" id=bttnPlus onclick="pieFact=pieFact*1.1">+</button></td>
<script type="text.javascript">
var pieFact=0;
</script>
How can I pass the value of "pieFact" to Django? Based on my limited knowledge, I think I may have to use AJAX post/get.
In order to keep from refreshing the page, yes, you will need AJAX. I usually don't like to suggest libraries too much in answers, however, in the interest of being easily cross-browser compatible, I would suggest the use of jQuery.
With jQuery it would be as simple as
Inside of your django template
<html>
...
<head>
<script>
var URL = "{% url 'my_view_that_updates_pieFact' %}";
</script>
</head>
...
Later on...
You'll need to either POST or GET the data to the server via AJAX. To be more RESTful, whenever I need to send data to the server I use POST. jQuery provides the $.post() convenience function to AJAX data to a url via POST. The three parameters are the URL, the data to send (as a JavaScript object; think python dictionaries if you're not too familiar with JavaScript), and a callback function once the server sends back a response.
<script>
function updatePieFact(){
var data = {'pieFact': pieFact};
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
The .click() functions are basically the same thing as specifying onlick in the html attribute. Both click events update pieFact as you would expect and then call updatePieFact() to send the value of pieFact to the server.
$(document).ready(function(){
$('#bttnMinus').click(function(){
pieFact *= 0.9;
updatePieFact();
});
$('#bttnPlus').click(function(){
pieFact *= 1.1;
updatePieFact();
});
});
</script>
In views.py
Since I've used the $.post() function in the JavaScript, the request that Django is going to receive is going to have a method of "POST", so I check to make sure that the method is indeed POST (this means that if someone visits the URL for this view with something like a GET request, they won't update anything). Once I see that the request is, in fact, a POST, I check to see if the key 'pieFact' is in the dict request.POST.
Remember when I set the variable data in the javascript to {'pieFact': pieFact}? That javascript just becomes the request.POST python dictionary. So, if in the javascript I had instead used var data = {'hello': pieFact};, then I would be checking if 'hello' in request.POST instead. Once I see that pieFact is in the request.POST dictionary, I can get its value and then do something with it. If everything is successful, I return an HttpResponse with the string 'success'. This correlates with the check in javascript: if(response === 'success').
def my_view_that_updates_pieFact(request):
if request.method == 'POST':
if 'pieFact' in request.POST:
pieFact = request.POST['pieFact']
# doSomething with pieFact here...
return HttpResponse('success') # if everything is OK
# nothing went well
return HttpRepsonse('FAIL!!!!!')
Hopefully that will get you pointed in the right direction.

Alternate method for dojo.xhrGet() method

I am new to Dojo Framework.I created one button using dojo constructor and dojo.connect onclick event function i written url and load functions.This url navigating servlet and get the response back.
but i don't want response back i want to send request only.
how to do this..anyone help me.
thanks in advance.
are you looking to navigate to another page? if so, you can use window.location.href or other approaches to achieve that. See the foll url for other approaches:
JavaScript: Navigate to a new URL without replacing the current page in the history (not window.location)
if you do not want to navigate but just send some data to the server (and dont care about the response), you can just write an empty function for the callback
var deferred = dojo.xhrGet( {
url : "xxx",
load: function(data) {
//ignore
}
});
});
However, it is recommended to always check the response to ensure there were no errors on the server side.
You could also use dojo.xhrPost to submit your form

Categories