How to get the text value of a datepicker? - javascript

I am trying to get the text value of a datepicker so that I can store it in a MySQL database.
Here is a sample of my HTML code (index.php):
<div class="col-xl-6">
<input id="datepicker2" placeholder="Date">
</div>
<div class="col-xl-12">
<a href="#form3" class="popup-with-form">
<button type="submit" class="boxed-btn3" onclick="customFunction()">Next</button>
</a>
</div>
Here is the JavaScript code (within index.php):
<script>
function customFunction() {
var DateOfBirth = document.getElementById("datepicker2").value;
if (DateOfBirth != null && DateOfBirth !="") {
$.post("insert.php", {DateOfBirth : DateOfBirth },function(response){
console.log(response);
});
}
}
</script>
Here is the insert.php file code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$Date = isset($_POST['DateOfBirth'])?$_POST['DateOfBirth']:'';
$sql = "INSERT INTO datepick (SinceDate) VALUES ('"$Date"')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The issue I am having is that I am unable to get the text value of the datepicker. Does anyone know a solution to this?

I think the problem of the empty post in your insert.php script is the fact that your JS doesn't properly send the data to the php script. I played a bit with your example on my own dev environment and i managed to make it work.
The only thing i changed in your index.php is that i gave your button an id so i can call it from javascript and i moved the javascript code in a separate file. I've been running a content-security-policy for so long that i just can't leave inline js anymore.
index.php
<div class="col-xl-6">
<input id="datepicker2" placeholder="Date">
</div>
<div class="col-xl-12">
<a href="#form3" class="popup-with-form">
<button id="submit-button" type="submit" class="boxed-btn3">Next</button>
</a>
</div>
<script src="js.js"></script>
I will use native JS and with new ES6 synthax and will also remove your JS from inline event hanlers (better anyway). Also i will not be using the jQuery ajax but native javascript fetch. So i've put your js in a file called js.js
js.js
document.getElementById('submit-button').addEventListener('click', () => {
// pick the value of the input
const dateofBirth = document.getElementById('datepicker2').value;
// same as yours
if (dateofBirth != null && dateofBirth != '') {
// Using the new modern fetch api to send the request
fetch('insert.php', {
headers: {
// This is what was missing from your call
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'post',
// Building the data to send, basically you need a key value pair, so i gave it a 'data' key and value - the value of the input
body: new URLSearchParams({
'date': dateofBirth
})
})
.then(response => response.text())
.then(text => {
// log the response in the console, for debug
console.log(text);
})
}
});
Now, your insert.php file. You are wide open to SQL Injection attack with the current insert, so i have made some changes to include prepared statements.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection, no need to check if it succeeded, we will be extending the error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$Date = isset($_POST['DateOfBirth']) ? htmlspecialchars($_POST['DateOfBirth']) : null;
if ($date !== null) {
// build the sql query for prepared statement
$sql = "INSERT INTO datepick (SinceDate) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $Date);
if ($stmt->execute()) {
echo "New record created successfully";
}
}
$conn->close();
?>

Change the attribute in the button tag, right now is submit, change it for button.
<button type="button" class="boxed-btn3" onclick="customFunction()">Next</button>

Related

Disable the date when the current date count is 8 in ajax,php, mysql

I am trying to disable the particular date whose count of the particular date is 8. In my code the particular date cannot be used after 8 counts..After 8 counts alert box appears. Instead of alert box i have to disable the particular date.. How can i disable the date.. Here is the code.
<input type="date" name="mass_date" id="txtDate" required="required" /></div>
<script>
$(document).ready(function() {
$('#txtDate').change(function(){
var selectedDate = $(this).val();
$.ajax({
type: 'GET',
url: "http://localhost/check_date.php?selectedDate=" +selectedDate,
success: function(data) {
var status= JSON.parse(data);
if((status=="SUCCESS")) {
$('#submitButton').prop('disabled', false);
} else {
alert('Opps! Booking is not available for this day');
}
}
});
});
});
</script>
check_date.php
<?php
error_reporting(E_ALL);
include_once "db.php";
$selectedDate = $_GET['selectedDate'];
$query2=mysqli_query($con,"SELECT COUNT(*) as booking_count FROM shrine_mass WHERE mass_date='$selectedDate'") or die(mysqli_error($con));
$row=mysqli_fetch_array($query2,MYSQLI_ASSOC);
$count = $row['booking_count'];
if($count < 8) {
echo json_encode("SUCCESS");
} else {
echo json_encode("FAIL");
}
As I understand your question, you are looking to prevent the user entering a given date once it has been selected 8 times by other users. Using #Martin's answer, you will disable the date input altogether, and I don't think this is what you are after. I presume you are looking for a solution that would prevent the entry of a 'fully booked' date, but not the input of other dates.
I don't think you can stop any date being selected in a type="date" INPUT. There are attributes to restrict the input to a date range, but not to restrict particular dates
from within a range.
So the only possible solution must involve checking a newly entered date against some data to determine if it can be used. You are currently doing this during your ajax call, and frankly, assuming your application is available to multiple users simultaneously, this is the only viable approach. Any data you might pass to the browser on page load could be rendered 'out of date' seconds later by the actions of another user.
So my answer to your question is No, there is no way to achieve what you want that is better than your current strategy, or some variation of it that references your database.
EDIT: Scroll down!
WARNING You are wide open to SQL Injections (SQLI Attacks). Please make use of Prepared Statements and Parametized queries.
With that said, I will be rewriting your PHP page to follow the guidelines of Prepared Statements and Parametized queries.
As for the jQuery part of your question, I believe what you're looking for is the property function, .prop("disabled", true);. You already used it for your submitButton, except there you enable the button by setting the property to false.
jQuery Exampled, using your code:
$(document).ready(function() {
$('#txtDate').change(function(){
var selectedDate = $(this).val();
$.ajax({
type: 'GET',
url: "http://localhost/check_date.php?selectedDate=" +selectedDate,
success: function(data) {
var status= JSON.parse(data);
if((status=="SUCCESS")) {
$('#submitButton').prop('disabled', false);
} else {
$('#txtDate').prop("disabled", true);
}
}
});
});
});
Your PHP page, using Prepared Statement and Parametized query:
<?php
// Your input GET variable
$selectedDate = $_GET['selectedDate'];
// DB variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Declare the query
$sql = "SELECT COUNT(*) as booking_count FROM shrine_mass WHERE mass_date = ?";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $selectedDate);
// Execute the query
$stmt->execute();
// Bind result variable and fetch value
$stmt->bind_result($booking_count);
$stmt->fetch();
// Close connection
$stmt->close();
$conn->close();
if($booking_count < 8) {
echo json_encode("SUCCESS");
} else {
echo json_encode("FAIL");
}
?>
Snippet example, displaying the .prop("disabled", true); in action:
$(document).ready(function() {
$('#txtDate').prop("disabled", true);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row d-flext justify-content-center">
<div class="col-md-4">
<input type="date" name="mass_date" id="txtDate" class="form-control" required="required" />
</div>
</div>
Codepen Example here.
EDIT:
Since you wanted to disable a specific date in particular depending on the count of that date in your database, then I would recommend using either jQuery datepicker or Bootstrap datepicker. I will move forward using jQuery datepicker.
More about jQuery datepicker here.
First you will need to query your database for the dates where your logic applies, i.e. where the date occurs more than 8 times.
Example:
SELECT
mass_date
FROM
mass_table
GROUP BY
mass_date
HAVING
COUNT(*) > 8;
DB Fiddle here.
The idea is that you create a JavaScript array, which contains the dates you want to disable. You then want to populate this array with the dates that fit your logic.
This is how your main page could look like:
<?php
// DB variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Declare the query
$sql = "SELECT mass_date FROM mass_table GROUP BY mass_date HAVING COUNT(*) > 8";
// Prepare
$stmt = $conn->prepare($sql);
// Execute the query
$stmt->execute();
// Get result of query
$result = $stmt->get_result();
// Close connection
$stmt->close();
$conn->close();
?>
<script>
// The array containing the dates to be disabled in the datepicker
let disabledDates = [];
<?php
// Loop through our query results
while($data = $result->fetch_assoc()) {
?>
// Push the dates into the disabledDates array
disabledDates.push("<?php $data['mass_date']; ?>");
<?php
}
?>
// jQuery datepicker function
$('#txtDate').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ disabledDates.indexOf(string) == -1 ]
}
});
</script>
<div class="row d-flext justify-content-center">
<div class="col-md-4">
<input type="date" name="mass_date" id="txtDate" class="form-control" required="required" />
</div>
</div>
Codepen Example of jQuery datepicker disabled dates here.

Securely communicate with mysql server (MariaDB) using javascript and php (NO jQuery)

I am trying to achieve two things:
(1) Get text from a contenteditable div, use javascript to send that text to php, use php to send that data to a MySQL database and save it
(2) retrieve the saved data/text and reinsert it into a contentedtiable div
All of this whilst NOT using jQuery
What I've got so far:
index.html
<body>
<div contenteditable="true" id="editable"></div>
<button onClick="send_data();">Save text</button>
<button onClick="retrieve_data();">Get text</button>
</body>
javascript.js
function send_data() {
var php_file = "connection.php";
var http_connection = new XMLHttpRequest();
http_connection.open("POST", php_file, true);
http_connection.onreadystatechange = function() {
if(http_connection.readyState == 4 && http_connection.status == 200) {
alert(http_connection.responseText);
}
}
http_connection.send(document.getElementById('editable').innerText);
}
function retrieve_data() {
// I do not know what to put here
}
connection.php
<?php
$servername = "localhost";
$username = "mysql_user";
$password = "secure_password";
$dbname = "some_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
if(!conn) {
echo 'No connection';
}
if(!mysqli_select_db($conn,'some_database')) {
echo "No database";
}
$some_val = $_GET['text']
$sql = "SELECT text FROM some_database";
$result = $conn->query($sql);
echo $result;
$conn->close();
?>
Edit: what my code fails to do is to upload text as well as recieve text.
Some problems in the js:
http_c is not defined
readyState is spelled incorrectly
the send method needs to be outside the onreadystatechange callback
Once those things are corrected, program should give different, which is not to say expected, result.
Other things:
The js is sending a 'POST' request. The php is looking for $_GET["text"] which will give undefined error. I'm speculation this $sql = "SELECT text FROM some_database"; will fail (if it reaches that line) unless there is a table in the database named "some_database".
Suggest, for starters, get the ajax working by short-circuiting the code in connection.php to something like
echo "You are here";
exit;
Then gradually working forward between the js and the php until programs give you what you want.

How to pass a value of page to other page without submit button

The page passed on the infoCheck.php for the POST.
First of all, I'm going to move on as follows.
<form id="theForm" method = "POST" action = "infoCheck.php"
<input type = "hidden" name = "name" value = "100">
<input type = "submit" value = "Input">
</form>
However, before submit, only the value corresponding to the name must be sent as soon as the page opens. There must be away. Even if I searched, I could only see how to use submit...
What should I do?
Try this if you use jQuery:
HTML
<form id="theForm" method="POST" action="infoCheck.php">
<input type="hidden" name="name" value="100">
<input type="submit" value="Input">
</form>
jQuery:
<script type="text/javascript">
$(function() {
$("#theForm").submit();
});
</script>
My guess is you want to submit the form as soon as the page loads. Here's what you can do using JS (as per the tags from your question):
HTML
<form id="myForm" method="POST" action="infoCheck.php">
<input type="hdden" name="name" value="100">
<input type="submit" value="Input">
</form>
Note the added id="myForm".
Javascript
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('myForm').submit();
});
Try this On window load submit your form.
window.onload = function(){
document.forms['form_name'].submit();
}
You can also use SESSION variable to use data globally.
I recommend you to use PDO to prevent SQL injection.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Here is PDO example with prepared statement:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Based on my understanding of your question, I will explain it to you. Instead of using submit, you can use the code below.
<script>
jQuery('form').submit();
</script>
I think it can pass the "name" to infoCheck.php

PHP Javascript Mysql Insert

I am trying to use java-script prompt to insert values into MySQL. I have a html file and a php file.
The html files saved as Test.html:
<button onclick="myFunction()">Create Project</button>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project });
}
}
</script>
The conn.php:
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The conn.php works perfectly and inserts values if I remove the post parameter.
For example, instead of this:
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if i use:
$proj = "NewProject";
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
NewProject gets inserted into the database.
I am not sure if I am missing something in my index.html which is not posting the value in the prompt to php script. I have tried echo $_POST['project']; instead of inserting into MySQL. The echo is missing.
I have run your given code, it runs only i have added the jquery link above script code
Please check this correction,
<button onclick="myFunction()">Create Project</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project },function(response){
console.log(response);
});
}
}
</script>
and also i have added isset() function with $_POST param in conn.php file
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = isset($_POST['project'])?$_POST['project']:'';
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Get value from select and compare with the DB to obtain a price

I'm using a select to choose from different products, then with that value I perform a DB query consult to obtain the price of the product and then set a input tag with it.
<section id="products">
quantity: <input type="number" id="quantity"><br><br>
<section id="selectProd">
<?php
$query = $conn->query("SELECT name FROM Products ORDER BY name");
?>
Product: <select id="comProduct" class="comProduct">
<?php while ($option = $query->fetch_object()) { ?>
<option><?php echo $option->name; ?></option>
<?php } ?>
</select>
<script>
$(document).on("ready",function(){
$("#comProduct").on("click", function(){
var value = $("#comProduct option:selected").text();
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "BERAKA";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$valuephp = $_GET['value'];
$query = $conn->query("SELECT price FROM products where name='$valorphp'");
?>
document.getElementById("ppu").value = "<?php $query->fetch_object(); ?>";
});
});
</script>
</section> <br>
Price per unit: <input type="text" id="ppu" >
</section>
Don't know why it's not working, Please help
You are vulnerable to sql injection attacks. Sit back and relax - your problem will become moot when your server gets pwn3d.
As well, your code is highly flawed:
document.getElementById("ppu").value = "<?php $query->fetch_object(); ?>";
Your fetch call doesn't DO anything useful. fetch will RETURN an object, but since you don't capture that object or output it in any way, the DB row data will simply be lost. Even if the fetch call DID by some miracle do output, you can't just dump a PHP object into a Javascsript code context.
You need something more like this:
<?php
...
$row = $query->fetch_object();
$price = $row->price;
?>
document.getElementById('ppu').value = <?php echo json_encode($price); ?>;
Never EVER dump text from PHP directly into a JS context without using json_encode(). You're at risk of dumping invalid text into the JS code block, which will trigger a JS syntax error, and kill the entire <script> block that this bad code is in. Always use json_encode() so that no matter what you're dumping into the JS code, that value will be VALID javascript.

Categories