Form submission without blank data - javascript

I have a form in at the footer section of my website, it email me basic user inputs and the current page url. Here is its layout
<form action="" id="myform" method="post">
<input name="name" type="text" class="transparent-white-border-input" placeholder="Your Name">
<input name="email" type="text" class="transparent-white-border-input" placeholder="Email Address">
<textarea name="enquiry" class="transparent-white-border-input" rows="5" placeholder="Enquiry or Project Details...."></textarea>
<input name="from_page" type="hidden" value="<?=$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]?>">
<div class="send-btn">Send</div>
</form>
following is my ajax submission and javascript validation
<script>
$('.send-btn').click(function(){
if(validateForm()){
$.ajax({
url: "/ajax-request.php?function=footer_contact_form",
type: "post",
data: $("#myform").serialize(),
success: function() {
$(".emocean-contact-form .section-container").html('<h1 style="color: #fff; text-align:center;">Thank you for contacting us, we will get back to you shortly.</h1>');
}
});
}
else{
alert("Please fill in all fields in blue.");
}
})
function validateForm(){
a=document.forms["myform"]["name"];
a_regex=/\S/;
d=document.forms["myform"]["email"];
d_regex=/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //stackoverflow standard
e=document.forms["myform"]["enquiry"];
e_regex= /\S/;
valid = true;
$("#myform input").css("backgroundColor", "");
$("#myform textarea").css("backgroundColor", "");
function check (origin, regex){
if (!regex.test(origin.value)){
origin.style.backgroundColor="blue";
valid = false;
}
}
check(a, a_regex);
check(d, d_regex);
check(e, e_regex);
return valid;
}
</script>
Here comes the problem. I tested in different devices and different browsers but everything works fine. But when it goes live sometimes it emails me with proper information just like in the test, but sometimes it sends me an email with all post data blanks, even $_post["from_page"] is blank. Don't know how this happened. I tried to submit this form in browser console to bypass the validation, while most fields are blank $_post["from_page"] still has value.
Also it didn't look like spam robots things since the blank emails are now coming quite often and they are all in random time. As mentioned before, some emails are not blank. Anyone with any idea what could possibly the problem be?
This post might or might not be relevant.

Related

Javascript XMLHttpRequest and Jquery $.ajax both are returning the current page HTML code

The problem
Hello i want to start off hoping all of y'all are having a fantastic day! I'm having a really weird problem that i have never came across before. I have a bootstrap navigation form with two fields, an input for a email and a field for the password.
When the user submits the form it calls to an AddEventListener which is waiting for a click of the login button. and after that is called it validates(Server Side Validation) the form of the entered data. After both the email_validated and password_validated is both equal to true it calls to a function called checkLogin(email, password){email = entered email in field, password = entered password in field}. In the checkLogin function it called to a JQuery $.ajax({}) call which sends the email and password field to a php document located in /scripts/checkLogin.php. However instead of it returning "Hello"(For testing purposes) is returns the entire HTML code for the current page(As shown above)
JQuery $.ajax({}) code
Here i have the code for the $.ajax({}) call.
Console
I'm not getting any errors in the console except for the XHR finished loading: POST
Other Pictures
Here are some other pictures that i am including to hopefully give yall a better idea of the structure.
Note
I just want to add that i have checked Stackoverflow for similar problems and other people have had this problem but they solutions did not work on my code. I have also tried just using a regular XMLHttpRequest and the same problem occurred, i'm honestly not sure what is wrong with the code for i have never had this problem before. Thank you for taking the time to read this i appreciate any help that i can get with solving this. I'm not the best with $.ajax({}) or XMLHttpRequest and im willing to make any changed to the code to try to get this to work. Below is my code for the entire javascript validation(server side).
Code
<form class="form-inline my-2 my-lg-0" method="POST">
<input class="form-control mr-sm-2 nav-login" type="text" autocomplete="off" placeholder="Email" name="email" value="trest#gmail.com" id="email">
<input type="password" name="password" autocomplete="off" class="form-control nav-login mr-sm-2" placeholder="Password" value="password" name="password" id="password">
<button class="btn btn-success my-2 my-sm-0 nr" type="button" name="login_button" id="login_button">Login <i class="fas fa-sign-in-alt"></i></button>
</form>
<script>
document.getElementById('login_button').addEventListener('click', (e) => {
e.preventDefault();
// const email_regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let email_validated = true;
let password_validated = true;
let email = document.getElementById('email');
let password = document.getElementById('password');
// let email_length = email.value.length;
// let password_length = password.value.length;
//
//
// if(!email_length){
// email.classList.add('is-invalid');
// }else{
// if(!email_regex.test(email.value)){
// email.classList.add('is-invalid');
// }else{
// email.classList.remove('is-invalid');
// email.classList.add('is-valid');
// email_validated = true;
//
// }
// }
// if(!password_length){
// password.classList.add('is-invalid');
// }else{
// password.classList.remove('is-invalid');
// password.classList.add('is-valid');
// password_validated = true;
// }
if(email_validated === true && password_validated === true){
checkLogin(email.value, password.value);
}
});
function checkLogin(email, password){
$.ajax({
type: "POST",
url: '/scripts/checkLogin.php',
data: {
'email': email,
'password': password
},
contentType: "application/json; charset=utf-8",
success: (result) => {
alert(result);
}
});
}
</script>
Links to the other StackOverFlow question
ajax returns the html code of current page instead of json
I was the way my server was configured with xammp as t.niese said.

Prompt recently entered values for forms without getting submitted and not ajax posting to any urls

I am running a simple Embedded web-server where a form needs to be filled and the data can be submitted in 3 different ways for a Truck weighing operation. As i am having 3 different buttons to submit the data through an ajax call to a lua webserver i don't want the form gets submitted in default way.
<form id="formTruck" class="form-group">
<label class="form-label" for="reg-num">Rego:</label>
<input class="form-input" type="text" id="rego">
<label class="form-label" for="product">Product:</label>
<input class="form-input" type="text" id="product">
<label class="form-label" for="valuePT">Preset Tare</label>
<input class="form-input" type="text" id="valuePT">
<input id="dump-submit" style="display:none" value="Submit_Dump" type="submit">
</form>
<div id="weighInOutGroup">
<button id="weighIn" onclick="weigh(this.id);">WEIGH IN</button>
<button id="weighOut" onclick="weigh(this.id);">WEIGH OUT</button>
<button id="weighInPt" onclick="weigh(this.id);">WEIGH IN (PT)</button>
</div>
I have JS function to do the ajax request depends on the button clicked
function weigh(type) {
var weighData = {};
if (type == "weighIn") {
$.ajax({
//ajax request
},
});
} else if (type == "weighInPt") {
//ajax request
} else if (type == "weighOut") {
//ajax
}
};
Also i have used following jquery function to prevent pressing enter navigating to default action
$("#formTruck").submit(function(e){
e.preventDefault();
console.log("weighIn submit prevented")
});
but by doing this i couldn't get the recent inputs prompted on text input fields, as the form is not actually submitted in default action.
Can anyone suggest me a way to achieve this without doing any posts or navigating to any pages?
i don't understand why you use 3 send buttons, use instead a radio buttons, in the jquery submit add your if's and for catch the form data use $("#formTruck").serialize()
$("#formTruck").submit(function(e){
console.log("weighIn submit prevented");
let data = $("#formTruck").serialize() ;
if ($("#rdWeighIn").prop("checked")) {
$.ajax({ data: data, ...
} else if ($("#rdWeighOut").prop("checked")) {
$.ajax({ data: data, ...
} else if ($("#rdWeighInPt").prop("checked")) {
$.ajax({ data: data, ...
} else {
//
}
return false;
});

Why won't this script load?

I have a contact us form:
<form id="contactus" name="contactus" action="html_form_send1.php" method="post">
<label for="name">Name:</label><br />
<input type="text" id="name" name="name" maxlength="50" size="59" autofocus required/><br /><br />
<label for="email">E-Mail Address:</label><br />
<input type="email" id="email" name="email" maxlength="50" size="59" required/><br /><br />
<label for="question">Question:</label><br />
<textarea id="question" name="question" maxlength="1000" cols="50" rows="6" required></textarea><br /><br />
<input class="c1_scButton" type="submit" id="submit" name="submit" value="Send" />
</form>
I want it to call my mail PHP script using this AJAX code:
var msg = "";
name = $("#name").val();
email = $("#email").val();
question = $("#question").val();
//validation phase
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([az]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
function validate(e) {
if (name == "") {
msg = " valid name";
}
if (!isValidEmailAddress(email)) {
msg = msg + " valid email address";
}
if (question == "") {
msg = msg + " valid question or comment";
}
}
// on submit, Validate then post to PHP mailer script
$(function() {
$("#contactus").on('submit', function(e) {
e.preventDefault();
validate(e);
if msg != "" {
e.preventDefault();
$("#alert").html "Please enter a" + msg;
} else {
$.post('/html_form_send1.php', $(this).serialize(), function(data) {
$('#alert').css(color: "black")
$('#alert').html("<h2>Thank you for contacting us!</h2>")
.append("<p>We will be in touch soon.</p>");
}).error(function() {
$('#alert').css(color: "red")
$('#alert').html("<h2>Something went wrong. Your Question was not submitted. /n</h2>").append("<p>Please try again later or email us at <a href=href="
mailto: support# allegroaffiliates.com ? Subject = Contact Us Form " target="
_top ">support#allegroaffiliates.com.</a> </p>");
});
};
});
});
The script is called at the bottom of the HTML page after another script, but it isn't loading. I suspect that it is due to a code error but I can't find the error. Can anybody give me an idea why it wont load?
Side note: I do know that HTML5 will validate the script, but I have the validation in place for when HTML5 is not available.
Thank you for your help.
A few troubleshooting suggestions:
(1) When specifying the ajax processor file, either this $.post('html_form_send1.php' or this $.post('./html_form_send1.php' but not this $.post('/html_form_send1.php'
(2) Instead of using the shortcut code $.post(), use the full form of the method until you are pretty good at it:
var varvalue = $('#first_name').val();
var nutherval = $('#last_name').val();
$.ajax({
type: 'post',
url: 'your_secondary_file.php',
data: 'varname=' +varvalue+ '&lname=' +nutherval,
success: function(d){
if (d.length) alert(d);
}
});
(3) Disable validation routine until the rest is working, then work on that when you know everything else is working correctly
(4) Change your ajax processor file html_form_send1.php to just echo back a response to make sure you've got the AJAX working. Then, once you get the response, change it to echo back the variable you are sending. Then build it into the final desired product. But initially, something dead simple, like this:
your_secondary_file.php:
<?php
$first_name = $_POST['varname'];
$last_name = $_POST['lname'];
echo 'Received: ' .$first_name .' '. $last_name;
die();
(5) Instead of using .serialize(), initially just grab one or two field values manually and get that working first. Note that .serialize() produces JSON data, while the simpler method is straight posted values, as in sample code in this answer. Get it working first, then optimize.
(6) Note that the dataType: parameter in the AJAX code block is for code coming back from the PHP side, not for code going to the PHP side. Also note that the default value is html, so if you aren't sending back a JSON object then just leave that param out.
(7) In my AJAX and PHP code samples above, note the correlation between the javascript variable name, how it is referenced in the AJAX code block, and how it is received on the PHP side. I was very deliberate in the names I chose to allow you to follow the var name => var value pairing all the way through.
For example, the input field with ID first_name is stored in a variable called varvalue (dumb name but intentional). That data is transmitted in the AJAX code block as a variable named varname, and received on the PHP side as $_POST['varname'], and finally stored in PHP as $first_name
Review some simple AJAX examples - copy them to your system and play with them a bit.

onSubmit button won't load location

I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.

Login without clicking submit

so I'm working on this project in which I made an admin area.
While I was working on the login functionality, I wanted a feature like this :-
As soon as the user fills all the entries (Username and Password), the system automatically logs him in.
He doesn't need to hit the submit button.
Similarly, he should be given an error message if the password was incorrect.
How can I achieve this functionality ?
I guess it could be done via jQuery and Ajax, and I have nil knowledge in both of them.
If anybody could guide me in the correct direction, it would be great.
Admin_login.php
<form class="form-horizontal" action="****" method="post" id="login">
<fieldset>
<div class="input-prepend" title="Username" data-rel="tooltip">
<span class="add-on"><i class="icon-user"></i></span><input autofocus class="validate[required] text-input, input-large span10" name="username" id="username" type="text" placeholder="Username"/>
</div>
<div class="clearfix"></div>
<div class="input-prepend" title="Password" data-rel="tooltip">
<span class="add-on"><i class="icon-lock"></i></span><input class="validate[required] text-input, input-large span10" name="password" id="password" type="password" placeholder="password"/>
</div>
<div class="clearfix"></div>
<div class="clearfix"></div>
<p class="center span5">
<button type="submit" class="btn btn-primary">Login</button>
</p>
</fieldset>
</form>
Database Table
Column Name Type
Username VARCHAR
Password VARCHAR
I wrote a git.
This is the link:
https://github.com/FabioSorre/HTML-PHP-AJAX-JQUERY-JS
The steps are these:
Html: No form action (action="") and specify method (Client-side)
Javascript/Jquery: onSubmit function call (Client-side)
Setup JSON callback (Client-side)
Php file (set json_encode, the operations and response(s)) (Server-side)
Show the results (Client-side)
Try using setInterval() that executes a function that checks if both fields are filled every 100MS. Please not this is a dirty hack. I would suggest using better validation methods. Google can help u with that
<script>
function checkCompleteness(){
if($('#username').val()!=='' || $('#password').val()!==''){
//POST DATA HERE MAYBE WITH AJAX OR TRIGER SUBMIT(GOOGLE HOW)
$.post(
'my/endpoint',
{
username:$('#username').val(),
password: $('#password').val()
}, function(response){
// ACT ON RESPONSE STATUS
});
}
//CHECK BOTH FIELDS EVERY 100 MS
setInterval(checkCompleteness(), 100);
</script>
Ok so I'm thinking a little out loud but I hope this guides you to the right direction.
Let's assume that when you are logging in you type a character at maybe 1 sec delay. Let's assume that when the user finishes typing the Password, 2 or 3 seconds will pass. You can make a listener that waits for 2 seconds to pass after the password is typed and then trigger the submit file. Of course you should check that the username is also typed (min characters and not empty exception).
You can make the 2 second listener like this:
Javascript code:
// Trigger a callback function after a given time
var wait = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
// Trigger the submit via AJAX
wait(function(){
// form validation
$.ajax({
url: '/Admin_login.php',
type: 'POST',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {
username: $('#username').val(),
password: $('#password').val()
},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}, 2000); // It submits the form via AJAX after 2 seconds have passed since
// the user typed something in the password field
Admin_login.php
The PHP part is more of a sketch but I hope you understand the idea behind it
<?php
$username = $_POST['username'];
$password = $_PSOT['password'];
//some more forom validation
$loggedin = login($username, $password);
if ($loggedin) {
// Loggedin
}
else {
// renegerate form
}
?>
P.S. Don't forget to avoid SQL injection and escape any special characters, some more information about this topic here: How can I prevent SQL injection in PHP?
Keep me posted and good luck! :)

Categories

Resources