Passing Javascript Input Values to a PHP file to Post to SQlite - javascript

I wanted to ask how can i get the values of the Javascript Input and store it into a php value so i can post this data into Sqlite3. Im receiving user inputs from the Javascript Prompts. Is there another way to accomplish this also. Any help would be greatly appreciated.
function myFunc(){
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
if(code==""||code==null||code!="1234"){
//Handle Error
window.location.href="error.html";
}
}
document.onreadystatechange = () => {
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
myFunc();
}
});
}

Using jquery you can use the $.post method:
function myFunc() {
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
var url = "phpToGetInputs.php";
var data = {
code: code,
email: email
}
$.post(url, data); // "send the data to the php file specified in url"
// code...
}
document.onreadystatechange = () => {
// code...
}
Then, in your PHP file (that you specified as the url)
phpToGetInputs.php:
<?php
if(isset($_POST['email'])) {
$email = $_POST['email']; // get the email input (posted in data variable)
$code = $_POST['code']; // get the code input (posted in data variable)
// do code that requires email and code inputs
}
?>

Use a jQuery post request to send the variable from javascript to php.
$.post([url], { "data" : text });
Look at this website for more information: https://api.jquery.com/jquery.post/

Related

Data Insertion And Page Redirect Not Working jQuery directly printing Else Part

I am working with HTML, PHP, jQuery.
In HTML Form with input type button I am sending data to jQuery and with post I am send to PHP file and then inserting in the database, the problem in my scenario is that in JavaScript file I am just getting else part of the code, the else part is "Enter Your Details Correctly" and data is not inserted in the database, and also page redirect is not working in both success or failure of data insertion. I will really appreciate your time if you guys can help.
On different project my data is inserted in the database but page redirect not working, for page redirect I tried window.location.href, window.location.replace.
$(document).ready(function() {
"use strict";
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var gender = $("input[type=radio]:checked").val();
var msg = $("#msg").val();
if(name ===''|| email===''|| contact===''|| gender===''|| msg==='') {
alert("Insertion Failed Some Fields are Blank....!!");
}
else {
$.post(
"contactsave.php",
{ name: name, email: email, contact: contact,gender:gender, msg:msg},
function(data) {
if(data.message==='success')
{
window.location.replace("http://multimighty/contactthankyou.php");
}
else
{
alert("Enter Your Details Correctly");
}
},
'json');
}
});
});
/*contactsave.php*/
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$contact=$_POST['contact'];
$gender=$_POST['gender'];
$msg=$_POST['msg'];
$sql = "INSERT INTO test(name, email, phone, gender, message) VALUES ('$name','$email','$contact','$gender','$msg')";
if ($con->query($sql) === TRUE) {
echo json_encode(array("message"=>"success"));
} else {
echo json_encode(array("message"=>"failuer".$con->error));
}
$con->close();
exit;
?>
I just want a simple form insertion without page refresh and after that page redirect

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

AJAX Message Clear

I am finishing up a form for user registration, and I wanted to know how to clear messages generated dynamically by AJAX, when the user clears the input (backspace). For example, let's say they enter a valid input, but then clear it with all backspaces - my code currently shows the valid input message, but I want that to switch to an empty string / no message when that happens:
if ($nameCheckCount < 1) {
if (preg_match("/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/", $email)) {
echo 'This email is available.';
exit();
} else {
echo 'You entered an email with an invalid format.';
exit();
}
} else {
echo 'This email is taken.';
exit();
}
Is there some way I can change the above code I currently have to clear the message if there is no input after a backspace?
Secondly, once all the input is validated (I have one main HTML file for the form, and then three PHP files to check username, password, and email validity through the use of MySQL, or in the case of the passwords, a simple string match), can I set some sort of flag to then allow the user to submit? For example, the code that checks the email is as such:
function checkEmail() {
"use strict";
var status = document.getElementById("email_status");
var email = document.getElementById("email").value;
if (!(email == "")) {
status.innerHTML = "Checking...";
var request = new XMLHttpRequest();
request.open("POST", "email_check.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
status.innerHTML = request.responseText;
}
}
var verify = "emailToCheck=" + email;
request.send(verify);
}
}
This is within my HTML file with the form. Once all fields are validated, is there a way to then allow the user to submit? One user may only have a unique combination of the username and email fields which are stored in the user table along with other data, and no username can be associated with multiple usernames, and vice versa. Thank you in advance for any tips!

How can I use the results of various ajax requests in another function?

I have been programming a registration form with ajax validation. The way I have it set up is in my js file, I have listeners that fire when the content of the field is changed. They send the data to the server, and the server makes sure it's valid and sends back its response in the form of a JSON object. I then read the values of the JSON object to output potential error messages.
I won't copy and paste the entire files, just one example:
$(document).ready(function() {
// USERNAME VALIDATION LISTENER
$("#regUsername").change(checkName);
}
and then the checkName function looks like this, it sends my ajax request:
function checkName() {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "nameAvail",
username: $("#regUsername").val()
},
success: function(data) { // execute on success
var json = jQuery.parseJSON(data);
if (json.success) { // if usernames do match
$("#usernameAvailiability").removeClass().addClass('match');
$("#usernameAvailiability").text(json.msg);
} else { // if the user has failed to match names
$("#usernameAvailiability").removeClass().addClass('nomatch');
$("#usernameAvailiability").text(json.msg);
}
}
});
}
And depending on the response, it updates a span that tells the user if the input they wrote is valid or not.
The server validates with this part of the php file:
if(!isset($_POST['request'])) { // do nothing if no request was provided
print("no request provided");
} else { //ELSE request has been provided
if ($_POST['request'] == "nameAvail") { // if the request is to check if the username is valid
$response = array("success" => false, "msg" => " ", "request" => "nameAvail");
// CHECK USER NAME AVAILIABILITY CODE
if (!isset($_POST['username']) || empty($_POST['username'])) { // if no username is entered
$response['success'] = false;
$response['msg'] = "No username provided";
} else { // if a username has been entered
$username = $dbConn->real_escape_string($_POST['username']);
if (!ctype_alnum($username)) { // Make sure it's alpha/numeric
$response['success'] = false;
$response['msg'] = "username may only contain alpha numeric characters";
} elseif (strlen($username) < 4) { // make sure it's greater than 3 characters
$response['success'] = false;
$response['msg'] = "username must be at least 4 characters long.";
} elseif (strlen($username) > 20) { // make sure it's less than 26 characters
$response['success'] = false;
$response['msg'] = "username can be up to 20 characters long.";
} else { // make sure it's not already in use
$query = $dbConn->query("SELECT `id`, `username` FROM `users` WHERE `username` = '"
. $username . "' LIMIT 1");
if ($query->num_rows) { // if the query returned a row, the username is taken
$response['success'] = false;
$response['msg'] = "That username is already taken.";
} else { // No one has that username!
$response['success'] = true;
$response['msg'] = "That username is availiable!";
}
}
}
print(json_encode($response));
}
What I'd like to do now is create a function in my javascript for the register button. But I need to make sure all the forms are validated first.
I'm not sure what my options are. What I'd LIKE to do is somehow be able to recycle the code I've already written in my PHP file. I don't want to write out an entirely new if($_POST['request'] == "register") clause and then copy and paste all the validation code to make sure the input is valid before I insert the registrant's data into the database. It seems really repetitive!
I know I could check to see if all the spans on the page were set to 'match', but that could easily be tampered with and blank forms could be submitted.
so far, my register button function looks like this:
function register() {
if ( NEED SOME KIND OF CLAUSE HERE TO CHECK IF ALL THE FIELDS ARE VALID) {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "register",
username: $("#regUsername").val(),
password: $("#regPassword").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sQuest: $("#securityQuestion").val(),
sAns: $("#securityAnswer").val(),
ref: $("#referred").val()
}, success: function(data) {
var json = jQuery.parseJSON(data);
console.log(json);
$("#regValid").removeClass();
$("#regValid").text("");
}
}); //AJAX req done
} else {
$("#regValid").removeClass().addClass('nomatch');
$("#regValid").text("One or more fields are not entered correctly");
}
return false;// so that it wont submit form / refresh page
}
I would really appreciate some help, I've spent the last few hours scouring StackOverflow for an answer, but I can't seem to get anything to work. Will I have to duplicate code in my PHP file or is there a more elegant way to handle this?

javascript onBlur not working, and how to connect javascript files

I have two javascript files that I am using to validate an email address.
validate.js:
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (emailFilter.test(email.value)) {
//alert('Please provide a valid email address');
//email.focus;
return true;
}
else{
return false
}
}
navigation.js EDIT:
$(document).ready(function() {
//ADDED IMPORTS
var imported = document.createElement('script');
imported.src = 'lib/validation.js';
document.head.appendChild(imported);
console.log("DOCUMENT IS READY!");
var viewsWrapper = $("#views-wrapper");
var loginButton = $("#login-button");
var registerButton = $("#register-button");
// Login Link
// TODO: Unclear if needed
$("ul li.login").click(function() {
$.get('/login', function(data) {
viewsWrapper.html(data);
});
});
$('#usernamefield').blur(function() {
var sEmail = $('#usernamefield').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (checkEmail(sEmail)) {
alert('Email is valid');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
...(more code follows but not relevant)
I am also using this jade template:
login.jade:
form(action="")
key EMAIL
input(type="text", name="username", id="usernamefield")
p hello world
br
key PASSWORD
input(type="text", name="password", id="passwordfield")
p hello world
br
input(type="submit", name="loginButton", id="login-button", value="LOGIN")
My issue is that when I input something into my email field, I do not get an alert message in any case. Am I allowed to just have to separate javascript files and call the methods I defined in validate.js within navigation.js? I tried putting the validate.js code in navigation.js, but even then it did not work. I would like to keep the files separate. Am I missing something obvious? I want it so that once the user inputs the email, and leaves the field, a message should appear warning if the email is valid or not.
Your help is appreciated.
Is it the blur Event or the checkEmail the problem? try to put a alert() or console.log() just after your blur (and make sure to lose focus on your input). Seperate file shouldn't be a problem. And also have you check for errors in your console ?
JavaScript string has no "value" field
After
var sEmail = $('#username').val();
sEmail becomes a string.
You are passing this string to checkEmail method and try to get "value" from a string:
if(!emailFilter.test(email.value)) {//...}
Replace to
if (!emailFilter.test(email)) {//...}
You are already sending the value of email into checkemail function. So in checkEmail function in validate.js remove email.value in second line of function checkEmail
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
//alert('Please provide a valid email address');
email.focus;
return false;
}
}

Categories

Resources