Loading HTML response from NodeJS server using AJAX - javascript

I am currently making a login interface that posts user data to a NodeJS server. Here is the code for the form.
<form action="http://127.0.0.1:8080/" method="POST" id="login_form">
<div class="input">
<input class="input-box" id="username" type="text" name="username" placeholder="Username">
</div>
<div class="input">
<input class="input-box" id="password" type="text" name="password" placeholder="Password">
</div>
<input type="submit" class="button blue" value="Login">
</form>
Now the form submission is intercepted by a javascript file that takes the form data and posts it to a NodeJS server using AJAX. The server validates the user login and if successful, returns an HTML page to be loaded using jQuery. Here is the code:
$(document).ready(function(){
$('#login_form').submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $('#login_form').serialize(),
dataType: 'html',
success: function(response) {
$("html").html(response);
}
});
});
});
Now the login form works properly and loads the HTML response, but with one minor issue. Before the final rendered page (with all the css styles and images) is loaded, all the text on the page gets displayed with no formatting, then the final design is displayed. This gives a strange transition between the login form page and the final user portal. Does anyone know why this might be happening and any solutions to fix it?

This is called FOUC (flash of unstyled content).
Here’s an existing answer to avoid it:
https://stackoverflow.com/a/5983338/3044358
Or just google the term. Lots of suggestions.
First thing to try: put your css link tags at the top of the head element

Related

Pausing site until button press Javascript

I am trying to make my website first ask Simple data and than continue loading the page, but I can't figure it out.(so first ask data and than print PRINT THIS AFTER)
this is what I have now:
<html>
<h1>PRINT THIS BEFORE</h1>
<form id="login">
name: <input id="name" type="text">
password: <input id="password" type="password">
<input value="log-in" type="button" onclick="sendIt()">
</form>
<script>
var send = false;
function sendIt() {
send = true;
}
var i = setInterval(function(){
console.log("f")
if(send) {
document.getElementById("login").remove();
clearInterval(i)
}
}, 100);
</script>
<h1>PRINT THIS AFTER</h1>
please help me
-------------EDIT----------------
I decided to use innerHTML to edit the html in a div with the id edit so it wont load the html yet
Code:
<html>
<h1>PRINT THIS BEFORE</h1>
<form id="login">
name: <input id="name" type="text">
password: <input id="password" type="password">
<input value="log-in" type="button" onclick="sendIt()">
</form>
<script>
var send = false;
function sendIt() {
send = true;
}
var i = setInterval(function(){
console.log("f")
if(send) {
document.getElementById("login").remove();
document.getElementById("edit").innerHTML = "<h1>PRINT THIS AFTER</h1>";
clearInterval(i)
}
}, 100);
</script>
<div id="edit">
</div>
I've read the other replies here and your comments. As others here suggested, the easiest way to do this would be to either hide the H1 or put the H1 in a hidden div, and you can then show that div via your "sendIt" function with Javascript if the login was successful. For what it's worth, you can't "pause" a site from loading content. Anything embedded in the HTML is going to load regardless of what Javascript is doing.
If hiding the content is not good enough (maybe for security reasons, you don't want to show someone content unless they are signed in, as hiding it would still let them view the source), there's only two other ways to do this. The first is server side programming. Post to the same page and if the login conditions exist, show the content instead of the login form.
The second method you can use an AJAX request. If the login is successful, you can dynamically load content from another web page on your server that contains the content you want to show. Note, the page you are dynamically loading should have some type of security (like server side programming) that validates if the person is logged in, otherwise you're back in the same hole, same goes for the server side method. If the content or AJAX page isn't validated in some way, they will find a way to view it anyway.
This problem is a little steeper than what you are asking us, but there are plenty of tutorials out there on a simple AJAX request or using server side programming languages like PHP. Now that you have an idea of how to do this, you can start experimenting.
<html>
<h1>PRINT THIS BEFORE</h1>
<form id="login">
name: <input id="name" type="text">
password: <input id="password" type="password">
<input value="log-in" type="button" onclick="sendIt()">
</form>
<script>
var send = false;
function sendIt() {
send = true;
}
var i = setInterval(function(){
console.log("f")
if(send) {
document.getElementById("login").remove();
document.getElementById("h1show").removeAttribute("hidden");
clearInterval(i)
}
}, 100);
</script>
<h1 id="h1show" hidden>PRINT THIS AFTER</h1>
Use hidden attribute on the h1, and then just remove it by :
document.getElementById("h1show").removeAttribute("hidden");
and it will show up.
Your form making submit when you press on button then page refresh is happen and you see your form again.
If you want to make request without page refresh you should return false on submit and have to use AJAX technology.
You can use CSS to show\hide your site content or backend to control your HTML.
If you want that your HTML will not contain a site content, after login make redirect to page with cookie checking or load a site content via AJAX.
get necessary info
login.html
<h1>PRINT THIS BEFORE</h1>
<form id="login" action="data.html">
name: <input id="name" type="text" required>
password: <input id="password" type="password" required>
<button type="bubmit">log in</button>
</form>
if prev page contains required info send to new page
data.html
<h1>PRINT THIS AFTER</h1>

Mobile upload refreshes page and file does not upload

I've asked this question to the admins of Smartjobboard software yet they are so inactive ill ask here...
On mobile phones/Ipads a jobseeker is able to apply to a job with a CV by uploading it and submitting it. However for some reason when a user uploads a CV it will sometimes refresh the page and the CV will not be uploaded..However on desktop the upload never breaks and works flawlessly
I'm pretty sure its something to do with the page speed or/and how the page loads. But to be proactive in getting this fixed and working as it should I thought id ask you genius people for help :)
Anyway the codes... (Posted in pastebin)
Apply_now.php - http://pastebin.com/JasSWTEg
The form for applying :
<form method="post" enctype="multipart/form-data" id="applyForm" action="{$GLOBALS.site_url}/apply-now/">
<input type="hidden" name="is_data_submitted" value="1">
<input type="hidden" name="listing_id" value="{$listing_id}">
<fieldset>
<div class="inputName" style="width:19%">
[[Attach your CV]]:
</div>
<div class="inputField" style="margin-top:7px;">
<input type="file" name="file_tmp" />
</div>
</fieldset>
<input class="button-green" type="submit" value="[[Apply Now]]" onclick="return applySubmit();"/>
</form>
Apply Script :
function applySubmit() {
$("#ApplicationForm").hide();
$("#applyForm").ajaxSubmit(
{
url: $("#applyForm").attr("action"),
type: "POST",
success: function (data)
{
$("#messageBox").html(data);
}
});
return false;
}
I'm unsure if there is a problem within the applying script/php/code it self. I'm working on the pagespeeds now to eliminate render blocking etc etc to see if its causing the issue.
As said in the comments, add a action tag to your html form.

Which is the secured way of scripting registration form?

In many sites, I have seen after clicking on "Sign Up" or "Register" button we are either re-directed to other page where the insertion of our data in database takes place. Like in Facebook, when you click "Sign Up" it goes to the facebook.com/r.php page. I want to create a registration form which when submitted, will be not re-directed but will validate and insert data in database in the same page.
For example, Facebook uses a form such as:
<form id="xyZ" name="abc" method="post" action="r.php">
It redirects us from index.php to r.php.
But I want to use:
<form id="xyZ" name="abc" method="post" action="index.php">
i.e Without redirecting.
Which one is safe?
Redirecting does not effect the security of the website at all in the slightest. I recommend taking a look here about possible authentication solutions you can use for your site.
Whether you authenticate and log them in/register them using index.php or r.php, it doesn't matter in the slightest. Forum systems such as phpbb used to at one time to everything in the index.php file, and depending on the ?page $_GET variable, it would display different things (Like a login form, or a registration form). How you handle it, is entirely up to you, but neither method is more insecure than the others.
Both are safe!
Redirect method, kind of link using which user redirects to another page where they can register
Ajax Method, here you can make calls using Javascript / jQuery which returns you html source, which you can just plug in appropriate place.
Your Page where you need your registration form to be displayed, when user click on sign up link
<div id="ajax-response"></div>
<a id="signup" href="signup.php">SignUp</a>
<script type="text/javascript">
jQuery("#signup").on('click', function(e){
e.preventDefault();
var _context = this;
jQuery.ajax({
url: jQuery(_context).attr('href'),
success: function(response){
jQuery("#ajax-response").html(response);
}
})
})
</script>
and signup.php, will contain the registration form
<form>
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit" />
</form>

Using JavaScript to submit a particular form button

As a college student at QANTM I regularly use its portal system to check information that is relevant to my study. However, the site uses a specific system that makes it impossible to view on small resolutions, such as mobile browsers.
I'm developing a small personal application that should allow me to view the contents of the site in my own formatted view. However, I'm having some issues executing JavaScript to submit credentials.
<form id="userslogin" method="post" action="javascript: saePortal.users.submitLogin();" onsubmit="return false" class="x-hidden">
<input type="text" id="username" name="username" />
<input type="password" id="password" name="password" />
<button type="submit" id="submit" value="Login" class="x-hidden" /></button>
</form>
This is basically the form structure of the portal and I am successfully able to alter the username and password field with my desired contents using
document.forms[0].username.value = 'text';
However I am unable to submit the results. I have done some searching online and it's not a simple matter of submitting the form. It refreshes the page.
document.forms[0].submit();
I've also tried non-standard compliant code such as document.forms[0].submit.click(); and many variants of this, as well as using getElementById with no luck.
The site in question https://portal.qantm.com.au/. I'm unsure if this is a form of protection that's built into the site or if I'm simply using the wrong syntax.
You could use JavaScript FormData-class if your browser supports it.
var fd = new FormData();
fd.append("username", username);
fd.append("password", password);
Then you could post this using jQuery or something.
$.ajax({
url: portalurl,
type: 'POST',
data: fd,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
Change attribute onsubmit="return true" in form tag.

jQuery not sending POST data

So I have a really simple form on a website that's entirely AJAX based for loading its pages. The only way for this form to work would be for it to do some AJAX magic as well, so I set about doing it. I had the form tested so I knew it all worked.
Here's the javascript for my form.
The variable "fullpath" just tells me what page is loaded at the moment, all of the pages are stored in the local "pages" directory.
It serializes the form and sends it to the server, with some debugging alerts.
$(document).ready(function() {
$("#regForm").submit(function(event) {
alert($(this).serialize());
$.post("pages/" + fullpath, $(this).serialize(), function(data){
alert(data);
});
return false;
});
});
Here's the form itself
<form name="input" id="regForm">
<div class="form-field"><label>Username</label> <input type="text" name="username"/></div>
<div class="form-field"><label>Password</label> <input type="password" name="password"/></div>
<div class="form-field"><label>Confirm Password</label> <input type="password" name="password2"/></div>
<div class="form-field"><label>Screen Name</label> <input type="text" name="screenname"/></div>
<div class="form-field"><label>Email Address</label> <input type="text" name="address"/></div>
<div class="form-field"><label>Group</label> <select name="usergroup">
<option value="0">Superuser</option>
<option value="1">Admin</option>
<option value="2">Moderator</option>
<option value="3">Advmember</option>
<option value="4">Member</option>
<option value="5">Guest</option>
</select> <br />
<label>Submit: </label><input type="submit" value="Submit" />
</div>
</form>
And here's some PHP I put at the beginning of the page
print_r($_POST);
So I fill the form with some bogus info, and I press submit. All of the data is displayed with the
alert($(this).serialize());
And then the call is successful and I see the loaded form with my
alert(data);
But, where I ask to print the $_POST array in PHP, this is all I get
Array ()
So jQuery is sending the data, it's getting the page back, but for some reason the POST variables aren't going through. Anyone care to lend a hand?
This works in a Fiddle.
Are you sure that fullpath is defined globally ? I don't see any other possible source of errors in your code.
Edit: I can see the actual problem from your comments: 301 redirects don't work through POST:
If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
You need remove this redirect thing, so "pages/" + fullpath directly points to the PHP script. This could also be a problem with your server configuration.
In case of Apache, you might also want to have a look at this SO question.
I packed your snippets together in an html-file and it worked for me so the problem has to be somewhere else in your code. (source: http://pastebin.com/y4Dfsepv)
You have not specified method="post" in your form. If you do not specify, it becomes method="get" by default. So there is no values in the $_POST, you can print_R($_GET) and you will see values there.
Change the below line from:
<form name="input" id="regForm">
to:
<form name="input" id="regForm" method="post">
Update:
Updating the answer as per the comment. The "pages/" + fullpath in $.post might be pointing to the wrong page, try alerting it and check server response in firebug. Make sure it is pointing to the page you want else use the full path to the php script like below:
$.post("http://localhost/pages/" + fullpath, $(this).serialize(), function(data)
you need to chance your direct link."pages/" + fullpath. That is a problem, ajax can't recognize your link when you post
** Editing because we've learned that there is a 301 Redirect code being returned by the server **
See this: https://mdk.fr/blog/post-data-lost-on-301-moved-permanently.html
301 Redirects lose contents of the POST. So jQuery is sending it along, but the server redirects it to the right location of the script without the POST data. You need to figure out where the right location of the script is and specify that in your jquery call to avoid the redirect.
You don't have method="POST" in your form.

Categories