I'm still new in web programming. I got problem when I use ajax and jQuery for get mysql data when I choose radio button then submit that value. For the query I'm using PDO. Here's my code :
1. Choose the value from radio button
<form method="get" name="urut">
<input type="radio" name="urut" value="ASC" id="urut"/>ASC
<input type="radio" name="urut" value="DESC" id="urut"/>DESC
<input type="submit" value="Filter" id="masukan"/>
</form>
jQuery code to get ASC or DESC value from the radio button when click the input submit
<script type="text/javascript">
$(document).ready(function(){
$('#masukan').click(function(){
$('#table_div').text("");
$('#info').text("");
$.ajax({
url : "php/by_name.php",
type : "get",
data : {"urut": $("#urut").val()},
success : function(data){
$('#info').html('<b>Daftar Siswa Berdasarkan Nama</b>');
$('#table_div').html(data);
},
error : function(xhr, teksStatus, kesalahan){
$('#info').html('<b>Terjadi Kesalahan</b>');
}
});
});
});
</script>
This page give data that choose by user when submit the value is DESC or ASC in html table
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="get">
<table>
<?php
# code...
if(isset($_GET['urut'])){
$urut = trim($_GET['urut']);
?>
<thead>
<th>N I S</th>
<th>N I S N</th>
<th>NAMA SISWA</th>
<th>TEMPAT LAHIR</th>
<th>TANGGAL LAHIR</th>
<th>AKSI</th>
</thead>
<tbody>
<?php
// echo $urut;
include "db_connect.php";
if($urut == "ASC"){
try{
$kueri = $dt_bas->prepare("SELECT nis, nisn, nm_dpn, tmp_lhr, dob_siswa FROM siswa ORDER BY nm_dpn ASC");
// $kueri->bindParam(":pilih", $urut);
$kueri->execute();
}catch(PDOException $e){
}
while ($row = $kueri->fetch(PDO::FETCH_ASSOC)) {
?>
<!--- Tabel Row Start ASC------------------>
<tr>
<td><?php echo $row["nis"];?></td>
<td><?php echo $row["nisn"];?></td>
<td><?php echo $row["nm_dpn"];?></td>
<td><?php echo $row["tmp_lhr"];?></td>
<td><?php echo $row["dob_siswa"];?></td>
<td>
<a href="#">Ubah<a/>
Detail
</td>
</tr>
<?php
} // end of while where $urut == ASC
}elseif($urut == "DESC"){
try{
$kueri = $dt_bas->prepare("SELECT nis, nisn, nm_dpn, tmp_lhr, dob_siswa FROM siswa ORDER BY nm_dpn DESC");
// $kueri->bindParam(":pilih", $urut);
$kueri->execute();
}catch(PDOException $e){
}
while ($row = $kueri->fetch(PDO::FETCH_ASSOC)) {
?>
<!--- Tabel Row Start ASC------------------>
<tr>
<td><?php echo $row["nis"];?></td>
<td><?php echo $row["nisn"];?></td>
<td><?php echo $row["nm_dpn"];?></td>
<td><?php echo $row["tmp_lhr"];?></td>
<td><?php echo $row["dob_siswa"];?></td>
<td>
<a href="#">Ubah<a/>
Detail
</td>
</tr>
<?php
} // end of while where $urut == DESC
} // end of child if
} // end of parent if
?>
</tbody>
</table>
</form>
</body>
</html>
When, I refresh the page on my web browser, I get error message but It only work once for both value I input and it's just temporary, but when I try it for 2 or more times I get nothing even the error message.
Here my console error
enter image description here
I get something weird also in this error, when I submit DESC in my web browser url I can see DESC, but in my console error it show me ASC even I try to submit DESC for many times. Here the picture
enter image description here
Thank's for your time, everyone.
You are using same id for both radio input which is why you are not getting correct value. Change one of radio button ID and use jQuery to get selected input button value and then use.
Use separate id s for radio buttons .That will do your need..
Related
I want to set a timer for one column of a table, the column contain time and I want to set a timer for this column. Each cell of this column has a specific time, if the time is 1 hour before 20 minutes of that hour it should display a popup message which the time is going to finish.
Below is my table:
column name: Time Difference
<body>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th>IdCard</th>
<th>Name</th>
<th>Company</th>
<th>Floors</th>
<th>Arrival</th>
<th>Departure</th>
<th>Time Difference</th>
</tr>
</thead>
<?php
include('includes/dbconnection.php');
$sql="SELECT *,
TIME_FORMAT(arrival, '%h:%i %p') AS arrival,
TIME_FORMAT(departure, '%h:%i %p') AS departure,
TIME_FORMAT(timediff(departure, arrival), '%H:%i') AS difftime
FROM master where Status = 'Pending'";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0) {
foreach($results as $row) {
?>
<tr>
<!-- <td><?php echo htmlentities($cnt);?></td>-->
<td><?php echo htmlentities($row->idcard);?></td>
<td><?php echo htmlentities($row->name);?></td>
<td><?php echo htmlentities($row->company);?></td>
<td><?php echo htmlentities($row->floors);?></td>
<td><?php echo htmlentities($row->arrival);?></td>
<td><?php echo htmlentities($row->departure);?></td>
<td><span style="color: red;"><?php echo htmlentities($row->difftime);?></span></td>
</tr>
<?php
$cnt=$cnt+1;
}
}
?>
</table>
</div>
</body>
Table Image
Eliana,
See these answers how to refresh PHP page by browser:
Refresh a page using PHP
PHP-script refresh it self and restart execution-time
After the page refresh your current code will then display the new time difference in the last column 'Time Difference'.
If you still want to show pop up then you need to use some Javascript to display the pop after page is loaded, e.g.:
<body onload="showArrivingSoon()">
<!-- Your code ... -->
<script>
<?php
// Iterate through rows to produce string $arrivingSoonAsStringDelimitedByNewLine ...
?>
// Here the prepared string is printed to the page and initialize JS variable
var arrivingSoon = '<?php echo $arrivingSoonAsStringDelimitedByNewLine ?>';
function showArrivingSoon(arrivingSoon)
{
alert('Arriving soon:\n' + arrivingSoon);
}
</script>
</body>
The iteration, calculations and checks could be done in Javascript as well. To do that it's easier first to pass data rows as JSON from PHP to Javascript variable, then iterate.
I have a simple html table that displays data from a mysql table containing a list of available tournaments.
<table>
<tr>
<th>Tournament Name</th>
<th>Platform</th>
<th>Date</th>
<th>Venue</th>
<th>Judge</th>
<th>Description</th>
<th>Limit</th>
<th>Register</th>
</tr>
<?php while($row = mysqli_fetch_array($result)):?>
<tr>
<td><?php echo $row['nTournament'];?></td>
<td><?php echo $row['pTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['vTournament'];?></td>
<td><?php echo $row['jTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['lTournament']; ?></td>
<td><form method="post" action="tournamentlist.php"><button type="submit" name="btn_register"></button></form></td>
</tr>
<?php endwhile; ?>
</table>
What I want to do is that once the current user clicks that button, the button executes a query which takes the current user's id and the tournament id of the selected row to add them to another mysql table. Something like a tournament inscription.
The query/function I want to run is:
if (isset($_POST['btn_register'])) {
singup();
}
function singup() {
global $db;
$idUser = $_POST['idUser'];
$idTournament= $_POST['idTournament'];
$query = "INSERT INTO registeredCompetitor(idUser, idTournament) VALUES ('$idUser', '$idTournament')";
mysqli_query($db, $query);
header('location: tournamentlist.php');
}
The query works just fine on it's own but I don't know if the function itself works because of the button.
Is it possible to do such thing without the use of a form? If not, What other ways are there to do something like this?
EDIT1: Button now is ready but nor the function or the query executes once it's clicked.
You can create a form on each row that has 2 hidden fields in it. Not sure what your DB fields are called though so you'll have to change user_id and tournament_id to something appropriate.
...
<td>
<form action="post" action="the_name_of_your_php_script.php">
<input type="hidden" name="idUser" value="<?php echo $row['user_id']; ?>">
<input type="hidden" name="idTournament" value="<?php echo $row['tournament_id']; ?>">
<button type="submit" name="btn_register"></button>
</form>
</td>
...
Can't wrap it because <form> is not allowed as a child of <td>
All the documentation I see online permits forms inside of <td>. The other alternative is to use a link instead of a form.
You can use javascript to execute this functionality.
<table>
<tr>
<th>Tournament Name</th>
<th>Platform</th>
<th>Date</th>
<th>Venue</th>
<th>Judge</th>
<th>Description</th>
<th>Limit</th>
<th>Register</th>
</tr>
<?php while($row = mysqli_fetch_array($result)):?>
<tr>
<td><?php echo $row['nTournament'];?></td>
<td><?php echo $row['pTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['vTournament'];?></td>
<td><?php echo $row['jTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['lTournament']; ?></td>
<td><button type="submit" onclick="sendRequest('<?php echo $idUser ?>','<?php echo $idTournament ?>')" name="btn_register"></button></td>
</tr>
<?php endwhile; ?>
</table>
Javascript code
function sendRequest(idUser,idTournament ){
// i am using jquery
$.post(other_page_url,{idUser:idUser,idTournament :idTournament},function(data)
{
window.location = 'tournamentlist.php';
} )}
I hope it's gonna help you
You don't need to wrap this in a <form> inside the table, you can do it all via Javascript / Jquery if you wish. On the html side, add the data you need to the button in data sets:
<td><button type="submit" name="btn_register" id="btn_register" data-user-id="<?php echo $userId ?>" data-tournament-id="<?php echo $row['idTournament']; ?>"></button></td>
Then in your script, you can call the data and send to post via ajax and either load the new page after INSERT, or load as a modal, or whatever you like. You can do something like below if loading a modal (change the load part to refresh the page if you want to go directly):
$('#btn_register').on('click', function () {
var t_id = $(this).data('tournament-id');
var u_id = $(this).data('user-id');
$.ajax({
url: "YourURL",
type: "POST",
data:{
t_id:t_id,
u_id:u_id
},
success: function (h) {
$(".modal-title").text("Table with new stuff");
$(".modal-body").html(h);
$('#modal').modal();
// lots of options here - you could even reload above if desired
}
})
});
i made a table with few attribute code is
<table class="table table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>File-name</th>
<th>Purpose</th>
<th>Recieved-By </th>
<th>Processed-By</th>
<th>Adress</th>
<th>Contact-No</th>
<th>Date</th>
<th>Update</th>
</tr>`
and here is fetching data from database table in all column except update
<tbody>
<?php
if ( $search )
{
$p_query = "select * from files where recieved_by like '%$search%' or processed_by like '%$search%' or purpose like '%$search%' or file_name like '%$search%' order by id desc limit $page_start_from, $total_num_page";
}
else
{
$p_query = "select * from files order by id desc limit $page_start_from, $total_num_page";
}
$p_run=mysqli_query($con,$p_query);
if(mysqli_num_rows($p_run)){
while($row=mysqli_fetch_array($p_run))
{
$c_id=$row['id'];
$file=$row['file_name'];
$purpose=$row['purpose'];
$recieve=$row['recieved_by'];
$processed=$row['processed_by'];
$address=$row['address'];
$contact=$row['contact_no'];
$date=$row['date'];
$show_status=$row['show_status'];
?>
<tr>
<td><?php echo $c_id;?></td>
<td><?php echo $file;?></td>
<td><?php echo $purpose;?></td>
<td><?php echo $recieve;?></td>
<td><?php echo $processed;?></td>
<td><?php echo $address;?></td>
<td><?php echo $contact;?></td>
<td><?php echo $date;?></td>
and now in update column there is changes when there is value in Update column from file table database then it will show in update column other wise it will open a action which is a button that have a form code is here
<td>
<?php if( !empty($show_status)){
echo $show_status;
}
else
{
?>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style=" padding-top: 3px; padding-bottom: 3px;">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu" style="margin-left:-50px;">
<?php
if(isset($_POST['submit-form']))
{
$update_date=$_POST['reason-date'];
$status=$_POST['reason'];
$p_id=$_POST['idvalue'];
$d_query="INSERT INTO update_table (id, reason, update_date) VALUES ('$p_id', '$status', '$update_date'); update files set show_status =' $status' where id=' $p_id'";
if(mysqli_multi_query($con,$d_query))
{
$msg="file have been submitted ";
header('location:index.php');
}
else
{
$error_msg="Already updated this file";
}
}?>
<script type="text/javascript">
function checkvalue()
{
var ureason=document.forms["sform"]["ureason"].value;
var udate=document.forms["sform"]["udate"].value;
if (ureason=="")
{
alert("Status Field is blank ");
return false;
}
if (udate=="")
{
alert("Date Field is blank ");
return false;
}
}
</script>
<form role="banner" class="actionform" action="index.php" method="POST" name="sform" onsubmit=" return checkvalue()">
<input type="hidden" name="idvalue" value="<?php echo $c_id; ?>">
<label style="font-weight: normal;">Enter Reason*</label><br>
<input type="text" name="reason" placeholder="call or letter or filed " id="ureason"><br>
<label style="font-weight: normal;">Update Date:*</label><br>
<input type="date" name="reason-date" placeholder="enter date here" id="udate">
<br><br>
<input type="submit" name="submit-form" id="actionid" value="Submit" style="background: #3596e0; ">
<?php
if(isset($error_msg))
{
echo "<span style='color:red; margin-bottom:10px;' class='pull-right'>$error_msg</span>";
exit();
}
else if(isset($msg))
{
echo "<span style='color:green;' class='pull-right'>$msg</span>";
exit();
}?>
</form>
</ul>
</div>
<?php
} ?>
</td>
</tr>
<?php
}
}
else {
echo "<h3> NO Related Table is Found Here </h3>";
}
?>
</tbody>
</table>
now problem is when i am filling at first update action form its going normal but when i am going for 2nd or 3rd action which have above row update function not filled its keep showing error of checking form column is empty , how to stop this , when i would fill in one row update column it should effect only that particular row, please someone help me , i stuck at this part for two days .
Because of You are using INSERT Method, use UPDATE method for update.
For first time because of no data exist, your INSERT method works as you want, but after that you have to use UPDATE method for update.
For UPDATE see https://www.w3schools.com/sql/sql_update.asp
For INSERT see https://www.w3schools.com/sql/sql_insert.asp
This is happened because your form values not unique form so i have changed some form values:
<form role="banner" class="actionform" action="test.php" method="POST" name="sform" **onsubmit=" return checkvalue(<?php echo $c_id ?>**)">
<input type="text" name="reason" placeholder="call or letter or filed " id="ureason_<?php echo $c_id ?>">
<input type="date" name="reason-date" placeholder="enter date here" id="udate_<?php echo $c_id ?>">
Now all id's have unique value, And now javascript code would be:
<script type="text/javascript">
function checkvalue(id)
{
var id = id;
alert(id);
var ureason=document.getElementById('ureason_'+id).value;
var udate=document.getElementById('udate_'+id).value;
if (ureason=="")
{
alert("Status Field is blank ");
return false;
}
if (udate=="")
{
alert("Date Field is blank ");
return false;
}
}
</script>
And one more think you missed to update your table files
run this query at same time when your are inserting in update table:
$d_query=$db->query("INSERT INTO update_table (id, reason, update_date) VALUES ('$p_id', '$status', '$update_date')");
$d_query=$db->query("Update files set show_status='ok' where id='$p_id' ");
I hope this may help you.
I have a webpage (i am beginner php for only 1.5 months following book examples) that allows a user to enter a gpa and then search for students that meet the minimum entered. When the search button is clicked it calls a function from php file to query the database. My code is almost working right. The problem is it is returning all students and I want to return only the rows that meet minimum gpa entered. Tried to use HAVING clause and others but still doesn't return what I want. Thanks!
Link to sql fiddle: http://www.sqlfiddle.com/#!2/be9da
html:
<script type="text/javascript">
function queryStudent() {
var ajaxRequest = new XMLHttpRequest;
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
document.getElementById("ajax_output").innerHTML = ajaxRequest.responseText;
}
};
ajaxRequest.open("GET", "gpa_search.php", true);
ajaxRequest.send(null);
}
</script>
<form name="student">
<label>Minimum GPA: </label>
<input type="text" id="GPA" name="gpa"><br><br>
<input type="button" onclick="queryStudent();" value="Search" id="button">
</form><br>
<!--output section after search-->
<section id="ajax_output">
</section><br><br>
<p>Students with higher than minimum GPA will be displayed here.</p><br>
Search & Split
php:
<?php
//get user input from text box on index.htm
$GPA = filter_input(INPUT_GET, 'GPA');
//Code for query
$query = 'SELECT *
FROM student
ORDER BY studentID';
$statement = $db->prepare($query);
$statement->bindValue(':GPA', "%".$GPA."%", PDO::PARAM_STR);
$statement->execute();
$students = $statement->fetchAll();
?>
<!--table to hold output-->
<table>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Email</th>
<th>GPA</th>
</tr>
<?php foreach ($students as $student) : ?>
<tr>
<td><?php echo $student['studentID']; ?></td>
<td><?php echo $student['name']; ?></td>
<td><?php echo $student['email']; ?></td>
<td><?php echo $student['GPA']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<body>
</body>
</html>
On your code use the following:
$query = 'SELECT *
FROM student
WHERE GPA >= :GPA
ORDER BY studentID';
$statement->bindValue(':GPA', $GPA, PDO::PARAM_STR);
This will search for students that have GPA greater and equal to $GPA, If you want to retrieve students that have only that GPA specifically then change WHERE GPA = :GPA
Check your SQL query, the error is most likely from there. Your select statement doesn't have a where clause. It should be something like select * from students where GPA = :GPA Order by studentid
I would like to ask how can I call Sql query when HTML button is pressed. I watched a couple tutorials, but never got it to work correct, thats why I would like to ask here.
So..I have a list of items displayed, and the list is generated from database. Here is how the code looks like:
<table width="100%" border="1" cellspacing="1" cellpadding="5" style="background-color:#FFC" >
<td>Id</td>
<td>Text</td>
<td>Solved?</td>
<td></td>
<?php
while( $array = mysql_fetch_assoc($queryRun) ) {
?><tr>
<td><?php echo $id = $array['id'].'<br />';?></td>
<td><?php echo $text = $array['text'].'<br />';?></td>
<td><?php echo $reseno = $array['solved'].'<br />';?></td>
<td><input type="button" value="Solve it" /></td>
</tr><?php
}?>
</table>
Now each item that is generated inside this loops has a button "Solved" at the end of the table, and I want to make it so when user click on that button, do a Sql query which changes a value of solved from 0 (false) to 1 (true).
You need ajax. write button onclick and make ajax call.
I've not tested this, but it should work.
Basically I've applied a class to anything to easily select stuff in jQuery:
<?php while ($array = mysql_fetch_assoc($queryRun)) { ?>
<tr class="row">
<td class="cell_id">
<?php echo $array['id']; ?>
</td>
<td class="cell_text">
<?php echo $array['text']; ?>
</td>
<td class="cell_solved">
<?php echo $array['solved']; ?>
</td>
<td class="cell_solve_it">
<input class="button_solve_it" type="button" value="Solve it" />
</td>
</tr>
<?php } ?>
Then I've created this short jQuery script:
$('.row').each(function(){
$('.button_solve_it', this).click(function(e){
e.preventDefault();
$.post(
'solve_query.php',
{
id: $('.cell_id', this).html(),
text: $('.cell_text', this).html()
},
function (data) {
$('.cell_solved', this).html('1');
}
);
});
});
In short:
when you click a .button_solve_it button, you make an AJAX request to solve_query.php, where you perform your SQL query.
Then, it sets the content of the row in Solved? column to 1 (or to true or whatever you want).