In the application I'm developing I have an admin panel in that panel there a function to create, edit and delete users.
In the form I create 3 user types using a while loop which drags data from a database and the 3 user types are:
Admin
Manager
User
HTML Form:
<?php
/**
* Created by PhpStorm.
* User: SiNUX
* Date: 4/6/2017
* Time: 3:41 PM
*/
session_start();
include_once("../iConnect/handShake.php");
$getUserRole = "SELECT * FROM userroles ORDER BY urId ASC";
$getUserRoleQuery = $dbConnect -> query($getUserRole);
?>
<html>
<head>
<title>Timer User Creation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Style Sheets -->
<link rel="stylesheet" type="text/css" href="../../CSS/main.css">
<!-- Java Scripts -->
<script language="JavaScript" type="text/javascript" src="../../jScripts/jquery-3.2.0.min.js"></script>
<script language="javascript" type="text/javascript" src="../../jScripts/svrTimeDate.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/reload.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/setMsg.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/userCreatFunctions.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/multiScript.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/getIds.js"></script>
</head>
<body onload="pauseLoad4()">
<div id="divCenter" class="box">
<label id="userName">Hello <?php echo $_SESSION["fName"]." ".$_SESSION["lName"]; ?></label><br><br>
<label id="uId" hidden>1</label>
<div style="width: 166px; position: absolute; left: 642px; top: 20px; height: 44px;">
<img src="../../images/logo.png" width="142" height="33">
</div>
<label for="date">Date:</label>
<label id="date" style="margin-left: 50px;"></label><br><br>
<label for="fName">First Name:</label>
<input type="text" id="fName" name="fName" style="margin-left: 10px;" onkeyup="checkEmpty();">
<label for="lName" style="margin-left: 8px;">Last Name:</label>
<input type="text" id="lName" name="lName" style="margin-left: 10px;" onkeyup="checkEmpty();" disabled>
<label for="uName" style="margin-left: 8px;">User Name:</label>
<input type="text" id="uName" name="uName" style="margin-left: 7px;" onkeyup="checkEmpty();" disabled><br><br>
<label for="pWord1" style="margin-left: 8px;" >Password:</label>
<input type="password" id="pWord1" name="pWord1" style="margin-left: 17px;" onkeyup="checkLength();" disabled>
<label for="pWord2" style="margin-left: 8px;">Confirm Password:</label>
<input type="password" id="pWord2" name="pWord2" style="margin-left: 8px;" onkeyup="checkPass();" disabled>
<label for="uTeam" style="margin-left: 8px;">Team</label>
<select name="uTeam" id="uTeam" style="width: 170px;" onchange="teamId(this.id);enableRoles();" disabled>
<option></option>
</select>
<input type="text" name="uTeamId" id="uTeamId" hidden><br><br>
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
<label id="msgID" hidden></label>
<div id="msg"></div>
<div id="sbmBtns">
<input type="button" value="Reset" name="reset" id="reset" class="btn" onclick="resetForm()">
<input type="button" value="Submit" name="submit" id="submit" class="btn" onclick="pauseLoad3();" disabled>
</div>
</div>
</body>
</html>
I use a JavaScript to validate the form and to enable the next text box if the validation criteria is met.
JavaScript:
function checkEmpty() {
var msg = document.getElementById('msg'),
fName = document.getElementById('fName'),
lName = document.getElementById('lName'),
uName = document.getElementById('uName'),
pass1 = document.getElementById("pWord1");
//Using ajax made the function to check if the text box value is empty or not
//when that text box has focus.
if ($("#fName").is(':focus')){
if (fName.value.length <= 3){
msg.innerHTML = "First name is too short";
}else{
msg.innerHTML = "";
lName.disabled = false;
}
}
if ($("#lName").is(':focus')){
if (lName.value === fName.value){
msg.innerHTML = "Last and first name can't be the same";
pass1.disabled = true;
}else{
if (lName.value.length <= 3){
msg.innerHTML = "Last name is too short";
}else{
msg.innerHTML = "";
uName.disabled = false;
}
}
}
if ($("#uName").is(':focus')){
if (uName.value.length <= 3){
msg.innerHTML = "User name is too short";
pass1.disabled = true;
}else{
if(uName.value.length > 0){
checkUname();
}
}
}
function checkUname() {
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
if (xmlhttp.responseText === "1"){
msg.innerHTML="Username taken";
pass1.disabled = true;
}else{
msg.innerHTML = "";
pass1.disabled = false;
}
}
};
xmlhttp.open("POST","../Functions/matchUname.php?uName="+uName.value,true);
xmlhttp.send();
}
}
function checkLength() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
passLength1 = pass1.value.length;
if(passLength1 <= 4){
document.getElementById("msg").innerHTML ="Password is less than 4 characters!";
}else{
document.getElementById("msg").innerHTML ="";
pass2.disabled = false;
}
}
function checkPass() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
uTeam = document.getElementById("uTeam"),
matchColor = "#66cc66",
noMatchColor = "#ff6666";
if (pass1.value === pass2.value){
document.getElementById("msg").innerHTML ="Passwords match!";
pass1.style.backgroundColor = matchColor;
pass2.style.backgroundColor = matchColor;
uTeam.disabled = false;
}else{
document.getElementById("msg").innerHTML ="Passwords do not match!";
pass1.style.backgroundColor = noMatchColor;
pass2.style.backgroundColor = noMatchColor;
}
}
function enableRoles() {
var team = document.getElementById("uTeam").value,
teamId = document.getElementById("uTeamId").value,
tlCheck = document.getElementById("tl"),
role = document.getElementsByClassName("userRoles");
if (team !== ""){
//For loop to enable radio buttons
for (var i = 1; i < role.length; i++){
role[i].disabled = false;
//This part will take the team is from uTeamId text box
//send it to getTeam.php checks if that team has a leader if that team has a leader
//"set" value will be returned making the check box for team attribute team leader disabled.
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
// document.getElementById("msgID").innerHTML = xmlhttp.responseText;
tlCheck.disabled = xmlhttp.responseText === "set";
}
};
xmlhttp.open("POST","../Functions/getTeam.php?teamId="+teamId,true);
xmlhttp.send();
}
}
}
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
It's working with out any errors but I want to disable the Admin user type if the logged in user is not a admin. I can get this done by using pure PHP but it breaks the flow of the form.
In my HTML/PHP form I have used PHP to archive what I'm describing but it not really what want to do I want use JavaScript or jQuery or AJAX to archive this.
The PHP I use:
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
Can some direct me down the right path or show me how to do this.
UPDATE:
After talking with professionals I learned that what I was trying to do is to shoot my self in the foot by my own gun. It's a bad idea to use client side languages to handle security options and WE CAN'T TRUST THE USER. My main issues was the flow of the form but security trumps the beauty so this will be split in to another one which the normal user want even see the admin option.
I would like to leave this question here and don't mind if it get closed so others can learn something from my mistake.
Just to nail this one down...
After a nice chat discussion, it appears that Jack (OP) has understood the importance not to manage user level security on client side.
The questions no longer needs more answer.
;)
Related
I have a custom method for validating the user input, but my form doesn't seem to be submitting. Also, the URL changes after my first submission, and the jquery only runs once the URL's changed.
The purpose of this code is to check if the information submitted is in a database. The function runs, but the value for the name field doesn't seem to be stored upon submission, and so I keep getting the error for name.
Here's my code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<title>Smiles Galore (SG)</title>
<script>
$(document).ready(function(){
$('#target').on('submit', function(){
var emailChecker = $('#email').val();
var idChecker = $('#number').val();
var passCheck = $('#pwd').val();
var userName = $('#text').val;
if (userName.length <2){
alert("Please enter a name");
}
else{
if (idChecker.toString().length != 8){
alert("That's not a proper input for ID. Please provide a proper ID");
}
else{
if (!hasUpperCase(passCheck)){
alert("That's not a password. Enter a proper password.");
}
else if(!/[0-9]/.test(passCheck)){
alert("That's not a password. Enter a proper password.");
}
else if(passCheck.length > 8){
alert("That's not a password. Enter a proper password.");
}
else{
Verification(userName,emailChecker,passCheck,idChecker);
}
}
}
function hasUpperCase(word){
return word.toLowerCase()!=word;
}
function Verification(userName1,emailCheck1,passChecker,idCheck){
var selection = $("list").val();
alert("Hello");
$.post('Access.php',{'Patron Email Address':emailCheck1,'Patron Name':userName1,'Patron ID':idCheck,'Patron Password':passChecker},function(data){
if (data=='0'){
alert("The email is incorrect");
return;
}
else{
alert("You good");
if (selection == "Search for Appointment"){
$.post('Process.php',{'Patron Email Address':emailCheck1},function(){});
}
else if (selection == "Schedule an Appointment"){
return;
}
else if (selection == "Cancel an Appointment"){
return;
}
else if (selection == "Create/Register an Account"){
return;
}
return;
}
});
}
return false;
});
});
</script>
</head>
<body>
<form id="target">
<div class="form-group">
<label for="text">Name:</label>
<input type="text" class="form-control" id="text">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="number">ID:</label>
<input type="number" class="form-control" id="number">
</div><br>
<label for="list">Select an Option:</label><br>
<select name="Select an Option:" id="list">
<option value="Schedule an Appointment">Schedule an Appointment</option>
<option value="Cancel an Appointment">Cancel an Appointment</option>
<option value="Search for Appointment">Search for Appointment(s)</option>
<option value="Create/Register an Account">Create/Register an Account</option>
</select><br>
<br><div>
<input type="submit" class="btn btn-primary mb-2" value="Continue">
</div>
</form>
</body>
You don't have a () after val for name like you do on the other variables.
Change var userName = $('#text').val; to var userName = $('#text').val();
That will fix your name problem.
Also noticed that you don't have a # in your jquery selector for selection.
Change var selection = $("list").val(); to var selection = $("#list").val();
Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box - should be in format example#gmail.com
Website : Text box - should be in format http://www.example.com
Country : Select box with 10 countries
Mobile : Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.
<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
// $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>
this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>
<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>
I have a PHP snippet that display the table row dynamically. Every row I there's a radio button with "Yes" and "No" option.
I created a JS function, when the user choose an option, there's a pop-box will be displayed.
If the user choose "Yes" option in the radio button and click "Ok" in the pop-box, the table row will be disabled even the radio button will be disable too. And the chosen option will be save in MYSQL.
How to save the chosen option in MySQL?
My JS snippet of disabling a row is not working. How to fix this?
PHP:
echo '<td id="resumeFile">Download Resume</td>';
echo '<td id="radioOption">
<label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes" name="processedOption" value="Yes" onclick="proccessedCheck()"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo" name="processedOption" value="No" onclick="proccessedCheck()"/></td>';
JS:
function proccessedCheck(){
var checked = null;
var inputs = document.getElementsByName('processedOption');
for (var i = 0; i < inputs.length; i++){
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked == null){
return false;
} else if (checked == true){
document.getElementById("resumeFile").disabled = true;
document.getElementById("radioOption").disabled = true;
document.getElementById("resumeFile").title = "This option has been disabled.";
} else {
return confirm('You have chosen '+ checked.value + ', is this correct?');
}
}
Ok so if you are echo'ing the whole table from PHP just preset the parameters into the table
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script>
function proccessedCheck(id,answer) {
if (confirm('You have chosen '+ id +': '+ answer + ', is this correct?')) {
$("#processedOptionYes"+id).attr('disabled',true);
$("#processedOptionNo"+id).attr('disabled',true);
var withlink = $("#resumeFile"+id).html();
var withoutlink = $(withlink).html();
$("#resumeFile"+id).html("").append(withoutlink);
$("#input1".val(id);
$("#input2".val(answer);
$("#myform").submit();
}
}
</script>
<!-- EDIT: hidden form to submit -->
<form id="myform" method="POST" action="savedb.php">
<input type="hidden" id="input1" name="id" />
<input type="hidden" id="input2" name="answer" />
</form>
<table>
<tr>
<?php
$dir="";
$file="";
$id = 0;
//foreach($array as $row) {
$id++;
echo '<td id="resumeFile'.$id.'">Download Resume</td>';
echo '<td id="radioOption>
<label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes'.$id.'" name="processedOption" value="Yes" onclick="proccessedCheck('.$id.',\'Yes\')"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo'.$id.'" name="processedOption" value="No" onclick="proccessedCheck('.$id.',\'No\')"/></td>';
//}
?>
</tr>
</table>
</body>
</html>
Contents of savedb.php, this doesn't have to be a seperate file
<?php
// Check if my post array arrived, comment this line when u done
echo "<pre>";print_r($_REQUEST);echo "</pre>"; die();
// Connect to DB
// Build SQL insert string with $_REQUEST['id'] as the primary key
?>
For starters, try replacing:
document.getElementById("resumeFile").disabled = true;
document.getElementById("radioOption").disabled = true;
with:
document.getElementById("processedOptionYes").disabled = true;
document.getElementById("processedOptionNo").disabled = true;
I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.
Here is the php code:
#session_start();
if(isset($_SESSION["username"])){
header("location: home.php");
exit();
}else{
$usertitle = $_POST['ut'];
$userfname = $_POST['uf'];
$userlname = $_POST['ul'];
$useremail = $_POST['ue'];
$userloc = $_POST['uloc'];
$user_est_typ = $_POST['utp'];
$userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
$userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
if($usertitle == "Title...."){
echo '<font color="red">Error: Please select a title.';
exit();
}else if($userfname == NULL){
exit('<font color="red">Error: You need a first name to proceed. </font>');
}else if( strlen($userfname) <= 2){
exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
} else if($userlname == ""){
exit('<font color="red">Error: Giving a Surname would be nice.</font>');
}else if( strlen($userlname) <= 2){
exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
}else if(!strpos($useremail, "#") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
exit('<font color="red">Email Address not valid</font>');
}else if($user_est_typ == "Select..."){
exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
}else if($userloc == ""){
exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
}else {
include("../../scripts/dbconect.php");
$queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1");
$useremail_check = mysql_num_rows($queryuseremail);
if ($useremail_check > 0){
echo "The email address ".$useremail." is already registered in ur database";
exit();
}
// More Validation and mysql insert
exit('<font color="red">signup_success</font>');
}
}
Here is my AJAX codes:
function _(x){
return document.getElementById(x);
}
function show(id){
var divelement = _(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display == 'none';
}
function hide(id){
var divelement = _(id);
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display == 'block';
}
function emptyElement(id){
_(id).innerHTML = "";
}
function estimatetypeimg(){
var estType = _('estimatetype').value;
if (estType == 'solarpv'){
show('estimate_pv');
hide('estimate_thermal');
}
else if(estType == 'solarthermal'){
hide('estimate_pv');
show('estimate_thermal');
}
else{
hide('estimate_pv');
hide('estimate_thermal');
}
}
function newUsers() {
var title = _("salutation").value;
var fname = _("fname").value;
var lname = _("lname").value;
var email = _("email").value;
var loc = _("location").value;
var tp = _("estimatetype").value;
var url = "ajax.php";
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
_("statuscheck").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(vars);
}
And here is my html code:
<div id="startbuts" style="display:none">
<form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
<button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
<button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
</form>
<div id="existingusers" style="display:none">
<form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
<fieldset>
<legend>Existing users: login with your email and Data ID.</legend>
<input type="email" id="dataemail" placeholder="Email" >
<input type="text" id="dataid" placeholder="DataId"><br/>
<button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
</fieldset>
</form>
</div>
<div id="newusers" style="display:none">
<form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
<fieldset>
<legend>New users start here.</legend>
<div class="pure-control-group">
<label for="salutation">Title: </label>
<select id="salutation" name="salutation">
<option>Title....</option>
<option>Prof. Dr.</option>
<option>Prof.</option>
<option>Dr.</option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss.</option>
</select>
</div>
<div class="pure-control-group">
<label for="fname">First name:</label>
<input id="fname" name="fname" type="text" placeholder="First Name">
</div>
<div class="pure-control-group">
<label for="lname">Last name:</label>
<input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
</div>
<div class="pure-control-group">
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
</div>
<div class="pure-control-group">
<label for="location">Project Location: </label>
<input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
</div>
<div class="pure-control-group">
<label for="estimatetype">Type of Estimate: </label>
<select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
<option value="Select">Select...</option>
<option value="solarpv">Solar PV</option>
<option value="solarthermal">Solar Thermal</option>
</select>
</div>
<div id="estimate_pv" style="display:none" >
<img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" />
</div>
<div id="estimate_thermal" style="display:none">
<img id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" />
</div>
<hr/>
<button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
<button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
</fieldset>
</form>
</div>
</div>
Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.
So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "uf"
var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After
Hope this can be of help to someone else.
regards and thanks David and Khan.
Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/