All variables appear to not be POSTing - javascript

I am currently working on a website that takes information from a form in a Bootstrap modal (addStudentModal.php) and sends it to createRecord.php via a jQuery script (dataManageFunctions.js). When the data reaches createRecord.php, it gets inserted into a MySQL database. For debugging purposes, instead of executing the INSERT command, I just had it echo out the variables that were POSTed to it. I discovered that all but 2 fields are not getting posted and I have absolutely no idea why. Specifically, gYear and lName are echoing blank values. I've checked spelling and tried to ensure that the variable names and IDs are identical. Maybe I'm missing something, I don't know.
The files in question are below:
addStudentModal.php
<!-- ADD STUDENT Modal -->
<div class="modal fade" id="addStudentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Student</h4>
</div>
<div class="modal-body">
<div id="additionResults"></div>
<!-- EDIT form-->
<form role="form" action="" method="" id="addStudentForm">
<div class="form-group">
<label for="studentID">Student ID Number:</label>
<input type="text" class="form-control" name="studentID" id="studentID" placeholder="123456">
</div>
<div class="form-group">
<label for="lastName">Graduation Year:</label>
<input type="text" class="form-control" name="gradYear" id="gradYear" placeholder="0">
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="Doe">
</div>
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="John">
</div>
<div class="form-group">
<label for="serHrsToDate">Service Hours to Date:</label>
<input type="text" class="form-control" name="serHrsToDate" id="serHrsToDate" placeholder="0.00">
</div>
<div class="form-group">
<label for="internToDate">Internships to Date:</label>
<input type="text" class="form-control" name="internToDate" id="internToDate" placeholder="0">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" name="save" value="save"> Add Student </button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- END ADD STUDENT MODAL -->
dataManageFunctions.js - only relevant snippet is copied
// JS for Add Student
$(function() {
$("#addStudentForm").bind('submit',function() {
var sID = $('#studentID').val();
var gYear = $('#gradYear').val();
var lName = $('#lastName').val();
var fName = $('#firstName').val();
var servHrs = $('#serHrsToDate').val();
var interns = $('#internToDate').val();
$.post('assetScripts/editInfo/createRecord.php',{sID:sID, gYear:gYear, lName:lName, fName:fName, servHrs:servHrs, interns:interns}, function(data){
$("#additionResults").html(data);
});
return false;
});
});
createRecord.php
<?php
include("../../config/db-connect.php");
$errExist = false;
if(isset($_POST['sID'])){
$safeID = intval($_POST['sID']);
if(!preg_match("/^.*(?=.{6,})(?=.*[0-9]).*$/", $safeID)){
$errExist = true;
}
} else {
$errExist = true;
}
if(isset($_POST['gYear'])){
$safeYear = intval($_POST['gYear']);
if(!preg_match("/^.*(?=.{4,})(?=.*[0-9]).*$/", $safeYear)){
$errExist = true;
}
} else {
$errExist = true;
}
if(isset($_POST['lName'])){
$safeLastName = mysql_real_escape_string(filter_var($_POST['lName'], FILTER_SANITIZE_STRING));
} else {
$errExist = true;
}
if(isset($_POST['fName'])){
$safeFirstName = mysql_real_escape_string(filter_var($_POST['fName'], FILTER_SANITIZE_STRING));
} else {
$errExist = true;
}
if(isset($_POST['servHrs'])){
$safeHrs = floatval($_POST['servHrs']);
} else {
$errExist = true;
}
if(isset($_POST['interns'])){
$safeInterns = intval($_POST['interns']);
} else {
$errExist = true;
}
// check if an error existed when checking inputs
if(!$errExist){
echo '<div class="alert alert-success" role="alert"><strong>Success!</strong></div>';
echo $_POST['sID'].', '.$_POST['gYear'].', '.$_POST['lName'].', '.$_POST['fName'].', '.$_POST['servHrs'].', '.$_POST['interns'].'<br>';
echo $safeID.', '.$safeYear.', '.$safeLastName.', '.$safeFirstName.', '.$safeHrs.', '.$safeInterns.'<br>';
echo $errExist.'<br>';
} else {
echo '<div class="alert alert-danger" role="alert"><strong>Failure!</strong></div>';
echo $_POST['sID'].', '.$_POST['gYear'].', '.$_POST['lName'].', '.$_POST['fName'].', '.$_POST['servHrs'].', '.$_POST['interns'].'<br>';
echo $safeID.', '.$safeYear.', '.$safeLastName.', '.$safeFirstName.', '.$safeHrs.', '.$safeInterns.'<br>';
echo $errExist.'<br>';
}
?>
It's also worth noting that I also had it echo isset(variable name) which returned 1 (true) for every variable. And yes, I ensured that the values I entered to test followed every condition so $errExist shouldn't have been set true.

Related

Cant get data from form sent to mysql database

Can someone help, I cant seem to get the data colleted from the form to be sent to the mysql database.
I am very new to coding and I cant seem to figure out why the form data is not being sent to the mysql database table.
Please any help would be muchly appricated.
once I press submit the page closes than refreshs without any errors, but the data has not been sent to the database table.
Please see code below.
<?php include'inc/header.php'; ?>
<div class="container">
<center>
<h2 style="color: #odc16f">Shipped</h2>
<hr>
</center>
<center>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addEmpModal">
Add Order
</button>
</center>
<!-- Modal -->
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria- hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Order</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter Name</label>
<input class="form-control" type="text" name="customer" id="customer" placeholder="Enter Name">
<label id="lbcustomer" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Date</label>
<input class="form-control" type="date" name="date" id="date" placeholder="Enter Date">
<label id="lbdate" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Invoice</label>
<input class="form-control" type="number" name="invoice" id="invoice" placeholder="Enter Invoice">
<label id="lbinvoice" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter eBay</label>
<input class="form-control" type="number" name="ebay" id="ebay" placeholder="Enter eBay">
<label id="lbebay" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Shipped</label>
<input class="form-control" type="text" name="shipper" id="shipper" placeholder="Enter Shipped">
<label id="lbshipper" style="color:red"></label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="save">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.container ends here -->
<?php
include'inc/footer.php';
?>
<script>
$(document).ready(function() {
$(document).on('click', '#save', function() {
var customer = $("#customer").val();
var date = $("#date").val();
var invoice = $("#invoice").val();
var ebay = $("#ebay").val();
var shipper = $("#shipper").val();
if (customer == "") {
$("#lbcustomer").html("Enter Name");
} else if (date == "") {
$("#lbdate").html("Enter Date");
} else if (invoice == "") {
$("#lbinvoice").html("Enter Invoice");
} else if (ebay == "") {
$("#lbebay").html("Enter eBay");
} else if (shipper == "") {
$("#lbshipper").html("Enter Shipper");
} else {
$.ajax({
url: "save_data.php",
type: "post",
data: {
customer: customer,
date: date,
invoice: invoice,
ebay: ebay,
shipper: shipper
},
success: function(data) {
alert("Order Has Been Successful");
$("#addEmpModal").modal('hide');
location.reload();
}
});
}
});
});
</script>
Please see below the save_data.php code
<$php
include 'config/config.php';
global $con;
$customer = $_POST['customer'];
$date = $_POST['date'];
$invoice = $_POST['invoice'];
$ebay = $_POST['ebay'];
$shipper = $_POST['shipper'];
$save_data = "INSERT INTO orders(customer, date, invoice, ebay, shipper)VALUES('$customer','$date','$invoice','$ebay','$shipper')";
$result = mysqli_query($con, $save_data);
and below is the config.php code.
<?php
$con = mysqli_connect("localhost","root","Password","shippedorders");
if (!$con) {
echo "Failed to connect to MySQL: ".mysqli_connect_error($con);
}
you are missing
action in :
<form action="save_data.php" method="post">
or are you running your php in same page as html ? or you

validations not working for checking empty fields

validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
my Jquery code:
var assign_report_form = $('#assign_report_form');
$('#create').on('click', function(){
var source_id = $('#src_id option:selected').text();
var username = $('#username').val();
var email = $('#email').val();
var query_name = $('#query_name').val();
var channel = $('#channel').val();
var condition = $('#condition').val();
if((source_id =="")||(username == "")||(email == "")||(query_name == "")||(channel == "")||(condition == "")){
$('#error_message').show().delay(5000).fadeOut();
}
else{
// var data = {'source_id': source_id,
// 'username':username,
// 'email':email,
// 'query_name':query_name,
// 'channel': 'email',
// 'condition': condition
// }
// console.log('data',data)
$.ajax({
url:'/add_report/',
type:'POST',
data:{'source_id': source_id,
'username':username,
'email':email,
'query_name':query_name,
'channel': 'email',
'condition': condition
},
success: function(res){
if(res =='success')
// $('#Add_modal').modal('toggle');
// $('#success_message').show().delay(5000).fadeOut();
// $("input[type=text],input[type=email],select").val("");
// }
// else{
// $('#error_message').show().delay(5000).fadeOut();
// }
console.log('form saved..')
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
}
})
event.preventDefault();
}
});
});
validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
Here is the html code:
<button type="button" data-toggle="modal" data-target="#Add_modal" class="btn btn-secondary" id="add_row" style="margin-right: 10px;">Add</button>
<!-- Add New Report Model -->
<div class="modal fade" id="Add_modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Assign New Report</h3>
</div>
<div class="modal-body">
<!-- content goes here -->
<div class="alert alert-warning" id="#error_message" style='display:none;'>
<strong>Error!</strong>Please fill Empty fields
</div>
<form id="assign_report_form">
{% csrf_token %}
<!-- <input type="hidden" id="src_id" value="{{ source_id }}"/> -->
<div class="form-group">
<label for="username">Source ID</label>
<select id="src_id" class="form-control" name="source_id">
{% for source in sources %}
<option value="{{source_id}}" selected>{{ source.id }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="queryname">Query_Name</label>
<input type="text" class="form-control" name="query_name" id="query_name" placeholder="Query_Name">
</div>
<div class="form-group">
<label for="channel">Channel</label>
<input type="text" class="form-control" name="channel" id="channel" placeholder="Channel">
</div>
<div class="form-group">
<label for="condition">Condition</label>
<input type="text" class="form-control" name="condition" id="condition" placeholder="Condition">
</div>
<input type="button" id="create" class="btn btn-primary" value='Create'/>
</form>
</div>
</div>
</div>
In your html code you need to omit the "#" in id="#error_message" and write id="error_message" instead.
You should always use $('<dropdown selector>').val();, like in your case.
var source_id = $('#src_id option').val();
This will work always for select elements.

JavaScript - Taking user input and using in calculation to validate value

I have a modal that allows users to 'refuel' by filling out a form where they can input the amount of fuel to add, however the maximum fuel amount is 180 litres, so if the existing fuel is 170 litres (the existing fuel value will be retrieved from a database), and the user tries to add 20 litres, it should produce an error. I've got some code already, but it's not producing the error. If anyone could point out the issue it would be greatly appreciated.
$(document).ready(function() {
$('#fuel').blur(function() {
if (!ValidateFuel()) {
e.preventDefault();
}
});
$('#auth_form8').on('submit', function(e) {
if (!ValidateFuel()) {
e.preventDefault();
}
});
});
function ValidateFuel() {
var IsValid = false;
var fuel_to_add = $('#fuel').val();
var current_fuel = '100'; // this value will be retrieved from database
var fuel_once_added = Number(current_fuel) + Number(fuel_to_add);
if (fuel_once_added > 180) {
$('#alertInvalidFuel').show();
IsValid = false;
} else {
$('#alertInvalidFuel').hide();
IsValid = true;
}
return IsValid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-success" role="button" data-target="#confirm-refuelG-EEGU" data-toggle="modal"><em class='fa fa-plus'></em></a>
<div id="confirm-refuelG-EEGU" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Fuel G-EEGU</h4>
</div>
<div class="modal-body">
<form name="auth_form8" id="auth_form8" method="post" action="action_refuel.php">
<p>This action cannot be undone.</p>
<hr>
<input class="form-control" id="aircraft_id" name="aircraft_id" value='1' type="hidden">
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">
Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
<div style="display:none;" class="alert alert-danger" id="alertInvalidFuel">
<p>Fuel will exceed 180 litres.</p>
</div>
<hr>
<div class="form-group has-feedback" name="auth_code8" id="auth_code8">
<label for="auth_code8" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input8" autocomplete="new-password" name="refuel_auth_code" type="password" required>
<span class="form-control-feedback glyphicon" id="iconBad8"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-success">Add Fuel</button>
</div>
</form>
</div>
</div>
</div>
JSFiddle Demo
The problem is here:
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
Your div has id="fuel" and so does the input. Remove the id from the div or make it unique. Also, there is no name attribute for div elements, you should remove that as well.

Can't access DOM from SCM Music Player

I am building a website using SCM Music Player (an open source web player), and I would like to use the "finish" callback to modify my DOM when the music stops. I can access this callback and execute a "console.log()", but I can't access DOM... I've noticed that this script uses Knockout library, but I don't know how it works and if it is necessary... Here is my code from scm.js:
finish = function(){
//repeat one start again, otherwise next song
if(repeatMode()==2) start();
else {
console.log('Next son de scm.js :');
var div = ko.observable($('#ajouterSon').attr('role'));
console.log('Div: ' + div);
next();
}
};
And the kind of changes I do when I play a song :
$('.musiqueLink').on('click', function(event) {
console.log('clic musique - last id = ' + lastidmusique);
event.preventDefault();
if(lastidmusique != null)
document.getElementById('row'+lastidmusique).setAttribute("class", "row");
document.getElementById('row'+$(this).attr('data-idmusique')).setAttribute("class", "row highlighted");
SCM.play({title:$(this).attr('data-titre'),url:$(this).attr('data-lien')});
lastidmusique = $(this).attr('data-idmusique');
});
The dom which contains 'ajouterSon' :
<body style=" background-image: url('imgs/backgrnd.jpg'); background-size: 100% 100%; background-repeat:no-repeat; background-attachment:fixed;">
<div id="ajouterSon" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h1 class="text-center">Ajouter un son</h1>
<?php
?>
</div>
<div class="modal-body">
<form class="form col-md-12 center-block" id="ajoutSon">
<div class="form-group">
<input type="text" title="Titre du son" class="form-control input-lg" placeholder="Titre" id="titre">
</div>
<div class="form-group">
<input type="text" title="Auteur du son" class="form-control input-lg" placeholder="Artiste" id="artiste">
</div>
<div class="form-group">
<label for="genre">Style</label>
<div class="form-group">
<select class="selectpicker" multiple id="genre">
<?php
$genres = $mysqli->query("SELECT idgenre, nom FROM GENRE");
while($row = $genres->fetch_array())
$rows[] = $row;
mysqli_free_result($genres);
foreach($rows as $row)
{
$styles = $mysqli->query("SELECT idstyle, nom FROM STYLE WHERE GENRE = ".intval($row['idgenre']));
while($rowStyles = $styles->fetch_array())
$rowsStyles[] = $rowStyles;
echo "<optgroup label=\"".$row['nom']."\">";
foreach ($rowsStyles as $rowStyles)
echo "<option value=\"".$rowStyles['idstyle']."\">".$rowStyles['nom']."</option>";
echo "</optgroup>";
mysqli_free_result($styles);
unset($rowsStyles);
}
unset($rows);
?>
</select>
</div>
</div>
<div class="form-group">
<input type="text" title="Décris ton son" class="form-control input-lg" placeholder="Description" id="description">
</div>
<div class="form-group">
<input type="url" title="Lien Youtube/Soundcloud" class="form-control input-lg" placeholder="Lien Youtube/Soundcloud" id="lien">
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" type="submit" id="submit">Ajouter</button>
</div>
</form>
</div>
<div class="modal-footer">
<div class="col-md-12">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Annuler</button>
</div>
</div>
</div>
</div>
</div>
...
</body>
I precise that I have placed my include balise for the JS just above the end of the body.
Thank you for your help,
Théo

How to keep a user logged if checkox is checked

I'm making a login system using modal dialog from bootstrap 3 and im adding a function to keep the user logged in if they check the checkbox in the modal dialog.
I want to keep a user logged in, even he/she refreshes or closes the browser.
index.php
<div class="container" id="myLogin">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title">PLEASE ENTER YOUR EMAIL ADDRESS AND PASSWORD TO LOG IN.</h5>
</div>
<div class="modal-body">
<div id="show" class="lalert lalert-warning"></div>
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input type="text" name="lemail" id="lemail" value="<?php echo $unm ?>" class="form-control" placeholder="Enter Email Address..." />
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input type="password" name="lpassword" id="lpassword" value="<?php echo $pwd ?>" class="form-control" placeholder="Enter Password..." />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="checkbox" name="chkbox" value="staylogged" class="checkbox-inline" />
<label> Keep me logged in</label> <b>|</b>
Forgot your password?
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="login" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-user"></span> Login</button>
<button type="button" class="btn btn-info show-page modal-btn" data-page="Signup" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-list-alt"></span> Register</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
script:
jQuery(function () {
$("#lemail").val($.cookie("unm"));
$("#lpassword").val($.cookie("pwd"));
});
$("#email").val($.cookie("unm") || "");
$("#lpassword").val($.cookie("pwd") || "");
php:
<?php
session_start();
$unm = $_POST['lemail'];
$pwd = $_POST['lpassword'];
?>
In order to get session_start(); to work,
you need to add variables to the $_SESSION array. Change you PHP code to this:
<?php
//Start the session
session_start();
//ALWAYS check if a $_POST variable is set before using it.
if(isset($_POST['lemail'])){
$unm = $_POST['lemail'];
} else {
//Error Code Goes Here
}
if(isset($_POST['lpassword'])){
$pwd = $_POST['lpassword'];
} else {
//Error Code Goes Here
}
//Set SESSION vars
$_SESSION["unm"] = $unm;
$_SESSION["pwd"] = $pwd;
When you want to check if they are logged in, use this code
session_start();
if(isset($_SESSION["unm"]) && isset($_SESSION["pwd"])){
$loggedIn = true;
//At this point you can also check your database if they are actually a user for extra security
} else {
$loggedIn = false;
}
Please, make sure your cookies is going save or not.
And another thing is make sure of expire time.
set coockies in PHP, like :
setcookie(
'pageVisits', // Name of the cookie, required
$visited, // The value of the cookie
time()+7*24*60*60, // Expiration time, set for a week in the future
'/', // Folder path the cookie will be available for
'demo.tutorialzine.com' // Domain to which the cookie will be bound
);
And Read coockies in JS:
$(document).ready(function(){
// Getting the kittens cookie:
var str = $.cookie('pageVisits');
// str now contains the value of $visited
});

Categories