While loop updation value - php

I am developing online attendance.But I stuck in while loop condition
I want to show my code first
<tbody>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value = "<?php echo $ro22['user_id'] ?>"/></td>
<td><?php echo $ro22['first_name'] ?> <?php echo $ro22['last_name'] ?></td>
<td><?php echo $ro22['parent_contact'] ?></td>
<td><input type="button" value="<?php echo $ro22['ai'] ?>" id="pres" name="pres" onclick="return change(this);" onBlur="checkAvailability()" class="w3-button w3-teal"/></td>
</tr>
<?php } ?>
</tbody>
This is output
What I want
I want update present,absent value based on 101,102,103... value
I tried many but failed. Please help me out
Thanks in advance

You need to place a call to the page on a click and pass the user_id. This is easy to do with jQuery:
function change(row) {
$.post('thispage.php', { user_id: $(row).val() }, function(){ window.location.reload(); } );
}
And then receive the post in the PHP:
if (!empty($_POST['user_id'])) {
/* toggle admission status */
}
After the request completes and the status is toggled, the page will reload.

Here is a general example. It's consisted of your PHP program (the AJAX sender) which I rewrote to be they way I think you wanted, a javascript file (containing the AJAX function) and another PHP file (the AJAX request receiver).
You can get different use-cases by altering the database query in the receiving PHP file.
Javascript file (AJAX):
// Send the `id` of the element
function checkAvailability(id)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
// This `if` underneath is success. It means we got a response back
if (this.readyState == 4 && this.status == 200)
{
if(this.responseText == "OK")
{
alert('ID: ' + id + ' changed. Response: ' + this.responseText);
document.getElementById("demo").innerHTML = 'The student has been updated.';
}
else if(this.responseText == "Not OK")
{
alert('Something went wrong with id: ' + id);
}
}
};
// For example you send a request to attendance.php sending `id` info
// - attendance.php just needs to echo the response to answer back
xhttp.open("GET", "attendance.php?id=" + id, true);
xhttp.send();
}
Main PHP page (the file that sends the request):
// U need jQuery to be able to send AJAX requests. Copy this, add to your html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
echo '<table>
<tr>
<th>Student ID</th>
<th>Student name</th>
<th>Phone number</th>
<th>Today\'s attendance</th>
</tr>';
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value="'.$ro22['user_id'].'"/></td>
<td>'.$ro22['first_name'].' '.$ro22['last_name'].'</td>
<td>'.$ro22['parent_contact'].'</td>
<td><input type="button" value="'.$ro22['ai'].'" id="pres" name="pres" onclick="change(this.id);" onBlur="checkAvailability(this.id)" class="w3-button w3-teal"/></td>
</tr>';
}
echo '</table>';
?>
The receiver file:
<?php
$conToDatabase = ... // Here goes DB connection data
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$clean['id'] = $_GET['id'];
}
// Query your DB here using variable $clean['id'] as ID
$querySuccess = ...
// if query successful echo 'OK';
// else echo 'Not OK';
?>

Related

How do we pass data in ajax? [duplicate]

This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 5 years ago.
I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records.
I have coded as below.
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
delete.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
Hopefully this conveys the idea of how an AJAX call works.
The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>
<p id="message">AJAX</p>
<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
event.preventDefault();
$.ajax(
{
url:"delete.php",
method:"POST", /* In the real world you want to use a delete here */
data: { /* plugin your data */
id: id,
name: "Bob",
age: 25
},
dataType:"html",
success: function(success) {
// Handle the success message here!
if (success) {
$('#message').text("Your message was received!");
}
},
error: function(error) {
// Handle your errors here
$('#message').text("Something went wrong!");
}
});
};
</script>
Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.
data: { /* plugin your data */
id: 1,
name: "Bob",
age: 25
},
Next, we need to setup our script.
delete.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Obviously validate the data.
// But this is how you access it.
// $_POST is a global array, so you can access it like so:
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
// Do your server side stuff...
$sql = "DELETE FROM member
WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";
// Do your SQL (delete) here
// $con = mysqli_connect("localhost","root","","ajaxtest");
// Use prepared statements http://bobby-tables.com/php
// $data = mysqli_query($con,"delete from member where id='$id'");
// if ($data) { // Your condition
// This is where you would check if the query passed
// and send back the appropriate message.
if ($id) {
echo json_encode($id);
}
else {
echo http_response_code(500);
}
}
else {
echo "You don't belong here!";
}
you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.
Now I am not exactly sure what you mean by this id value from index.php
But taking your index.php file, I would change it like this
//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
$html[] = "<tr>";
for($i=0;$i<$col;$i++)
{
$html[] = "<td>".$row[$i]."</td>";
}
$html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
$html[] = "</tr>";
}
$html[] = "</table>";
$result = [
'html' => implode("\n", $html),
'debug' => ob_get_clean()
];
header("Content-type:application/json");
echo json_encode($result);
//?> ending tags are undesirable
Your JavaScript part will change too
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(data){
$('#delMsg').html(data.html);
}
})
})
})
You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php
{
html : '<div id=" ...',
debug : ""
}
I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.
Just replace
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
To
echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";
Javascript
function deleteRow(recordID)
{
event.preventDefault();
$.ajax({
type: "GET",
url: "delete.php",
data:{id: recordID}
}).done(function( result ) {
alert(result);
});
}
In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks.
PHP:
$db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();
if ($query->rowCount()) {
echo "success";
}
else
{
echo "fails";
}

PHP Session variable not passing

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}",

Pull data from a database every minute and update on the website without refreshing

I have this PHP page which connects to an SQLite database and reads data from it. The data is constantly being updated and I need the web page to refresh the data shown every minute. How to do it? I saw that Ajax helps in this but I am a complete Ajax newbie and I have to turn this in soon. Any pointers?
Sample code:
<?php
$db = new SQLite3('some_db.db');
$query = $db->query('SELECT * FROM random_table');
?>
<table>
<th>
<td>ID</th><th>Value</th>
</th>
<?php
while ($row = $query->fetchArray (SQLITE3_ASSOC)) { ?>
<tr>
<td><?php echo $row['id'];?></td><td><?php echo $row['val'];?></td>
</tr>
<?php } ?>
</table>
<pre>
JS CODE:
------------
function UpdateTable(){
$.ajax({
url: "script.php"
}).success(function(data) {
var d= JSON.parse(data);
$('table#someID tr').remove();
$('table#someID').append( d.tableContent );
});
}
$( document ).ready(function() {
setTimeout(UpdateTable(),60000);
});
PHP CODE: (script.php)
-----------
<?php
$res = array();
$res['result'] = false;
$db = new SQLite3('some_db.db');
$query = $db->query('SELECT * FROM random_table');
$res['tableContent'] = "";
while ($row = $query->fetchArray (SQLITE3_ASSOC)) {
$res['tableContent'] .= "<tr><td>".$row['id']."</td><td>".$row['val']."</td></tr>";
}
$res['result'] = true;
echo json_encode($res);
?>
</pre>

Is it possible to return a table with some constraint in another .php page in ajax and show it in div

when i click the today button, it goes to updatetoday.php page where i select a query and display it in call back of an ajax and display the table in .php file to div with id #test. but it display's error as Uncaught TypeError: Illegal invocation
$(document).ready(function(){
$('#today').click(function()
{
alert("hi");
$.ajax({
url:'updatetoday.php',
data:{update:today}, // pass data
success:function(result)
{$( "#test" ).html(result);}
});
});
});
updatetoday.php
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['update']==today) //taking
{
echo "<table align='center' border='1' cellspacing='2'><tr><th>Book_id</th><th>Name</th><th>Phone Number</th><th>Email Address</th><th>Start Date</th><th>Source</th><th>Destination</th><th>Morning Time</th><th>Evening Time</th><th>Duration</th><th>Days Off</th><th>Date Off</th><th>Current Status</th><th>Call Counter</th><th>Option</th><th>Calender</th><th>Save</th></tr><br><br><br>
<?php
$query_book = 'Select * from `booking` where validity = 1 limit 5';
$result_book = mysql_query($query_book);
while($row = mysql_fetch_assoc($result_book))
{
$user_id = $row['user_id'];
// query for customer table
$query_cus = 'Select * from `customer` where user_id = $user_id limit 5';
$result_cus = mysql_query($query_cus);
$row_cus = mysql_fetch_assoc($result_cus);
$name = $row_cus['user_id'];
$email = $row_cus['email_id'];
$mobile_number = $row_cus['mobile_number'];
$current_status = $row['valid'];
$startdate = $row['start_date_timestamp'];
if($current_status == '1')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>Reg</p>';
}
else if($current_status == '2')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>New</p>';
}
else if ($current_status == '3.1' )
{
$status = '<p style='color:red;font-weight:600;font-size:19px'>R</p>';
}
?>
<tr align='center'><td class='bookid'><?=$row['book_id']?></td><td ><?=$row_cus['name']?></td><td ><?=$row_cus['mobile_number']?></td><td ><?=$row_cus['email_id']?></td><td><?=$row['start_date_timestamp']?></td><td ><?=$row['source']?></td><td ><?=$row['destination']?></td><td ><?=$row['mor_timestamp']?></td>
<td><?=$row['eve_timestamp']?></td><td><?=$row['duration']?></td><td ><?=$row['days_off']?></td><td ><?=$row['date_off']?></td>
<td><?=$row['current_status']?></td ><td ><?=$row['call_counter']?></td>
<td><select class='sel' name='select_option'><option value='NULL'>Select An Option</option><option value='taking'>Taking</option><option value='later-def'>Later Defined</option><option value='later-undef'>Later Undefined</option><option value='outofrange'>Out Of Range</option><option value='rejected'>Rejected</option><option value='norespond'>No Respond</option></select></td><td><input type='text' class='cal' size='6' disabled='disabled' value='<?=$startdate?>'/></td><td><button id='<?php echo $row['book_id'];?>' class='save'>Save</button></td></tr>
<?php
}//booking table while ends
echo '</table>';
?>
</div>";
}
?>
To fix your problem you must change the line :
data:{update:today}, // pass data
to :
data:{update:'today'}, // pass data
in your code today is a string not a varible
Change the line :
success:function(data)
to :
success:function(result)
You are assigning the result from the php to a variable called data and in
{$( "#test" ).html(result);}
trying to display inside the #test div a variable called result.

auto fill text field after pressing enter key

i got an useful tutorial where if you input 'id' [or first 1-2 letter of your id], the rest of form's field will filled automatically by pulling data from mysql database. this thing will happen without pressing ENTER key! now, what i'm trying to do is, i'll input the full 'id' & press ENTER key to fill the rest of form's field! what modification would need for this code below? here is my index.html file:
<html>
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var http; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
http = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var url = "getagentids.php?param=";
var idValue = document.getElementById("agid").value;
var myRandom = parseInt(Math.random()*99999999); // cache buster
http.open("GET", "getagentids.php?param=" + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
</script>
<form name="schform">
<table>
<tr>
<td>Contact ID:</td>
<td><input id="agid" type="text"
name="contactid" onKeyUp="ajaxFunction()"></td>
</tr>
<tr>
<td>Tel Number:</td>
<td><input id="agtel" type="text"
name="contacttel"></td>
</tr>
<tr>
<td>Name:</td>
<td><input id="agfn" type="text"
name="contactfullname"></td>
</tr>
<tr>
<td>Salutation:</td>
<td><input id="agsal" type="text"
name="contactsalutation"></td>
</tr>
<tr>
<td><input type="reset" value="Clear"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
and here is my getagentids.php file:
<?php
error_reporting(0); // turns off error reporting
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("contactdetail", $con);
mysql_select_db("contactdetail");
$param=$_GET['param'];
if (strlen($param) > 0) {
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
$agentname = $myrow["contactfullname"];
$agenttel = $myrow["contacttel"];
$agentsal = $myrow["contactsalutation"];
$agentid = $myrow["contactid"];
$textout .= $agentid . ", " . $agentname . ", " . $agenttel . ", " . $agentsal;
}
} else {
$textout = " , , ," . $param;
}
}
echo $textout;
?>
first create a javascript function to detect if the Enter key is pressed and call the ajaxFunction from within it:
function run(e) {
if (e.keyCode == 13) {
ajaxFunction();
return false; //disable the default Enter behavior
}
return true;
}
change the onKeyUp="ajaxFunction()" call in the Contact ID text input into onKeyUp="run()"
You can change your ajaxFunction like (just paste the code at the top of your ajaxFunction)
function ajaxFunction(e){
var e=e || window.event;
var keycode=e.which || e.keyCode;
if(keycode!==13 || (e.target||e.srcElement).value=='') return false;
// rest of your code
}​
And change your onKeyUp with this (notice event in the argument)
<input id="agid" type="text" name="contactid" onKeyUp="ajaxFunction(event)">​
Just for an idea.

Categories