I have an input field with the date type, and there is a database that contains data with dates. I need that when selecting a date in the date field without refreshing the page, all the data associated with this date will be displayed. I have this code, which, when choosing an option from the list, will display what I need. how to fix this script so that when a date is selected in a date type field, it sends the date to the server
<input type="date" class="form-control" name="date_sched" value="" required>
<span id="skidka"></span>
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var category = $(this).find(':selected').val();
$.ajax({
url:_base_url_+"admin/appointments/get_cat.php",
type: 'POST',
data: {category: category},
success: (function (data) {
$("#date_field").html(data);
})
});
});
});
get-cat.php
$query = "SELECT * FROM `appointments` WHERE `id` = '".($_POST['category'])."'";
$result = $mysqli->query($query);
$data = '';
foreach ($result as $value){
$data .= $value['date_sched'];
}
echo $data;
?>
For retrieving data using Ajax + jQuery, you should write the following code:
Create an HTML button with id="showData". Ajax script will execute on click this button.
backend-script.php
<?php
include("database.php");
$db=$conn;
// fetch query
function fetch_data(){
global $db;
$query="SELECT * from usertable ORDER BY id DESC";
$exec=mysqli_query($db, $query);
if(mysqli_num_rows($exec)>0){
$row= mysqli_fetch_all($exec, MYSQLI_ASSOC);
return $row;
}else{
return $row=[];
}
}
$fetchData= fetch_data();
show_data($fetchData);
function show_data($fetchData){
echo '<table border="1">
<tr>
<th>S.N</th>
<th>Full Name</th>
<th>Email Address</th>
<th>City</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th>
</tr>';
if(count($fetchData)>0){
$sn=1;
foreach($fetchData as $data){
echo "<tr>
<td>".$sn."</td>
<td>".$data['fullName']."</td>
<td>".$data['emailAddress']."</td>
<td>".$data['city']."</td>
<td>".$data['country']."</td>
<td><a href='crud-form.php?edit=".$data['id']."'>Edit</a></td>
<td><a href='crud-form.php?delete=".$data['id']."'>Delete</a></td>
</tr>";
$sn++;
}
}else{
echo "<tr>
<td colspan='7'>No Data Found</td>
</tr>";
}
echo "</table>";
}
?>
ajax-script.js
$(document).on('click','#showData',function(e){
$.ajax({
type: "GET",
url: "backend-script.php",
dataType: "html",
success: function(data){
$("#table-container").html(data);
}
});
});
You need to make it so that when your date changes, you fetch data based on that date:
<input type="date" class="form-control" name="date_sched" id='date_sched' required>
<script type='text/javascript'>
$(document).ready(function(){
$(document).on('change', '#date_sched', function(){
let date = $(this).val();
$.ajax({
url:_base_url_+"admin/appointments/get_cat.php",
type: 'POST',
data: {date: date},
success: function (data) {
$("#data_to_be_shown").html(data);
);
});
});
});
</script>
Your query then, should look something like this:
$date = $_POST['date'];
$sql = "SELECT * FROM `table_name` WHERE `date` = $date";
$stmt = $connection->query($sql);
Also I recommend you look up prepared statements.
Im not sure what you want, are you mean server side table with date filter?
If yes, I think this will help:
https://datatables.net/examples/data_sources/server_side
You can read the docs for advance costume date range filter or for your own filter
Related
I am trying to create a chat system using php and ajax. I started the ajax request when the user hit the send button and after that the request will be called after 5 sec automatically. I want fetch the latest entry from the database. I am passing a last item id "tid".
I am getting the data from the database after the last id but it appending my div the same data until I entered a new record.
function startajax()
{
var usfrnd = $("#username").text();
var data = 'lastid=' + tid + '&usfrnd=' + usfrnd;
$.ajax({
type: "POST",
url: "includes/wow_message.php",
data: data,
//dataType: "JSON",
success: function(msg){
$("#msgbody").append(msg);
console.log(msg);
},
complete: function() {
setTimeout(startajax, 5000);
}
});
}
php code.
<?php
include '../include/database.php';
session_start();
$username = $_SESSION['uName'];
if(isset($_POST['lastid'], $_POST['usfrnd']))
{
$lastid = $_POST['lastid'];
$sent_to = $_POST['usfrnd'];
$qry2 = "select * from msg_tab where (((sent_by= '$username' AND sent_to='$sent_to') OR (sent_by= '$sent_to' AND sent_to='$username')) AND $lastid < msg_id) ORDER BY msg_id ASC";
$res = mysqli_query($conn, $qry2);
if (mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_assoc($res)) {
$message = $row['msg'];
$msg_id = $row['msg_id'];
$sent_by = $row['sent_by'];
echo ' <tr data-msg-id="'.$msg_id.'">
<td><span class="subject">'.$sent_by.'</span></td> <td><span class="subject">'.$message.'</span></td>
</tr>';
}
}
}
?>
If you want create chat maybe you should use ex. WebSocket.
Send request in some time interval in my opinion is no so good solution.
I need to pass a variable which called 'square' between my php files, and everything is ok until I go to the action file to retrieve data from my database:
//plan.php
<?php
include("config.php");
session_start();
$loggeduser = $_SESSION['user'];
if (!isset($_SESSION['user']))
{
header("Location: login.php");
}
// Get selected square
$selsquare = $_GET["square"];
?>
<script>
$(document).ready(function(){
fetchUser();
function fetchUser()
{
var action = "Load";
$.ajax({
url : "action.php?square=$selsquare",
method:"POST",
data:{action:action},
success:function(data){
$('#result').html(data);
}
});
}
</script>
and here is my action.php file
<?php
//Database connection by using PHP PDO
$username = 'root';
$password = '';
$connection = new PDO( 'mysql:host=localhost;dbname=db', $username, $password );
$selsquare = $_GET["square"];
if(isset($_POST["action"]))
{
if($_POST["action"] == "Load")
{
$statement = $connection->prepare("SELECT * FROM plans WHERE square = '$selsquare' ");
$statement->execute();
$result = $statement->fetchAll();
$output = '';
$output .= '
<table class="table table-bordered">
<tr>
<th width="10%">ID</th>
<th width="10%">Square</th>
<th width="40%">Plan</th>
<th width="10%">Update</th>
<th width="10%">Delete</th>
</tr>
';
if($statement->rowCount() > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["square"].'</td>
<td>'.$row["plan"].'</td>
<td><button type="button" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button></td>
<td><button type="button" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td align="center">Data not Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
I need to retrieve all the data that has square = $selsquare but it is not working. The selsquare is working in the plan.php but not in action.php
Please help me figure out whats wrong
You are not doing it correctly. In your ajax method your method of passing data is post and in your action.php file you are fetching it as a get variable.
<script>
$(document).ready(function(){
fetchUser();
function fetchUser()
{
var action = "Load";
var square = "<?php echo $selsquare ?>";
$.ajax({
url : "action.php",
method:"POST",
data:{action:action, square:square},
success:function(data){
$('#result').html(data);
}
});
}
</script>
Now fetch square as post variable in action.php file
I haven't tested the code but it should work.
By default, PHP sessions require a cookie to identify them. You’re trying to run 2 separate PHP scripts (including the script for the Ajax call), so each will need access to the cookie.
Ajax by default doesn’t send cookies. This is a relatively new feature, but is supported in all current browsers.
First, you need to set the property withCredentials to true. This will allow the passing of cookies.
See http://api.jquery.com/jQuery.ajax/
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
In PHP, you will also need to include a statement like:
header("Access-Control-Allow-Credentials: true");
in your responding script.
Alternatively, you can instruct PHP to accept the session id and get Ajax to send it as a query string.
You are sending POST from Javascript, while in your PHP you are reading as $_GET.
<script>
$(document).ready(function(){
fetchUser();
function fetchUser()
{
var square_js = '<?php echo $selsquare; ?> ';
$.ajax({
url : "action.php?square=$selsquare",
method:"GET",
data:{square:square_js},
success:function(data){
$('#result').html(data);
}
});
}
</script>
If your square has the value ABCDEF, then in your PHP, you will get the request this way
print_r($_GET);
Array{
"square" => "ABCDEF"
}
Recommended way of passing string in double quote is with {}
url : "action.php?square=$selsquare",
Should be
url : "action.php?square={$selsquare}",
So I have an issue where I want to be able to query some data with the user's current location but I am still new to JSON and trying to figure out how to send the data back to the main page.
Here are the hidden inputs for the lat/lng values on the index.php page
<input type="hidden" id="latitude">
<input type="hidden" id="longitude">
Here is the code to send the lat/lng to tables.php from the index.php page
$.getJSON(GEOCODING).done(function(location) {
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
$.ajax({
url:'table.php',
method: 'POST',
dataType: 'json',
data:{
lat: $('#latitude').val(),
lng: $('#longitude').val()
},
success: function(data){
console.log();
}
});
});
I am using datatables to display the data on the index.php page.
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css">
<script>
$(document).ready(function(){
var dataTable = $('#searchTable').dataTable();
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
});
});
</script>
echo'<table id="searchTable" class="display">
<thead>
<tr>
<th>Latitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody>
';
(data to display from tables.php)
echo'</tbody>
</table>
';
And then on the tables.php page I am pulling the data from the MYSQL database, now this is where I have to figure out how to send the data back to the index.php page through JSON and display it in the table.
<?php
require_once("connect.php");
$lat = isset($_POST['lat']) ? $_POST['lat'] : null;
$lng = isset($_POST['lng']) ? $_POST['lng'] : null;
if($lat && $lng){
$locations = array();
$stmt = "SELECT * FROM location LIMIT 500"; //Query data from table
$stmt = $conn->prepare($stmt);
$stmt->execute();
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo'<tr>
<td>';
$locations['Latitude'][] = $row;
echo'</td>
<td>';
$locations['Longitude'][] = $row;
echo'</td>
</tr>';
}
}
return json_encode($locations);
}
?>
What I am looking to do is update the table with data from the database based on the user's current location, when the user lands on the index.php page, Or the user can also search for a location using the search bar provided on the index.php page.
Thank you in advance for your time.
You need to first send JSON correctly from PHP file, and then receive at the AJAX response and parse to use it further to show in data tables. See below codes for the help.
Client side code:
$.getJSON(GEOCODING).done(function(location) {
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
$.ajax({
url:'table.php',
method: 'POST',
dataType: 'json',
data:{
lat: $('#latitude').val(),
lng: $('#longitude').val()
},
success: function(data){
// Here you need to parse the JSON data and put it in the data table rows by looping over it, see example code #E1
console.log();
}
});
});
PHP Code:
<?php require_once("connect.php"); $lat = isset($_POST['lat']) ? $_POST['lat'] : null; $lng = isset($_POST['lng']) ? $_POST['lng'] : null; if($lat && $lng){ $locations = array(); $stmt = "SELECT * FROM location LIMIT 500"; //Query data from table $stmt = $conn->prepare($stmt);$stmt->execute(); if($stmt->rowCount() > 0){ $result = $stmt->fetchAll(); foreach($result as $row){
$result[] = ['col1'=>$row['col1'],'col2'=>$row['col2']]; // here you need to add as many columns as you want to show in the data table } } print json_encode($result);die; } ?>
Example codes:-
_#E1_
console.log(JSON.stringify(json.topics)); $.each(json.topics, function(idx, topic){ $("#nav").html('' + topic.link_text + ""); });
Apply code as per your need and it will resolve your problem. Assuming you are getting proper data from the database query.
Hope it helps.
Thanks
I new to php, ajax and mysql. I am trying to build a web application where i get an output table from my database. My question is what code should i use if i want to search another table using the current output table for eg
name surname
john smith
is my out put table, if i click on smith it should search other table containing data about smith
My js code is
$(function myFunction() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
var value1= $('#str1').val();
$.post('test_refresh.php',{value:value,value1:value1}, function(data){
$("#search_results").html(data);
});
return false;
});
});
My Php code is
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = mysql_select_db("cancer database") or die(mysql_error());
echo"";
/*$query = mysql_query("SELECT * FROM tbl_cancer_database
WHERE gene_symbol LIKE '".$_POST['value']."'
OR gene_name LIKE '".$_POST['value']."'
OR gene_id LIKE '".$_POST['value']."'
OR gene_locus LIKE '".$_POST['value']."'
OR function LIKE '%".$_POST['value']."%'
OR alteration_in_cancer LIKE '".$_POST['value']."'
OR reference LIKE '".$_POST['value']."'
");*/
$query = mysql_query("SELECT * FROM tbl_cancer_database
WHERE gene_name LIKE '".$_POST['value']."'
and gene_id LIKE '".$_POST['value1']."'
");
echo '<br />';
echo "You have searched for ".$_POST['value']." and ".$_POST['value1']."";
echo '<br />';
echo '<br />';
echo '<table>';
echo "<tr>
<th bgcolor=silver>Sr. No.</th>
<th bgcolor=silver>Gene Symbol</th>
<th bgcolor=silver>Gene Name</th>
<th bgcolor=silver>Gene Id</th>
<th bgcolor=silver>Gene locus</th>
<th bgcolor=silver>Function</th>
<th bgcolor=silver>Alteration in cancer</th>
<th bgcolor=silver>Reference</th></tr>";
while ($data = mysql_fetch_array($query)) {
echo '<tr style="background-color:pink;">
<td>'.$data["id"].'</td>
<td>'.$data["gene_symbol"].'</td>
<td>'.$data["gene_name"].'</td>
<td>'.$data["gene_id"].'</td>
<td>'.$data["gene_locus"].'</td>
<td>'.$data["function"].'</td>
<td>'.$data["alteration_in_cancer"].'</td>
<td>'.$data["reference"].'</td>
</tr>';
}
echo '</table>';
?>
Any help would be greatly appreciated.
First of all add a class that uniquely identifies each of your table data.
So your table would look like this
<table>
<tr>
<td class="fistname">John</td>
<td class="lastname">Smith</td>
</tr>
</table>
Then your javascript would look like this
$(function myFunction() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
var value1= $('#str1').val();
$.post('test_refresh.php',{value:value,value1:value1}, function(data){
$("#search_results").html(data);
initializeClick();
});
return false;
});
});
function initializeClick(){
$('.firstname').click(function(){
var sSearchValue = $(this).text();
$.post('PAGE TO SEARCH YOUR OTHER TABLE',{value:sSearchValue}, function(data){
//CAN DO WHAT EVER YOU WANT WITH THE RESULTS HERE
});
});
}
Also keep in mind to escape characters when they are output on the html
Im working om a menu system.
I use a query to get the menu list from the database.
On that table I also have an edit and delete option.
The edit and delete both works, but the edit function get activated on the TR.
I want to activate the edit function when I click on the edit TD.
When I just simply change
$(".edit_tr").click(function()
to
$(".editmenu").click(function()
It does the job, but it only changes the value in the input field, not in the html and or database.
Ill hope u guys know what I mean, and can help me out.
Thanks in advance.
Here's the code:
Javascript:
// delete menu
$(document).ready(function() {
// delete the entry once we have confirmed that it should be deleted
$('.delete').click(function() {
var parent = $(this).closest('tr');
$.ajax({
type: 'get',
url: 'deletemenu.php', // <- replace this with your url here
data: 'ajax=1&delete=' + $(this).attr('id'),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.fadeOut(300,function() {
parent.remove();
});
}
});
});
});
// edit menu
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#menunaam_"+ID).hide();
$("#voorgerecht_"+ID).hide();
$("#hoofdgerecht_"+ID).hide();
$("#nagerecht_"+ID).hide();
$("#prijs_"+ID).hide();
$("#menunaam_input_"+ID).show();
$("#voorgerecht_input_"+ID).show();
$("#hoofdgerecht_input_"+ID).show();
$("#nagerecht_input_"+ID).show();
$("#prijs_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var menunaam=$("#menunaam_input_"+ID).val();
var voorgerecht=$("#voorgerecht_input_"+ID).val();
var hoofdgerecht=$("#hoofdgerecht_input_"+ID).val();
var nagerecht=$("#nagerecht_input_"+ID).val();
var prijs=$("#prijs_input_"+ID).val();
var dataString = 'id='+ ID +'&menunaam='+menunaam+'&voorgerecht='+voorgerecht+'&hoofdgerecht='+hoofdgerecht+'&nagerecht='+nagerecht+'&prijs='+prijs;
$("#menunaam_"+ID).html('<img src="load.gif" />'); // Loading image
if(menunaam.length>0&& voorgerecht.length>0&& hoofdgerecht.length>0&& nagerecht.length>0&& prijs.length>0)
{
$.ajax({
type: "POST",
url: "editmenu.php",
data: dataString,
cache: false,
success: function(html)
{
$("#menunaam_"+ID).html(menunaam);
$("#voorgerecht_"+ID).html(voorgerecht);
$("#hoofdgerecht_"+ID).html(hoofdgerecht);
$("#nagerecht_"+ID).html(nagerecht);
$("#prijs_"+ID).html(prijs);
}
});
}
else
{
alert('Vul de velden in');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
And the PHP for the table's
$sql = "SELECT * FROM menus";
$result = mysql_query($sql);
echo "<table>";
echo "<th>#</th> <th>Menu naam</th> <th> Voorgerecht </th> <th> Hoofdgerecht </th> <th> Nagerecht </th> <th> Prijs </th> <th></th><th></th>";
while($row = mysql_fetch_assoc($result)) {
$menunr = $row['menunr'];
$menunaam = $row['menunaam'];
$voorgerecht = $row['voorgerecht'];
$hoofdgerecht = $row['hoofdgerecht'];
$nagerecht = $row['nagerecht'];
$prijs = $row['prijs'];
// open tr
echo "<tr id='$menunr' class='edit_tr'>";
echo "<td>$menunr</td>";
echo "<td><span id='menunaam_$menunr' class='text'>$menunaam</span><input type='text' value='$menunaam' class='editbox' id='menunaam_input_$menunr'/></td>";
echo "<td><span id='voorgerecht_$menunr' class='text'>$voorgerecht</span><input type='text' value='$voorgerecht' class='editbox' id='voorgerecht_input_$menunr'/></td>";
echo "<td><span id='hoofdgerecht_$menunr' class='text'>$hoofdgerecht</span><input type='text' value='$hoofdgerecht' class='editbox' id='hoofdgerecht_input_$menunr'/></td>";
echo "<td><span id='nagerecht_$menunr' class='text'>$nagerecht</span><input type='text' value='$nagerecht' class='editbox' id='nagerecht_input_$menunr'/></td>";
echo "<td><span id='prijs_$menunr' class='text'>$prijs</span><input type='text' value='$prijs' class='editbox' id='prijs_input_$menunr'/></td>";
echo "<td id='$menunr' class='editmenu'>edit</td>";
echo "<td><div class='delete' >delete</div></td>";
// close tr
echo "</tr>";
}
echo "</table>";
?>
And the ajax url php files
deletemenu.php
<?php
include 'config.php';
if(isset($_GET['delete']))
{
$query = 'DELETE FROM menus WHERE menunr = '.$_GET['delete'];
$result = mysql_query($query);
}
?>
editmenu.php
<?php
include("config.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$menunaam=mysql_escape_String($_POST['menunaam']);
$voorgerecht=mysql_escape_String($_POST['voorgerecht']);
$hoofdgerecht=mysql_escape_String($_POST['hoofdgerecht']);
$nagerecht=mysql_escape_String($_POST['nagerecht']);
$prijs=mysql_escape_String($_POST['prijs']);
$sql = "update menus set menunaam='$menunaam',voorgerecht='$voorgerecht',hoofdgerecht='$hoofdgerecht',nagerecht='$nagerecht',prijs='$prijs' where menunr='$id'";
mysql_query($sql);
}
?>