POST request to MySQL - javascript

I have this next code
<!doctype html>
<html class="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nieuwe gebruiker | Sociale buurt</title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="onzebuurt.css" rel="stylesheet" type="text/css">
<script type="text/javascript" language="javascript">
function formulierValideren() {
if (document.getElementById('Username').value == '' || document.getElementById('Username').value == null)
{
alert ('Gebruikersnaam is verplicht.');
document.getElementById('Username').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord').value == '' || document.getElementById('Wachtwoord').value == null)
{
alert ('Wachtwoord is verplicht.');
document.getElementById('Wachtwoord').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value == '' || document.getElementById('Wachtwoord2').value == null)
{
alert ('Bevestig wachtwoord.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value != document.getElementById('Wachtwoord').value)
{
alert ('Wachtwoorden komen niet overeen.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else
{
$("#bevestig").click(function() {
gebruikerToevoegen();
});
var msg = "Registratie succesvol. Klik op OK om u aan te melden op de site.";
if(confirm(msg)){
setTimeout(function() {window.location.href = "http://webs.hogent.be/kevinbaeyens/"})
}
}
//end if
}//end function
function gebruikerToevoegen() {
var request = new XMLHttpRequest();
request.open("POST", url);
request.onload = function() {
if (request.status == 201){
alert("everything OK!");
} else {
alert("you're wrong");
}
};
}
</script>
</head>
<body class="body2">
<div class="gridContainer clearfix">
<div class="header1">
<center>
Nieuwe gebruiker
</center>
</div>
<div id="formulier2">
<form method="post" name="form" action="">
<p class="labels"><center>Gebruikersnaam *</center></p><input id="Username" type="text" name="Username" placeholder="Gebruikersnaam" size="50">
<p class="labels"><center>Wachtwoord *</center></p><input id="Wachtwoord" type="password" name="Wachtwoord" placeholder="Wachtwoord" size="50">
<p class="labels"><center>Bevestig wachtwoord *</center></p><input id="Wachtwoord2" type="password" name="Bevestig wachtwoord" placeholder="Bevestig wachtwoord" size="50">
<br />
<center><img id="return" name="jsbutton" src="return.png" alt="Terug" /></center>
<br />
<center><input id="bevestig" type="image" src="Bevestig.png" width="200" height="50" border="0" alt="SUBMIT!" onclick="formulierValideren()"></center>
<br />
</form>
</div>
</div>
</body>
</html>
I want to send the data from #Username and #Wachtwoord to my MySQL database.
Please help me please, i'm stuck on this for almost a week now. i'll be so happy if anyone could help me! if i need to give more information, please ask me

first I thought you were looking for a client side solution (which woul be a very bad idea anyway). Jason is right. But if you want something kind of automatic, have a look to smarty php. Though, first you have to learn some basic stuff and a watch very clear example you could find in this video tuto: http://www.youtube.com/watch?v=gvGb5Z0yMFY

1) Why are you using a framework (seems jQuery) and dooing something like this
var request = new XMLHttpRequest();
You may have a look at: http://api.jquery.com/jQuery.ajax/
2) It would recommend, to use e.preventDefault instead of returning false on validation.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
3) What are you doing in your "action"? Or: where is your url pointing to?
as mentioned before: you need some kind of "endpoint" on the serverside:
http://www.springsource.org/
http://www.asp.net/
http://rubyonrails.org/
https://www.djangoproject.com/
http://framework.zend.com/
http://www.catalystframework.org/
http://www.seaside.st/
or whatever

Related

How do we apply Bootstrap classes to JavaScript Error messages and make them stay on the screen when a form submit button is clicked?

I am trying to figure out how to make Javascript error messages be displayed in the DOM and stay there until valid information is added into the form inputs. Right now they appear for a brief moment and then disappear. On top of that, I have to use Bootstrap 5 to stylize the JavaScript Error messages. I've been trying to figure this out all day and I haven't had any luck.
I have my HTML and Javascript down below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Form</title>
<link rel="stylesheet" href="login/login.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<main>
<h1 class="text-primary">Login</h1>
<form id="login_form" name="login_form" method="get">
<div>
<label for="email1">Email:</label>
<input name="email" type="email" autocomplete="email" id="email" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label for="password">Password:</label>
<input name="password" type="password" autocomplete="password" id="password" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label> </label>
<button type="submit" class="btn btn-primary" id="login">Login
</div>
</form>
</main>
</main>
<script defer src="login/login.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
const $ = selector => document.querySelector(selector);
document.addEventListener("DOMContentLoaded", () => {
$("#login").addEventListener("click", () => {
// get values user entered in textboxes
const email = $("#email");
const password = $("#password");
// create a Boolean variable to keep track of invalid entries
let isValid = true;
// check user entries - add text to error message if invalid
if (email.value == "" || password.value == "") {
email.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
password.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
return false;
} else {
email.nextElementSibling.textContent = "";
password.nextElementSibling.textContent = "";
}
if (email.value == "admin#example.com" && password.value == "password") {
document.writeln("Welcome back Admin!")
} else {
document.writeln("That email and password doesn't seem to be right. Try again.")
}
// submit the form if all entries are valid
if (isValid) {
$("#login_form").submit();
}
});
});

HTML FORM - setting form action on javascript

i've been having a problem where i have a form in which several entities within an unordered list are displayed, a name and a button dinamically with vanilla javascript. The problem is, im changing the action value from the html form, from javascript this so i can add an id that i get in a JSON from a http request so i can manipulate a specific object, but it doesnt send the "delete" request, which is actually a post request that im managing from my server side correctly (tested in postman and works like a charm), but when calling from the front-end it stops working. Here are my html and script.
PANEL.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
<link rel="stylesheet" type="text/css" href="css/panel-style.css">
<script defer src="panel-script.js"></script>
<title>Panel de Control</title>
</head>
<body>
<header>
<img src="assets/mrvapeslogo.png" alt="mrvapes logo">
</header>
<section>
<form id="files-form" accept-charset="UTF-8" enctype="multipart/form-data" action="#" autocomplete="off" method="POST" onsubmit="return validate(this);">
<label for="user">Banners Activos</label><br/>
<ul id="files-container">
</ul>
</form>
<form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
<div class="container">
<div class="button-wrap">
<!-- <label class="button" for="upload">Subir</label> -->
<input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
<input id="image" name="file" value="Subir" placeholder="Subir Archivo" type="file" required>
<button id="upload" value="post-request" type="submit">Enviar</button>
<!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
</div>
</div>
</form>
</section>
</body>
PANEL-SCRIPT.JS
const list = document.getElementById("files-container");
const filesForm = document.getElementById("files-form");
fetch('http://localhost:3000/banner')
.then(response => response.json())
.then(json => {
console.log(json)
console.log(json.message)
for (let i = 0; i < json.message.length; i++) {
var item = `<li>${json.message[i].name}
<button id="delete-button" onclick="deleteButton('${json.message[i].name}','${json.message[i]._id}')">Borrar</button>
</li>`;
list.innerHTML += item;
}
});
function deleteButton(name, id) {
var answer = confirm(`Seguro que deseas borrar ${name}?`);
if (answer) {
filesForm.action = `http://localhost:3000/banner/${id}`;
alert('Borrado Correctamente!');
window.location.reload(true);
} else {
validate();
}
}
function validate() {
return false
}
HAPPY HOLIDAYS! :D
-- UPDATE --
When making these changes below to my panel-script.js, my delete function starts working but everytime i cancel the confirm dialog it forwards me to a "cannot post page".
function deleteButton(name, id) {
var answer = confirm(`Seguro que deseas borrar ${name}?`);
if (answer) {
filesForm.action = `http://localhost:3000/banner/${id}`;
alert('Borrado Correctamente!');
// window.location.reload(true);
} else {
// validate();
return false;
}
}
// function validate() {
// return false
// }

if statement passed but else statement is also executed - JavaScript

I have a login system that loops through an array of objects to fetch and compare username and password entered by the user in the login page. I have issued an if statement to check if user credentials are correct. The problem am having is that the system shows the else statement even when the if statement has passed or the user credentials are correct.
Please see the full demo in the link below;
https://jsfiddle.net/dej5sr9z/
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta name="generator" content="Ayub Technologies">
<meta name="author" content="Verai Bosobori" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="description" content="">
<title>Lycan CREATIONS | Home</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<section>
<div class="form_div">
<h2>Login</h2>
<div style="text-align:left; color:red; font-weight:bold;" id="error"></div>
<div style="text-align:left; color:green; font-weight:bold;" id="success"></div>
<br>
<form action="#">
<div class="form_input">
<label for="">Username</label>
<input type="text" id="username" placeholder="">
</div> <br>
<div class="form_input">
<label for="">Password</label>
<input type="password" id="passwd" placeholder="">
</div>
<div class="form_input">
<p style="text-align:left; color:blue;">Forgot Password?</p>
</div>
<div class="form_submit">
<button type="submit" onclick="getInfo()">Submit</button>
</div>
</form>
</div>
</section>
</body>
</html>
Beolow is the JavaCript Code
var objPeople =[
{
username: "verai",
passwd: "lycan"
},
{
username: "ayub",
passwd: "metah"
},
{
username: "chris",
passwd: "forever"
}
]
function getInfo(){
var username = document.getElementById("username").value;
var passwd = document.getElementById("passwd").value;
var error = document.getElementById("error").innerHTML;
if (username != '' || passwd != ''){
for(i = 0; i < objPeople.length; i++){
if(username == objPeople[i].username && passwd == objPeople[i].passwd){
document.getElementById("success").innerHTML = "Hello " + username + "!! You are successfully logged in!!!";
console.log(username + " is logged in!!!");
setTimeout(function(){
document.getElementById("success").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},5000);
}else{
document.getElementById("error").innerHTML = " Incorrect Username or Password. Please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
}else{
// console.log("Your username is " + username + " and your password is " + passwd );
document.getElementById("error").innerHTML = "All fields required, please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
I will appreciate if someone points out what am not doing right, thanks.
Assuming a correct combination has been entered, the for-loop goes into the if-part once for the matching user, but also it goes into the else-part for all other non-matching users. There is nothing in place to prevent that from happening.
You need to determine who is the one matching person if any, and then proceed with that result (which is either a user object, or undefined).
You can do so with find, using code like this:
var matchingUser = objPeople.find(p => username === p.username && passwd === p.passwd);
if (matchingUser) {
// ...
} else {
// ...
}
Side note - I used the "triple equal sign", which does an exact comparison between objects without any type conversions that could get in the way.

Why is php POST array empty for me in one instance and populated in another, both using XHR POST?

I am trying to write code that will check if username is already used, and I wrote some test code where my php $_POST array was populated. However, I modified the test code slightly for the 'production' code I am developing, and my $_POST array is empty. My first set of code, that is working, html file is
<!DOCTYPE html>
<html lang="en">
<head>
<title>Testing XMLHttpRequest</title>
<meta charset="utf-8">
</head>
<body>
<header>
<h1>Testing XMLHttpRequest</h1>
</header>
<main>
<form name="newUser">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<p id="serverResponse"></p>
<label for="password">Password:</label>
<input type="password" name="password">
</br>
<label for="confirm">Retype Password:</label>
<input type="password" name="confirm">
</form>
</main>
<script src="index.js"></script>
</body>
</html>
First set of code javascript file
(function () {
let usernameInput = document.querySelector("#username");
let serverResponse = document.querySelector("#serverResponse");
usernameInput.addEventListener("blur", function (event) {
let username = event.target.value;
if (username !== "") {
let request = new XMLHttpRequest();
request.open("POST",'validator.php',true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
serverResponse.innerHTML = this.responseText;
}
}
request.send(`username=${username}`);
}
else {
serverResponse.innerHTML = "";
}
});
}());
First set of code php file
<?php
$username = $_POST['username'];
echo $username;
?>
My modified code that does not work is below. The html file is
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lunch Decider - New User Registration</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Lunch Decider</h1>
</header>
<nav>
<ul>
<li>Home/Cancel</li>
</ul>
</nav>
<main>
<form action="newUser.php" method="POST" name="newUser">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<button type="button" id="checkAvailabilityButton">Check Availability</button>
<p id="availabilityResponse"></p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</br>
<label for="checkPassword">Repeat Password:</label>
<input type="password" id="checkPassword" name="checkPassword" required>
</br>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
</main>
<script src="newUser.js"></script>
</body>
</html>
The javascript file for the code that does not work is
(function () {
let checkAvailabilityButton = document.querySelector("#checkAvailabilityButton");
let username = document.querySelector("#username");
let availabilityResponse = document.querySelector("#availabilityResponse");
checkAvailabilityButton.addEventListener("click", function(event) {
if (username.value === "") {
alert("You must first enter a username.");
}
else {
let xhr = new XMLHttpRequest();
xhr.open("POST","checkAvailability.php",true);
xhr.setRequestHeader("Content-type","application/x-www-url-formencoded");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
availabilityResponse.innerHTML = this.responseText;
}
};
xhr.send(`username=${username.value}`);
}
});
}());
and finally my php code that does not work is
<?php
$username = $_POST['username'];
echo $username;
?>
Not sure where I have gone wrong in the second set of code. I have tried putting my data in a FormData object and passing that to the XHR.send() method. I realize I have switched in my first set of code from a 'blur' event on the input I am interested in directly, to my second set of code where my main event is clicking on a 'checkAvailability' button, but I can't see where that would make my $_POST array not accept the sent value. In both cases I can see where in the request there is username=nameEntryFromInputTextBox.
Please take a look and advise.
Not sure if xhr.send sends in JSON format, but in any case, try catching the post with:
$post = json_decode(file_get_contents("php://input"));
// will make an object - $post->var
$post = json_decode(file_get_contents("php://input"), true);
// will make an array - $post['var']
PHP "php://input" vs $_POST
I had a typo, in my code that was not working I had Content-type set to x-www-url-formencoded. It should have been x-www-form-urlencoded.

This form is submiting but it shouldn't [duplicate]

This question already has answers here:
How to stop form submit during ajax call
(7 answers)
Closed 8 years ago.
I'm working on a website and I have this change_password.php script which is a 3 fields where the user puts his last password, his new password and his new password for a second time. I've tried to make a verification if the second and the third matches. If they don't I show an alert to the user.
The problem is that it does show the alert when the password are different but it redirects to the next page, do_change_password.php anyway. What can I do to fix it?
<html>
<?php
session_start(); // começa a session
require "config.php";
if(Check_Login_Status())
{
Update_Login_Status();
}
else
{
session_unset();
phpAlert_Redirect("ACESSO NEGADO", "index.php");
exit();
}
?>
<head>
<meta charset = 'UTF-8'>
<link rel="shortcut icon" href="images/favicon.ico"/>
<title>Sistema de Estágios - UFMS - Login</title>
<link href = "css/bootstrap.css" rel = "stylesheet" >
<link href = "css/index.css" rel = "stylesheet" >
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("input").blur(function()
{
if($(this).val() == "")
{
$(this).css({"border" : "1px solid #F00"});
}
else
$(this).css({"border" : "1px solid #FFF"});
});
$("#botao").click(function()
{
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
cont++;
});
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x == y)
$("#form").submit();
else
alert("Senhas não conferem");
}
});
});
</script>
</head>
<body>
<?php
Set_Barra_Superior($_SESSION["auto"]);
?>
<center>
<div class = "container">
<div class = "principal">
<form id="form" name="Form" method="post" action="do_change_password.php">
<p>
<label for="a">Senha antiga:</label>
<input id="a" name="old_pass" type="password" class="form-control"/><br/>
</p>
<p>
<label for="b">Nova Senha:</label>
<input id="b" name="new_pass" type="password" class="form-control"/><br/>
</p>
<p>
<label for="c">Confere nova senha:</label>
<input id="c" name="conf_pass" type="password" class="form-control"/><br/>
</p>
<button id="botao" name="botao" value="login" class="btn btn-primary" style="width: 100%;">Login</button>
</form>
</div>
</div>
</center>
</body>
Add the event into the click function, call preventDefault on the event and then return false.
$("#botao").click(function(e)
{
e.preventDefault();
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
cont++;
});
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x == y)
$("#form").submit();
else
alert("Senhas não conferem");
}
return false;
});
Try returning false like:
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x != y)
{
alert("Senhas não conferem");
return false;
}
}

Categories