Connecting HTML page with MySQL using PHP - php

This is my code to connect a page to a database (MySQL):
<html>
<body>
<title>Home</title>
<script language="javascript">
function checkTextField(field) {
if (field.value == '') {
alert("Field is empty");
}
}
function a(id) {
var ay = document.getElementById(id).value;
var pattern = /\d{4}-\d{2,4}/;
if(pattern.test(ay))
{
ay.style.backgroundColor="#52F40C";
return true;
}
else
{
window.alert ("Enter in YYYY-YY or YYYY-YYYY format");
ay.style.backgroundColor="red";
ay.focus();
ay.value="";
return false;
}
}
function c()
{
var n=document.getElementById("name");
var re=/^[a-zA-Z]+ ?[a-zA-Z]*$/;
if(re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("Invalid place name");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
function d()
{
var n= document.getElementById("date");
var re=/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/;
if (re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("enter in MM DD YYYY format");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
</script>
<body style="background-color:#708090;">
<?php
if (isset($_POST['submit']))
{
$mysqli= new mysqli("localhost","admin","admin", "nba" );
if($mysqli === false)
{
die("could not connect:" . mysqli_connect_error());
}
if ($inputError != true && empty($_POST['ayear']) )
{
echo 'ERROR: Please enter a valid year';
$inputError = true;
}
else
{
$ayear = $mysqli-> escape_string($_POST['ayear']);
}
if ($inputError != true && empty($_POST['fyear']) )
{
echo 'ERROR: Please enter a valid year';
$inputError = true;
}
else
{
$fyear = $mysqli-> escape_string($_POST['fyear']);
}
if ($inputError != true)
{
$sql="INSERT INTO year VALUES ('$ayear','$fyear')";
if ($mysqli-> query($sql)==true)
{
echo'Added';
}
else
{
echo"ERROR: Could not execute query : $sql. " . $mysqli-> error;
}
}
$mysqli-> close();
}
?>
<h1 style="font-family:Verdana;text-align:center;">National Board of Accrediation <br>of<br> Programme</h1>
<br>
<div id="menu" style="background-color:#800000;height:25px;width:1000px">
<b><font "style="font-family:Verdana">Part I&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspPart II&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspPart III&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspPart IV</font></b>
</div>
</p>
<h4 style="font-family:Verdana;text-align:center;"><b><u>Declaration</u></b></h4>
<form method="post" action="home.html">
<p> (<input type="text" size="9" name="ayear" id="ayear" onChange="a('ayear');" onBlur="checkTextField(this);">) (<input type="text" size="9" name="fyear" id="fyear" onChange="a('fyear');" onBlur="checkTextField(this);">).</p>
<p>Place:<input type="text" size="20" name="name" id="name" onChange="c();" onBlur="checkTextField(this);"></p>
<p>Date:<input type="text" size="10" name="date" id="date" onChange="d();" onBlur="checkTextField(this);">
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
The database connection is not working. How can I fix this? What is the problem with the code?

Unless you've set HTML to be executed like PHP code, none of your dynamic code will work.
Save a copy of that file with a .php extension and test if it works.

Change your file Extension to .php
And furthermore on your Form Action include a PHP extetention. like below
<form method="post" action="home.php">

Besides the other suggestions, I see that you have put a 'space' after -> on several locations;
e.g.
$mysqli-> escape_string($_POST['ayear']);
Should be
$mysqli->escape_string($_POST['ayear']);

Why you are trying to execute your php code in HTMl
Save your file wth .php extension definitely it will work.

Related

why the trim function is mandatory when compare responseText

While testing some Ajax and PHP code I stumbled an issue with AJAX's responseText. When I use it without trim() a comparison in inside the function registration (see js.js) fails. I have verified if the response of the php code does not include a newline (see registration.php).
form.php
<?php?>
<html>
<head>
<script type="text/javascript" src=".js"></script>
</head>
<body>
<div>
<form>
<div>
Name : <input type="text" id="name"><br />
LastName : <input type="text" id="lastname"><br />
<input type="button" value="send" onclick="registration()">
<div id="message"></div>
</div>
</form>
</div>
</body>
</html>
js.js
function getRequestHttp()
{
var requestHTTP;
if(window.XMLHttpRequest)
{
requestHttp=new XMLHttpRequest();
if(requestHttp.overrideMimeType)
requestHttp.overrideMimeType('text/xml');
}
return requestHttp;
}
function getDataForm() {
var name,lastname,all;
name = document.getElementById('name').value;
lastname = document.getElementById('lastname').value;
all = "name="+name+"&lastname="+lastname;
return all;
}
function registration()
{
req.open('POST','inscription.php',false);
req.setRequestHeader('Content-Type','application/x-www-form-
urlencoded');
req.send(getDataForm());
if(req.readyState==4)
{
if(req.status==200)
{
//alert(req.responseText);
document.getElementById('message').innerHTML = "";
if (req.responseText.trim()=="no")
document.getElementById('message').innerHTML = "already exists";
else if (req.responseText.trim()!="no")
{
document.getElementById('message').innerHTML = "registration succeeded";
}
else
document.getElementById('message').innerHTML = "problem ";
}
else
alert("Error :"+req.status+",wrong request");
}
return true;
}
registration.php
<?php
header("Content-type: text/plain");
$conn=pg_connect("host=localhost dbname=data user=user password=pass")
or die ("Connexion Impossible".pg_last_error());
$name= $_POST['name'];
$lastname=$_POST['lastname'];
$request="SELECT registration('$name','$lastname')";
$res=pg_query($conn,$request) or die('damn ' . pg_last_error());
$code=pg_fetch_row($res)[0];
if ($code==0) echo "no"; else echo $code;
?>
Because some times the spaces are being concatenated and your condition doesn't fulfill what you want. so for we use trim to avoid white spaces from both sides of results. Lets say we got success message from ajax request and we wrote condition like this :
if(response.message == "success"){
//do this
}else{
//do this
}
So in this case the response messages sometime comes with some white spaces appended thats why we use trim.
var response_msg = response.message;
if(response_msg.trim() == "success"){
//do this
}else{
//do this
}
This was the whole scenario i faced. If i am wrong, please correct me.

keeping first field in html form after submitting then have a master submit button after someone is done with the first field

I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"

Creating PHP Forms using jquery/ajax

I want to create two reports and submit the report data to database by using two functions within a class: Here I have two submit buttons: "Create ES Report" and "Create RP Report".
(1) When I click on "Create ES Report", create_es_report form should display and be able to fill the data and submit successfully to database and if errors it should display the errors on the same div.
(2) When I click on "Create RP Report", create_rp_report form should display and be able to fill the data and submit successfully to dataabase and if errors it should display the errors on the same div.
Rightnow, When I click on any of the submit buttons, nothing was displaying
index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#es').click(function ()
{
create();
});
});
function create(){
$.ajax({
url: "check.php?proc=create",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
</script>
</head>
<body>
<div class="container2">
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Create ES Report" id="es"></div>
<div id="returnMessage" style="display:none;"></div>
</div>
</body>
</html>
check.php
<?php
require 'includes/config.inc.php';
require 'classes/class.report.php';
$report = new Report($db);
if(isset($_GET['proc']) && !empty($_GET['proc']))
{
$proc = $_GET['proc'];
if($proc == 'create')
{
$report->create_es_report();
$return = array('mes' => 'Created' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
}
else
{
$return = array('mes' => 'The $_GET is empty , check if all parms and ajax function passing to the true file, good luck :).' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
?>
class.report.php
<?php
class Report
{
private $db;
public function __construct($database){
$this->db = $database;
}
//CREATE DATASOURCE REPORT
public function create_es_report()
{
if (isset($_POST['create_es_report']))
{
$report_name = htmlentities($_POST['report_name']);
$from_address = htmlentities($_POST['from_address']);
$subject = htmlentities($_POST['subject']);
$reply_to = htmlentities($_POST['reply_to']);
if (empty($_POST['report_name']) || empty($_POST['from_address']) || empty($_POST['subject']) || empty($_POST['reply_to']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['report_name']) && empty($_POST['report_name'])) { $errors[] = '<span class="error">Report Name is required</span>'; }
else if (!ctype_alnum($_POST['report_name']))
{ $errors[] = '<span class="error">Report Name: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['from_address']) && empty($_POST['from_address']))
{ $errors[] = '<span class="error">From address is required</span>'; }
else if (filter_var($_POST['from_address'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid From address</span>'; }
if (isset($_POST['subject']) && empty($_POST['subject'])) { $errors[] = '<span class="error">Subject is required</span>'; }
else if (!ctype_alnum($_POST['subject']))
{ $errors[] = '<span class="error">Subject: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['reply_to']) && empty($_POST['reply_to'])) { $errors[] = '<span class="error">Reply To is required</span>'; }
else if (filter_var($_POST['reply_to'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid Reply-To address</span>'; }
}
if (empty($errors) === true)
{
$query = $this->db->prepare("INSERT INTO report(report_name, from_address, subject, reply_to) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $report_name);
$query->bindValue(2, $from_address);
$query->bindValue(3, $subject);
$query->bindValue(4, $reply_to);
try {
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Location:home.php');
echo '<span class="error">Report is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
<div style="font-weight:bold;padding:17px 80px;text-decoration:underline;">Section A</div>
<table class="create_report">
<tr><td><label>Report Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="report_name" required placeholder="Name of the report" value="<?php if(isset($_POST["report_name"])) echo $report_name; ?>" size="30" maxlength="30">
</td></tr>
<tr><td><label>From</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="from_address" required placeholder="From address" value="<?php if(isset($_POST["from_address"])) echo $from_address; ?>" size="30">
</td></tr>
<tr><td><label>Subject</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="subject" required placeholder="Subject" value="<?php if(isset($_POST["subject"])) echo $subject; ?>" size="30">
</td></tr>
<tr><td><label>Reply To</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="reply_to" required placeholder="Reply address" value="<?php if(isset($_POST["reply_to"])) echo $reply_to; ?>" size="30">
</td></tr>
<tr><td><input type="submit" value="create report" style="background:#8AC007;color:#080808;padding:6px;" name="create_es_report"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false) {
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
}
}//Report CLASS ENDS
My guess is that your PHP is failing and the success option is not triggering.
I would suggest adding a console write of data.res in your success option and also add an error option and add a complete option that will write something different to console so you can determine if jquery is failing or if php is failing.
As a side note, I would combine your create_es and create_rp function to 1 since they are identical except for the query string value being passed in ajax. You would then call create_report("es") and create_report("rp") in your click events and your ajax url would be "check.php?proc=" + report, where report is your function param.
You seems don't know how to handle PHP and AJAX as well.
First change the urls E.G:
url: "check.php?proc=create_es",
to
url: "check.php?proc=create",
Look how at check.php the GET works.
And change type: "POST", to type: "GET",
Now to return the error's it's more complicated from just call a php function.
To return the error's you return from the create_es_report error's to the check.php file and return json format to you'r html page, this why i said LEARN ajax first.
Also don't use htmlentities i suggest you to use HTMLPURIFER to santize inputs from malicious inputs.

adding information to mysql database

Before i proceed, i would like to say i am a beginner and i am trying to validate a form using ajax, for username availability. Validations are done. But, everytime the page gets redirected to the form action page (Even if there are errors). I want, if there are errors i get a alert message and if no errors then data is written to db. I have been trying this for quite some time but i think i messed up and i dont understand what is wrong. Please, correct my mistakes. I am just trying to learn. What i am doing wrong here and what should i do?
registration.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<link rel="stylesheet" type="text/css" href="css/style.css"/>-->
<title>Using AJAX</title>
<script type="text/javascript" src="jquery-2.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#txtUsr').on('keyup', function(){
var username=$("#txtUsr").val();
var user_name_avail_result=$('.check');
var userCorrect=true;
if(username.length>2)
{
$.ajax({
type : 'POST',
cache:'false',
data : "username="+username,
url : "usr_available.php",
beforeSend: function()
{
user_name_avail_result.fadeIn(1000).html('<img src="green_ajax-loader.gif" /> ');
},
success: function(responseText) {
if(responseText == 200)
{
$(".check").html("<img src='available.png'/><span style='color:#59b200;'>Username available</span>");
}
else if(responseText ==201)
{
$(".check").html("<img src='not-available.png'/><span style='color:#ff0033;'>Username not available</span>");
userCorrect=false;
}
else if(responseText==202)
{
$(".check").html("Username too short");
userCorrect=false;
}
}
});
}
else
{
user_name_avail_result.html('<span style="color:#e50000;">Name too Short!</span>');
userCorrect=false;
}
if(username.length == 0) {
user_name_avail_result.html("");
userCorrect=false;
}
var exprUsr=/(^[A-Za-z][A-Za-z0-9]*([._-][a-z0-9]+){3,15})$/;
if(!exprUsr.test(username))
{
userCorrect=false;
}
});
$("#txtPwd").on('keyup',function(){
var regPwd=/^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,12})+$/;
var passTxt=$('#txtPwd').val();
var pwdCorrect=true;
if(!regPwd.test(passTxt))
{
$(".chkPwd").html('<div style="width:200px; height:80px; margin-left:190px; margin-top:-20px; text-align:left;"><span style="font-size:small; color:#ff0033;">Password must contain at least one digit, one lowercase, one uppdercase and one special character</span></div>');
pwdCorrect=false;
}
else
{
$(".chkPwd").html("");
}
if(passTxt.length==0)
{
$(".chkPwd").html("You Must Enter a Password");
pwdCorrect=false;
}
});
$("#txtUsr,#txtPwd,#txtMob").keydown(function(e) { <!-- Dont allow users to enter spaces for their username and passwords and Mobile Number-->
if (e.which == 32) {
return false;
}
});
$("#txtMob").keydown(function(e){<!--No other keys except number keys and backspace and tab work-->
if(e.which==8 || e.which==9)
return true;
if(e.which<48 || e.which>57)
return false;
});
$("#txtMob").on('keyup',function(){
var exprMob=/^[789]\d{9}$/;
var mobNum=$('#txtMob').val();
var mobCorrect=true;
if(!exprMob.test(mobNum))
{
if(mobNum.length<10)
{
$("#span3").html("Number must be minimum 10 characters long");
mobCorrect=false;
}
else
{
$("#span3").html("Number in wrong format");
mobCorrect=false;
}
}
else
{
$("#span3").html("");
}
});
function Validation(n){
if(userCorrect==false || pwdCorrect==false || window.mobCorrect==false)
{
alert("One or More field(s) is/are unfinished/empty. Please re-check.");
return false;
}
else
{
return true;
}
}
});
</script>
<script type="text/javascript">
function clearAll()
{
document.getElementById("txtUsr").value="";
document.getElementById("txtPwd").value="";
document.getElementById("txtMob").value="";
}
</script>
<style>
.chkPwd
{
margin-left:80px;
}
.check
{
margin-left:90px;
}
.form
{
margin:auto;
text-align:center;
font-family:Consolas;
font-size:medium;
}
.texts
{
font-family:Consolas;
}
#userDiv
{
background-color:#ccdbff;
height:320px;
width:500px;
border-radius:10px;
opacity:0.8;
}
#mainBody
{
background-color:#7a7acc;
width:100%;
height:100%;
}
</style>
</head>
<body class="form" id="mainBody">
<h1 style="color:#bfff00;">Registration</h1><br>
<form class="form" id="regForm" action="registration_success.php" method="POST" onsubmit="return Validation(this)">
<div class="form" id="userDiv"><br><br>
Username: <input class="texts" id="txtUsr" name="txtUsr" type="text" placeholder="Type user name here" autocomplete="off" maxlength="15" autofocus="autofocus" title="Please dont enter an aweful username!"/><br>
<span id="span1" class="check" style="font-size:small; color:"></span>
<br>
Password: <input type="password" id="txtPwd" class="texts" name="txtPwd" placeholder="Type password here" autocomplete="off" maxlength="12" title="Password must contain at least one digit, one lowercase, one uppdercase and one special character"/><br>
<span id="span2" class="chkPwd" style="font-size:small; color:red;">Min 6 and Max 12 Characters</span><br>
MobileNo.:<input type="text" maxlength="10" id="txtMob" class="texts" name="txtMob" placeholder="Enter your mobile number here" autocomplete="off" title="Please enter numbers only"/><br>
<span id="span3" class="chkMob" style="font-size:small; margin-left:10px; color:#ff0033; font-size:small;"></span><br>
<pre class="texts"> <input type="button" value="Back To LogIn" id="register" class="texts" name="register"/> <input type="submit" value="Submit" id="submit" class="texts" name="send"/> <input type="button" value="Reset" id="clear" onclick="clearAll()"/></pre>
</div>
</form>
</body>
</html>
user_available.php
<?php
if($_SERVER['REQUEST_METHOD']==='POST'){
if(!empty($_POST['username'])){
mysql_connect("localhost", "root","") or die ("Oops! Server not connected"); // Connect to the host
mysql_select_db("db_chkAJAX") or die ("Oops! DB not connected"); // select the database
// Check for the username posted
$username= mysql_real_escape_string($_POST["username"]); // Get the username values & prevent SQL-Injection
if(strlen($username)>2){
$check_query= mysql_query('SELECT Username FROM LoginRecord WHERE Username = "'.$username.'" ') or die("Cannot get data from table"); // Check the database
if(mysql_num_rows($check_query)<1){ // check num or rows 0 or greater than 0
echo 200;//Username doesnot exist in database
}
else{
echo 201;//Username exists in databse
}
} else {
echo 202;//Too short username
}
}
mysql_close($link);
return;//Stop execution
}
?>
registration_success.php
<!--Writing to the database-->
<?php
if(isset($_POST['send']) && !empty($_POST['txtUsr']) && !empty($_POST['txtPwd']) && !empty($_POST['txtMob']))
{
//Connecting to databse
$usr_name=test_input(strtolower($_POST['txtUsr']));
$pwd=$_POST['txtPwd'];
$mob=test_input($_POST['txtMob']);
$db_host='localhost';
$db_user='root';
$db_pwd='';
$conn=mysql_connect($db_host, $db_user, $db_pwd,true);
if(!$conn)
{
echo "Database connection Unsuccessful".mysql_error($conn)."<br>";
}
else
{
echo "Database connection Successful"."<br>";
}
//Creating a new database
$sql="CREATE DATABASE IF NOT EXISTS db_chkAJAX";
if (mysql_query($sql,$conn))
{
echo "Database db_student created successfully"."<br>";
}
else
{
echo "Error creating database: "."<br>";
}
//Creating a Table
$dataselect=mysql_select_db("db_chkAJAX",$conn);
if(!$dataselect)
{
die("Database not Selected".mysql_error()."<br>");
}
else
{
echo "Database Selected"."<br>";
}
$sql_create="CREATE TABLE IF NOT EXISTS LoginRecord (Username varchar (50), Password varchar(15), MobileNumber bigint(10))";
$qry=mysql_query($sql_create);
if(!$qry)
{
die("Table not created".mysql_error()."<br>");
}
else
{
echo "Table Created Successfully"."<br>";
}
//Inserting values into table
$data_insert="INSERT INTO LoginRecord(Username, Password, MobileNumber) VALUES('$usr_name', '$pwd', '$mob')";
$data_insert_query=mysql_query($data_insert);
if(!$data_insert_query)
{
die(" Unsuccessful data Insertion into table".mysql_error()."<br>");
}
else
{
echo "Data inserted into table successfully"."<br>";
}
//Closing the connection
mysql_close($conn);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
One problem, you are using html comments in your javascript instead of javascript comments, use //
http://www.jshint.com
Also, It looks like you need to set the check variables as global, since you are validating outside of the function that checks if they are valid.
I don't think you need to put this inside of Validate()
http://www.w3schools.com/js/js_form_validation.asp

HTML form variables aren't POSTed (to PHP) after being handled by JavaScript

Firstly I have searched previous answers and (as far as I'm aware) none of the answers seemed to fit my question - though I'm sure it's been answered somewhere in the past - so forgive me.
I have 3 pages, which work together to submit a HTML form and save it in a MySQL database.
The pages are as follows;
idea.php (contains the form, includes the below idea_js.js file in a <script></script> tag).
idea_js.js (checks the submitted form for errors and submits via ajaxSubmit to ideaSubmit.php)
ideaSubmit.php (assigns POST'd variables and submits to database.)
My problem is that when the form is submitted, ideaSubmit recieves no POST'd variables.
I've come to this conclusion with a check;
if (!empty($_POST)){
echo "empty!"; }
and my page loads (with a bunch of unassigned variable errors and the message);
empty!
Can you fill me in as to why this is happening? Included are the three files.
idea.php:
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
<script type="text/javascript" src="js/idea_js.js"></script>
<!DOCTYPE html>
<html>
<head>
<?php include 'headIncludes.php'; ?>
</head>
<body>
<?php include 'includes/userInterface.php'; ?>
<div id="mainContent">
<div class="mainContentContainer">
<div id="home" >
<section id="content-wrapper">
<br>
<br>
<form id="submit_idea" action ="submitIdea.php" method="POST">
<fieldset>
<legend>Idea submission</legend>
<label for="title">Title</label>
<input type="text" name="title"/>
<br>
<label for="brief">Brief</label>
<input type="text" name="brief"/>
<br>
<label for="problem">Problem</label>
<input type="text" name="problem"/>
<br>
<label for="solution">solution</label>
<input type="text" name="solution"/>
<br>
<label for="audience">audience</label>
<input type="text" name="audience"/>
<br>
<label for="prediction">prediction</label>
<input type="text" name="prediction"/>
<br>
<label for="constraints">constraints</label>
<input type="text" name="constraints"/><br>
<button type="submit" onclick="processIdea();">Submit</button>
<div style="clear:both;"></div>
</fieldset>
</form>
</section>
</div>
</div>
</div>
</body>
</html>
idea_js.js;
$("document").ready(function() {
$("#submit_idea").submit(function() {
processIdea();
return false;
});
});
function processIdea() {
var errors = '';
// Validate title
var title = $("#submit_idea [name='title']").val();
if (!title) {
errors += ' - Please enter a title\n';
}
// Validate brief
var brief = $("#submit_idea [name='brief']").val();
if (!brief) {
errors += ' - Please enter a short idea brief\n';
}
// Validate Problem
var problem = $("#submit_idea [name='problem']").val();
if (!problem) {
errors += ' - Please discribe the problem you want to solve\n';
}
//Validate Solution
var solution = $("#submit_idea [name='solution']").val();
if (!solution) {
errors += ' - Please discribe your solution to the above problem\n';
}
//Validate Audience
var audience = $("#submit_idea [name='audience']").val();
if (!audience) {
errors += ' - Please discribe the audience your solution targets\n';
}
//Validate Prediction
var prediction = $("#submit_idea [name='prediction']").val();
if (!prediction) {
errors += ' - Please discribe the prediction you want to solve\n';
}
//Validate constraints
var constraints = $("#submit_idea [name='constraints']").val();
if (!constraints) {
errors += ' - Please discribe the constraints of your solution\n';
}
if (errors){
errors = 'The following errors occurred:\n' + errors;
alert(errors);
return false;
} else {
// Submit our form via Ajax and then reset the form
$("#submit_idea").ajaxSubmit({success:showResult});
return false;
}
}
function showResult(data) {
if (data == 'save_failed') {
alert('Form save failed, please contact your administrator');
return false;
} else {
$("#submit_idea").clearForm().clearFields().resetForm();
alert('Form save success');
return false;
}
}
submitIdea.php;
<?php
//Starts session
include_once '/includes/db_connect.php';
include_once '/includes/functions.php';
sec_session_start();
if(login_check($mysqli) == true) {
// Retrieve form data
if (!empty($_POST)){
echo "empty!"; }
if(isset($_POST['submit_idea'])){
if(isset($_POST['title'])){ $title = $_POST['title']; }
if(isset($_POST['brief'])){ $brief = $_POST['brief']; }
if(isset($_POST['problem'])){ $problem = $_POST['problem']; }
if(isset($_POST['solution'])){ $solution = $_POST['solution']; }
if(isset($_POST['audience'])){ $audience = $_POST['audience']; }
if(isset($_POST['prediction'])){ $prediction = $_POST['prediction']; }
if(isset($_POST['constraints'])){ $constraints = $_POST['constraints']; }
if (!$title || !$brief || !$problem || !$solution || !$audience || !$prediction || !$constraints) {
echo "save_failed";
return;
}
// Clean variables before performing insert
$clean_title = mysql_real_escape_string($title);
$clean_brief = mysql_real_escape_string($brief);
$clean_problem = mysql_real_escape_string($problem);
$clean_solution = mysql_real_escape_string($solution);
$clean_audience = mysql_real_escape_string($audience);
$clean_prediction = mysql_real_escape_string($prediction);
$clean_constraints = mysql_real_escape_string($constraints);
// $clean_categories_list = mysql_real_escape_string($categories_list);
}
else {
// Perform insert
$now = time();
$user_id = $_SESSION['user_id'];
$mysqli->query("INSERT INTO idea_thread (user_id, time, title, Brief, problem, solution, audience, prediction, constraints) VALUES ('{$user_id}', '{$now}', '{$clean_title}', '{$clean_brief}', '{$clean_problem}', '{$clean_solution}', '{$clean_audience}', '{$clean_prediction}', '{$clean_constraints}')");
// if (#mysql_query($sql, $link)) {
echo "success";
}
// return;
//} else {
// echo "save_failed";
// return;
//}
} else {
echo "How did you get here? Please log in first!";
header("Location: ../signup.php");
exit;
}
?>
Thanks, all help appreciated!

Categories