$_POST value returns blank/empty - php

I do have a form where the user can retrieve the data depending on the dates selected. Here's what I have:
<form class="form" method="post">
<div class="form-row">
<div class="form-group col-md-2 col-5">
<label class="col-form-label col-form-label-sm" for="From">From</label>
<input type="date" class="form-control" id="fromDate" name="fromDate" value="<?php echo (new DateTime('first day of this month'))->format('Y-m-d');?>">
</div>
<div class="form-group col-md-2 col-5">
<label class="col-form-label col-form-label-sm" for="To">To</label>
<input type="date" class="form-control" id="toDate" name="toDate" value="<?php echo (new DateTime('today'))->format('Y-m-d');?>">
</div>
<div class="form-group col-md-1 col-2">
<label class="col-form-label col-form-label-sm text-white" for="Search">Search</label>
<input type="button" class="btn btn-success btn-block" id="submit" name="submit" value="Submit" onclick="getResult()">
</div>
</div>
</form>
<div id="data_result"></div>
On the same page, I have a script below:
<script>
function getResult(){
var fm = $('#fromDate').val();
var to = $('#toDate').val();
$.ajax({
method: 'POST',
url: 'chart-data/card-sales.php',
data: { fm:fm, to:to },
success: function(data) {
$('#data_result').html(data);
}
});
}
</script>
And finally, my chart-data/card-sales.php file:
<?php
// db settings
$hostname = 'localhost';
$username = 'root';
$password = 'password';
$database = 'accounts';
// db connection
$con = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($con));
$fm = '';
$to = '';
if(isset($_POST['fromDate'],$_POST['toDate']))
{
$date1 = strtr($_POST['fromDate'], '/', '-');
$fm = date('Y-m-d',strtotime($date1));
$date2 = strtr($_POST['toDate'], '/', '-');
$to = date('Y-m-d',strtotime($date2));
} else {
var_dump($_POST);
}
echo'<div id="data_result">
<h6>
<span class="text-danger">'.$fm.'</span> to
<span class="text-danger">'.$to.'</span>
</h6>';
$sql="SELECT * FROM sales WHERE date >='$fm' and date <= '$to'";
foreach ($con->query($sql) as $row) {
echo'//table contents';
};
echo '</div>';
?>
The thing is, $fm and $to returns an empty value (1970-01-01) that is why I couldn't get the proper data I need while the var_dump($_POST); returns array(2) { ["fm"]=> string(10) "2021-01-01" ["to"]=> string(10) "2021-01-26" }. So I think the main problem here is that I cannot get the input value from my form. Why is that so?

The problem is that you're not using the correct indexes on $_POST.
You should use the same indexes that you sent in the ajax: fm and to.
Change this:
if(isset($_POST['fromDate'],$_POST['toDate']))
{
$date1 = strtr($_POST['fromDate'], '/', '-');
$fm = date('Y-m-d',strtotime($date1));
$date2 = strtr($_POST['toDate'], '/', '-');
$to = date('Y-m-d',strtotime($date2));
} else {
var_dump($_POST);
}
To this:
if(isset($_POST['fm'], $_POST['to']))
{
$date1 = strtr($_POST['fm'], '/', '-');
$fm = date('Y-m-d',strtotime($date1));
$date2 = strtr($_POST['to'], '/', '-');
$to = date('Y-m-d',strtotime($date2));
} else {
var_dump($_POST);
}
P.S: Yo should take a look about SQL injection and prepared queries as #Strawberry suggested.
I encourage you to change to an object-oriented aproach using PDO

As you send in your ajax call, data: {fm: fm, to: to} this is what to use.
Try to change:
if (isset ($_POST['fromDate'], $_POST['toDate']))
{
$date1 = strtr($_POST['fromDate'], '/', '-');
...
$date2 = strtr($_POST['toDate'], '/', '-');
...
}
by
if (isset ($_POST['fm'], $_POST['to']))
{
$date1 = strtr($_POST['fm'], '/', '-');
...
$date2 = strtr($_POST['to'], '/', '-');
...
}

Related

Date is being sent as 0000-00-00 and returned as 11/30/-0001 when I use SQL update statement

For some reason when I edit the the date it's being sent as 0000-00-00 to the database. The wrest of the update is working as expected. I have the db rows for the dates set on type: date, default: none, and null: no.
Also tried to remove the values for the date inputs, that didn't do anything either. Please help, thank you!
<?php
include 'db.php';
$WAGE = 14;
$TAX = 0.01;
$SS = 0.062;
$MEDI = 0.0145;
$GOAL = 0.75;
if($_SERVER['REQUEST_METHOD'] === "POST") {
// Variables
$id = htmlspecialchars($_POST['id']);
$begDate = htmlspecialchars($_POST['date1']);
$endDate = htmlspecialchars($_POST['date2']);
$hours = htmlspecialchars($_POST['hours']);
$total = number_format($hours * $WAGE, 2, '.', '');
$taxDeducted = number_format($total * $TAX, 2,'.', '');
$SSDeducted = number_format($total * $SS, '2', '.', '');
$MEDIDeducted = number_format($total * $MEDI, '2', '.', '');
$deducted = number_format($taxDeducted + $MEDIDeducted + $SSDeducted, 2, '.', '');
$total -= number_format($deducted, 2, '.', '');
$save = number_format($GOAL * $total, 2, '.', '');
$date = $_POST['date1'];
// SQL
$sql = "UPDATE hours SET begDate=$date, endDate=$endDate, hours=$hours, deducted=$deducted, save=$save, total=$total WHERE id=$id;";
// EXECUTE
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
<?php
include 'header.php';
include 'db.php';
if(isset($_GET['id'])) :
$id = $_GET['id'];
$sql = "SELECT * FROM hours WHERE id=$id;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $res) :
$begDate = $res['begDate'];
$endDate = $res['endDate'];
$hours = $res['hours'];
endforeach;
?>
<div class="container form bg-light p-5">
<h1 class="text-center my-5">Add a week</h1>
<form action="editForm.php" method="post">
<input type="hidden" name="id" value="<?= $id; ?>" id="id">
<div class="row">
<div class="form-group col-md-5">
<input type="date" name="date1" id="date1" value="<?=$begDate;?>" class="form-control" required>
</div>
<div class="col-md-2 text-center">
<h3>TO</h3>
</div>
<div class="col-md-5 form-group">
<input type="date" name="date2" id="date2" value="<?=$endDate;?>" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-md-3 form-group mx-auto mt-5">
<input class="form-control" value="<?= $hours;?>" type="float" name="hours" id="hours" placeholder="Hours this period" required>
</div>
</div>
<div class="row text-center mt-5">
<div class="form-group col-md-3 mx-auto">
<input type="submit" value="SUBMIT" name="submit" class="btn btn-secondary">
</div>
</div>
</form>
</div>
<?php endif; ?>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script>
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'editForm.php',
method: 'post',
data: $('form').serialize()
})
.done(function(res, status) {
if(status == 'success') {
window.location.href = 'index.php';
}
})
.fail(function(res, status) {
if(status == 'error') {
console.log('error');
}
});
})
</script>
<?php include 'footer.php'; ?>

PHP + MySQL - Autocomplete from database not getting data from table

I'm having a small college project about discussion room service. Right now I'm being tasked to implement autocomplete feature of name that orders it. I already google some tutorials. I'm not sure what went wrong, when i try to type a name, there's no data being typed ahead.
Here's my form code:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$name = "pinjamruang";
$koneksi = mysqli_connect($host, $user, $pass, $name);
//Periksa apakah koneksi berhasil
if(mysqli_connect_errno()){
echo "Error: ";
echo mysqli_connect_error();
echo "<br /> Error Code: ";
echo mysqli_connect_errno();
die();
}
$sql = "SELECT * FROM ruangan
WHERE id = $_GET[id]";
$hasil = mysqli_query($koneksi,$sql);
$row = mysqli_fetch_assoc($hasil);
$sql2 = "SELECT * FROM shift
WHERE id = $_GET[shift]";
$hasil2 = mysqli_query($koneksi,$sql2);
$row2 = mysqli_fetch_assoc($hasil2);
?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#typeahead" ).autocomplete({
source: 'typeaheads.php';
});
});
</script>
<h1> Konfirmasi Pemesanan Ruang <?php echo $row['kode']; ?></h1><br>
<form class="form-horizontal" action="process/process-order-ruang.php" method="post">
<div class="form-group">
<label for="inputNamaPemesan" class="col-sm-2 control-label">Nama</label>
<div class="col-sm-10">
<input type="text" name="nama_pemesan" class="form-control" id="typeahead" placeholder="Nama Pemesan">
</div>
</div>
<div class="form-group">
<label for="inputKeperluan" class="col-sm-2 control-label">Keperluan</label>
<div class="col-sm-10">
<select name="keperluan" class="form-control" id="inputKeperluan">
<option value="Diskusi Belajar">Diskusi Belajar</option>
<option value="Diskusi Tugas">Diskusi Tugas</option>
<option value="Dokumentasi">Dokumentasi</option>
<option value="Lain-lain">Lain-lain</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputWaktu" class="col-sm-2 control-label">Waktu</label>
<div class="col-sm-10">
<input type="text" class="col-sm-5" name="waktu" value="<?php $row2['shift'];
$timestamp = strtotime($row2['shift']);
$waktuk = date('H.i A', $timestamp);
$int = (int)$waktuk;
echo $int; ?>:00" disabled> - <input type="text" class="col-sm-5"value="<?php $row2['shift'];
$timestamp = strtotime($row2['shift']);
$waktuk = date('H.i A', $timestamp);
$int = (int)$waktuk;
echo $int+2; ?>:00" disabled>
</div>
</div>
<?php $shift = $_GET['shift'];
$ruangan = $_GET['id'];?>
<input type="hidden" value="<?php $int2 = (int)$shift;?>" name="shift">
<input type="hidden" value="<?php $int3 = (int)$ruangan;?>" name="ruangan">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Pesan</button>
</div>
</div>
</form>
and here is my code which should return json data from my table
<?php
$host = "localhost";
$user = "root";
$pass = "";
$name = "pinjamruang";
$koneksi = mysqli_connect($host, $user, $pass, $name);
//connect with the database
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $koneksi->query("SELECT * FROM user
WHERE nama LIKE '%".$searchTerm."%' ORDER BY nama ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['nama'];
}
//return json data
echo json_encode($data);
?>
Any help would be much appreciated. Thanks a lot!
Use below code in script. remove semicolon from source. You can use colon for other parameters.
<script>
$(function() {
$( "#typeahead" ).autocomplete({
source: 'typeaheads.php'
});
});
</script>

Form Data does not post duplicate data

I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},

Inserting data from scope to PHP variable with ajax request

I'm searching for a way to insert scope data from inputs to a php variable, this is how my code look:
HTML:
<div class="form-group" ng-app="Filter" ng-controller="InsertFilter">
<form>
<label for="limit">Limit:</label>
<input type="text" class="form-control" id="limit" name="limit" ng-model="limit">
<label for="page">Page:</label>
<input type="text" class="form-control" id="page" name="page" ng-model="page">
<label for="from">From:</label>
<input type="date" class="form-control" id="from" name="from" ng-model="from">
<label for="to">To:</label>
<input type="date" class="form-control" id="to" name="to" ng-model="to">
<button type="submit" class="btn btn-default" style="margin-top: 15px;">Show Report</button>
</form>
Ajax request in angular:
var FilterApp = angular.module('Filter', []);
FilterApp.controller('InsertFilter', function($scope, $http) {
$http.post("/api/data-dashboard.php").then(function(response){
$scope.limit = /* ??? */;
});
});
data-dashboard.php:
if (empty($_POST["from"])) {
$from = date('Y-m-d');
} else {
$from = $_POST["from"];
}
if (empty($_POST["to"])){
$week = time() + (7 * 24 * 60 * 60);
$to = date('Y-m-d', $week);
} else {
$to = $_POST["to"];
}
if (empty($_POST["page"])) {
$page = 1;
} else {
$page = $_POST["page"];
}
if (empty($_POST["limit"])) {
$limit = 10;
} else {
$page = $_POST["page"];
}
Thanks for all kind responses.
*should I transfer input to json format ?
To Collect all details form Angular HTTP Request use
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$from = request->from;
And pass parameter to $http.post
$http.post("/api/data-dashboard.php",{from:$scope.from}).then(function(response){});

Messaging system in Codeigniter AJAX

Good day guys, I don't know how can I make an ajax call on Codeigniter
Is there anyone can show me how to do it here? It will help me too much in my career in programming . I'm watching tutorials but that isn't the way I need.
So here is the process, once I submit a data on the database, the whole page must not load and updates my records on the view. I tried my best, but I think I really need your help now. Advance thank you.
My script
<script>
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: <?php echo base_url()?> + "messages/send_message",
data: {textbox: $("#textbox").val(),owner: $("#owner").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have missed this bracket
return false;
});
});
</script>
My controller
function send_message()
{
$sk = random_string('alnum',5).time();
$from= $_SESSION['username1'];
$owner = $_POST['owner'];
$desc = $_POST['textbox'];
$to = $this->Model_items->get_owner_name($owner);
$from = $this->Model_items->get_owner_name2($username);
date_default_timezone_set('Asia/Manila');
$date = date("Y-m-d H:i:s");
$data = array('message_from_username'=>$username,'message_to_username'=>$owner,'message_sk'=>$sk,'message_desc'=>$desc,'message_from'=>$from,'message_to'=>$to,'message_date'=>$date,'status'=>1);
$this->Model_messages->message_owner($data);
}
My model
function message_owner($data)
{
$this->db->insert('messages',$data);
}
function view_convo($from,$username)
{
$query = $this->db->query("Select * from messages where
(message_from_username = '$username' AND message_to_username = '$from') OR
(message_from_username = '$from' AND message_to_username = '$username')
order by message_id desc");
return $query->result();
}
And for my views
<div class="col-md-9 ui segment pre-scrollable" style="min-height:100px;">
<h3 class="ui dividing header">Conversation with <?php echo $convo_with?>
</h3>
<div class="ui comments">
<?php
foreach($convo as $key)
{
?>
<div class="comment">
<a class="avatar">
<img src="<?php echo base_url()?>img/default-avatar.png" style="width:30px;height:25px;border-radius:50%;">
</a>
<div class="content">
<a class="author"><?php echo $key->message_from?></a>
<div class="metadata">
<span class="date">
<?php
date_default_timezone_set('Asia/Manila');
$now = strtotime(date("Y-m-d H:i:s"));
$date = strtotime($key->message_date);
$dateDiff = abs($now - $date);
$fullDays = floor($dateDiff/(60*60*24));
if($fullDays==0)
{
echo " Today ";
}
else if($fullDays==1)
{
echo " Yesterday ";
}
else
{
echo $fullDays ." days ago";
}
$at=date('g:iA',$date)
?> at <?php echo $at?>
</span>
</div>
<div class="text">
<?php echo $key->message_desc?>
</div>
</div>
</div>
<?php
}
?>
<br>
</div>
<form method="post">
<input id="owner" type="hidden" value="<?php echo $this->uri->segment(3);?>" name="owner">
<input id="textbox" type="text" name="textbox">
<input id="send" type="submit" name="send" value="Send">
</form>
</div>
You need to send back something to the ajax call
Update your controler function to return a json with the updated list of messages, form that json you use jquery in the success function to update the list of messages
function send_message()
{
$sk = random_string('alnum',5).time();
$from= $_SESSION['username1'];
$owner = $_POST['owner'];
$desc = $_POST['textbox'];
$to = $this->Model_items->get_owner_name($owner);
$from = $this->Model_items->get_owner_name2($username);
date_default_timezone_set('Asia/Manila');
$date = date("Y-m-d H:i:s");
$data = array('message_from_username'=>$username,'message_to_username'=>$owner,'message_sk'=>$sk,'message_desc'=>$desc,'message_from'=>$from,'message_to'=>$to,'message_date'=>$date,'status'=>1);
$this->Model_messages->message_owner($data);
$datareturned = $this->Model_messages->view_convo($from,$to);
return json_encode(array('message'=>'Database Updated successfully','data'=>$datareturned));
}
js:
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: <?php echo base_url()?> + "messages/send_message",
data: {textbox: $("#textbox").val(),owner: $("#owner").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data.message); //as a debugging message.
//here you update the message list with the data from "data.data"
//using a loop and append
}
});// you have missed this bracket
return false;
});
});
Controller:
function send_message()
{
$sk = random_string('alnum',5).time();
$from= $_SESSION['username1'];
$owner = $_POST['owner'];
$desc = $_POST['textbox'];
$to = $this->Model_items->get_owner_name($owner);
$from = $this->Model_items->get_owner_name2($username);
date_default_timezone_set('Asia/Manila');
$date = date("Y-m-d H:i:s");
$data = array('message_from_username'=>$username,'message_to_username'=>$owner,'message_sk'=>$sk,'message_desc'=>$desc,'message_from'=>$from,'message_to'=>$to,'message_date'=>$date,'status'=>1);
$value = $this->Model_messages->message_owner($data);
Print_r($value);
die();
}
Use the function in your controller

Categories