While loop gets killed when refreshing div - javascript

I have this JavaScript code refreshing my watcher.php file every 5 seconds and that works great. The first page load is fine but after the 5 seconds and so on the while loop gets killed. Any reason?
index.php file
<script type="text/javascript">
var auto_refresh = setInterval(function(){
$('.view').load('watcher.php');
}, 5000); // refresh div time
</script>
<body>
<div class="view">
<?php include 'watcher.php'; ?>
</div>
</body>
...
watcher.php file
include 'config.php';
$sql = "SELECT id, name, available, will_return, status FROM check_in_out";
$result = $conn->query($sql);
echo '<div style="margin-top:35px;"><center>';
echo '<table class="pure-table">
<thead>
<tr>
<th>Name</th>
<th>Available</th>
<th>Status/Comments</th>
<th>I\'ll Return At:</th>
<th>Returned</th>
</thead>
</tr>
';
if ($result->num_rows > 0) {
$i = 1;
// output data of each row
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td><img style="vertical-align:middle" src="imgs/card.jpg"> <a class="various" href="#'.$i.'"/>'.$row["name"];'</a></td>';
echo "<td>";
if ($row['available'] == 1) {
echo "<img src='imgs/available.gif'/>";
echo "Online";
} else {
echo "<img src='imgs/not-available.gif'/>";
echo "<span style='vertical-align:middle'>Away</span>";
};
echo "</td>";
echo '<td>'.$row["status"];'</td>';
echo '<td>'.$row["will_return"];'</td>';
echo '<td></td>';
echo '</tr>';
echo '<div align="center" id="'.$i++.'" style="display:none;width:520px;">
<h2>'.$row["name"].'</h2>
<!-- <h4>Current Status: '.$row["status"].'</h4> -->
<form method="post" action="statusChange.php" />
<input type="hidden" value="'.$row["id"].'" name="id"/>
<textarea rows="4" cols="50" placeholder="Enter Comment/Status Here..." name="comment"></textarea>
<br/><br/>
When will you return? - <input type="time" name="e_time">
<br/><br/>
<input class="pure-button pure-button-primary" type="submit" value="Leave/Return">
</form>
</div>';
}
} else {
echo "0 employees";
}
echo '</tr></table>';
echo '</div></center>';
$conn->close();
UPDATE:
What is by this is that look at image below. You will notice that after the first load (5 seconds) the clickable (href) gets killed...

<script type="text/javascript">
var updateWatcher = function() {
$.ajax({
url: 'watcher.php',
success: function(response) {
$('.view').html(response);
window.setTimeout(function(){
updateWatcher();
}, 3500);
}
});
}
updateWatcher();
</script>
Granted, this could be solved more elegantly with something like promises, but as far as a simple fix you could try something like this where the timer is only setup once the response has been successfully received. This should be more reliable.
Here is a simple fiddle: http://jsfiddle.net/agentfitz/26mahomm/3/ (look in the console).

Related

Create a text form inside table row that stays after submission and updates database

I want to create a column that has a text box inside each table row. The user can write any text inside the text box and click the 'Save' button to save it in the database. Additionally, the text box can be edited unlimited times. My code is the following:
index.php
<?php
...
while($row = $result->fetch_assoc()){
echo "<form action= 'search.php' method='post'>";
echo "<form action='' method='get'>";
echo "<tr>
<td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
<td> ".$row['test_id']." </td>
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
<td> ".$row['path']." </td>
<td> ".$row['video1_path']." </td>
<td> ".$row['video2_path']." </td>
<td> ".$row['video3_path']." </td>
<td> ".$row['video4_path']." </td>";
if(empty($row["directory"])){
echo "<td></td>";
}else {
echo "<td><div><button class='href' id='" . $row['test_id'] . "' >View Report</button><div></td>";
}
echo " <td style='display: none;'> ".$row['directory']." </td>
</tr>";
}
?>
</table> <br>
<input id= 'select_btn' type='submit' name='submit' value='Submit' class='w3-button w3-blue'/>
</form>
</form>
</div>
<!-- Opens the pdf file from the pdf_report column that is hidden -->
<script type="text/javascript">
$(document).on('click', '.href', function(){
var result = $(this).attr('id');
if(result) {
var dir = $(this).closest('tr').find("td:nth-child(9)").text();
window.open(dir);
return false;
}
});
</script>
<!-- Updates text input to database -->
<script type="text/javascript">
$(document).on('click', '.name', function(){
var fcookie1= 'mycookie1';
var fcookie2= 'mycookie2';
var name = $(this).attr('id');
if(name) {
var text1 = $(this).closest('tr').find("td:nth-child(2)").text();
var text2 = $(this).closest('tr').find("td:nth-child(3)").text();
document.cookie='fcookie1='+text1;
document.cookie='fcookie='+text2;
$.ajax({
url: "name_edit.php",
type:"GET",
success: function() {
// alert("Edited Database");
}
});
}
});
</script>
name_edit.php
<?php include 'dbh.php' ?>
<?php include 'search.php' ?>
<?php
if (isset($_COOKIE["fcookie1"]))
echo $_COOKIE["fcookie1"];
else
echo "Cookie Not Set";
if (isset($_COOKIE["fcookie2"]))
echo $_COOKIE["fcookie2"];
else
echo "Cookie Not Set";
$var1 = $_COOKIE["fcookie1"];
$var2 = $_COOKIE["fcookie2"];
$conn = mysqli_connect($servername, $username, $password, $database);
$sql = "UPDATE test_data SET name='$var2' WHERE id='$var1'";
$query_run= mysqli_query($conn,$sql);
if($query_run){
echo '<script type="text/javascript"> alert(Data Updated)</script>';
} else {
echo '<script type="text/javascript"> alert(Data Not Updated)</script>';
}
?>
My idea was for the user to write any text. Then i will 'grab' the text and its expected id and save it to a cookie, when the save button is clicked. The cookie will then be echoed in name_edit.php and insert it in the sql code which will then update my database.
Im not sure what to include in 'value' inside the form tag. If there is data inside the database then display it inside the text box which can also be edited, else display blank for a text to be inserted.
I am new to coding and I'm a bit confused if my idea is correct or should i approach it another way.
I did some research and found out i did not have to use form but instead use 'contenteditable'. To edit the specific column i changed
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
to this:
<td class='name' data-id1='" . $row['test_id'] . "' contenteditable='true'>".$row['name']."</td>
and for my jquery i added the following:
<style>
.editMode{
border: 1px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Add Class
$('.name').click(function(){
$(this).addClass('editMode');
});
// Save data
$(".name").focusout(function(){
$(this).removeClass("editMode");
var id = $(this).closest('tr').find("td:nth-child(2)").text();;
var value = $(this).text();
$.ajax({
url: 'name_edit.php',
type: 'post',
data: { value:value, id:id },
success:function(response){
alert('Edits Saved');
return false;
}
});
});
});
</script>
and in the php side, i simply did the following:
<?php include 'dbh.php' ?>
<?php
$conn = mysqli_connect($servername, $username, $password, $database);
$field = $_POST['field'];
$value = $_POST['value'];
$id= $_POST['id'];
$sql = "UPDATE test_data SET name='".$value."' WHERE test_id='".$id."'";
mysqli_query($conn,$sql);
echo 1;
?>

JavaScript values to another PHP page

i m trying to send a value from one page to another by using java script, where the user is redirected to the other php page oncick,
the problem i m having is sending a value to the other page
the code on 1st page is
<html>
<body>
<div id="management" onclick="myFunction()" class="col-md-2">
<p>Management</p>
</div>
<script>
function myFunction() {
var search="Assam";
location.href = "search.php";
}
</script>
</body>
</html>
and i want the value of search to be forwarded to the second search.php page
$search=how do i get the variable here;
$query = $pdo->prepare("select * from collegetable where name LIKE '%$search%' OR courses LIKE '%$search%' OR address LIKE '%$search%' OR affiliation LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">College Names</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Courses</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['courses'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['fees'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
use query string for forward to second page
<html>
<body>
<div id="management" onclick="myFunction()" class="col-md-2">
<p>Management</p>
</div>
<script>
function myFunction() {
var search="Assam";
location.href = "search.php?q=" + search;
}
</script>
</body>
</html>
and in second page get q from URL
$search= $_GET['q'];
$query = $pdo->prepare("select * from collegetable where name LIKE '%$search%' OR courses LIKE '%$search%' OR address LIKE '%$search%' OR affiliation LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">College Names</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Courses</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['courses'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['fees'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
U may use get parameters of url, for example:
<script>
function myFunction() {
var search="Assam";
location.href = "search.php?q=" + search;
}
</script>
To get parameters on search.php use $_GET method http://php.net/manual/en/reserved.variables.get.php
$search = $_GET['q'];
Ajax is the solution for you.
Plain ajax looks like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
I would recommend using the jquery ajax, because it's way more simple and beginner friendly.
An example for your use case would look like this:
<script>
var search="Assam";
$.ajax({
method: "GET",
url: "some.php?search=" + urlencode(search)
}) .done(function( response ) {
$("#field-for-response").html(response);
});
</script>
In PhP you can read the value over $_GET["search"]. If you just want to locate the client just on the php page, you should have a look on this, but Ajax gives you the advantage of no need to reload the page and this is what makes the user experience much smoother.
Try this
Javascript
$scope.submitForm = function (form, e) {
if(form.$valid){
// e.preventDefault(e);
$http({
method : "POST",
url : "search.php",
data: {
"givenName":"james",
"displayName":"Cameroon"
},
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, X-Requested-With",
"Content-Type": "application/json"
}}).then(function(response) {
console.log(response);
}, function(response) {
console.log("Error"+response);
});
}
}
HTML
<form id="attributeVerification" name="vm.attributeVerification" onsubmit="submitForm(vm.attributeVerification)" novalidate>
<div class="attr" id="attributeList">
<ul>
<li>
<div class="attrEntry">
<label for="givenName">First name</label>
<div class="helpText" role="alert" aria-live="polite" tabindex="1">This information is required.</div>
<input id="givenName" name="givenName" class="textInput" type="text" placeholder="First name" title="Your given name (also known as first name)." required maxlength="15" ng-model="userInfo.givenName" aria-required="true">
</div>
</li>
<li>
<div class="attrEntry">
<label for="displayName">Last name</label>
<div class="helpText" role="alert" aria-live="polite" tabindex="1">This information is required.</div>
<input id="displayName" name="displayName" class="textInput" type="text" placeholder="Last name" title="Your display name." required maxlength="25" ng-model="userInfo.displayName" aria-required="true">
</div>
</li>
</ul>
</div>
<div class="buttons">
<button id="continue" aria-label="Create" type="submit">Continue</button>
</div>
</form>
change html to :
<html>
<body>
<div id="management" onclick="myFunction()" class="col-md-2">
<p>Management</p>
</div>
<script>
function myFunction() {
var search="Assam";
location.href = "search.php?search="+search;
}
</script>
</body>
</html>
php to :
$search = $_GET['search'];
$query = $pdo->prepare("select * from collegetable where name LIKE '%$search%' OR courses LIKE '%$search%' OR address LIKE '%$search%' OR affiliation LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">College Names</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Courses</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['courses'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['fees'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}

submit form not working/ not reload

i create a form(form1) to search mysql data into table without reload the page using ajax, it's working fine, but when i want to insert data from the second form(formorder) the submit button not refresh or reload.
this my code
index.php
<html>
<head>
<title>Search Data Without Page Refresh</title>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
</head>
<body>
<center>
<br>
<?php include("koneksi1.php");
$sql="select * from supplier";
$query=mysqli_query($koneksi,$sql);
?>
<form action="" name = "form1">
<select name="namea" style="width:300px; padding:8px;">
<?php
while($data=mysqli_fetch_assoc($query)){
echo "<option value='".$data['id_supplier']."'>".$data['id_supplier']."</option>";
}
?>
</select>
<input type="submit" value="Search" id="search-btn" style="padding:8px;"/>
</form>
<br>
<div id = "s-results">
<!-- Search results here! -->
</div>
<script type = "text/javascript">
$(document).ready(function(){
$('#s-results').load('search.php').show();
$('#search-btn').click(function(){
showValues();
});
$(function() {
$('form').bind('submit',function(){
showValues();
return false;
});
});
function showValues() {
$.post('search.php', { namea: form1.namea.value },
function(result){
$('#s-results').html(result).show();
});
}
});
</script>
</center>
</body>
</html>
search.php
<?php
include("koneksi1.php");
isset( $_REQUEST['namea'] ) ? $name=$_REQUEST['namea'] : $name='';
$name = mysqli_real_escape_string($koneksi,$name);
if( empty( $name )){
echo '<script> alert("Please search something!")</script>';
}else{
$sql = "select * from barang where id_supplier like '%$name%'";
$rs = mysqli_query($koneksi,$sql ) or die('Database Error: ' . mysql_error());
$num = mysqli_num_rows($rs);
if($num >= 1 ){
echo "<div style='margin:10px; color:green; font-weight: bold;'>$num records found!</div>";
echo "<table width='365' border ='0' cellspacing='5' cellpadding='5'>";
echo"<tr><th>RESULTS</th></tr>";
echo "<div class='table-responsive'>";
echo "<table class='table table-hover'>";
while($data = mysqli_fetch_array( $rs )){
?>
<tbody>
<?php
$kuantitas=0;
$kuantitas++;
?>
<form action="aksi.php" method="post" id="formorder">
<tr>
<td><?php echo $data['nama_barang']?></td>
<td><?php echo $data['stok']?></td>
<td><input type="text" name="kuantitas" size="4"></td>
<td><input type="text" name="harga_satuan" id="harga_satuan" size="10"></td>
<td><input type="text" name="ppn" id="ppn" size="3"> %</td>
<td><button type="submit" class="btn btn-success btn-sm" id="add" name="add">ADD</button></td>
</tr>
</form>
<?php }?>
</tbody>
</table>
</div>
<?php
}else{
echo "<tr><th>NO RESULTS</th></tr>";
}
}
?>
the button submit in formorder not working, what wrong with my code???

checked checkbox will remain through pagination

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

Passing an id to a PHP script using jQuery/Ajax

This is the code that the user have a participation with.
<html>
<head>
<title></title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery.form.js"></script>
</head>
<body>
<?php
include 'connection.php';
$sql="SELECT * FROM blog";
$result=mysqli_query($link, $sql);
if(!$result)
{
$output='Error fetching students:'.mysqli_error($link);
}
?>
<div id="table">
<table border='1' cellpadding='10' id="table">
<tr>
<td><b>Title<b></td>
<td><b>Edit<b></td>
<td><b>Delete<b></td>
</tr>
<?php
while($row=mysqli_fetch_array($result))
{
echo '<tr class="record">';
echo '<td>'.$row['articletitle'] .'';
echo '<td>Edit';
echo "<input type='hidden' name='id' value='".$row['articleid']."'></td>";
echo '<td><div align="center">Delete</div></td>';
echo "</tr>\n";
}
echo '<form method="post" id="myForm" action="postview.php">';
echo '<input type="hidden" name="myID">';
echo '</form>';
?>
</table>
<button id="addrecord">Add New Post</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#addrecord").click(function(){
$("#table").load("addpost.php");
$("#addrecord").hide();
});//add
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){}
});//ajax
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});//delete
$(".title").click(function(){
$('[name=myID]').val($(this).attr('id'));
$('#myForm').submit();
});//view
$(".edit").click(function(){
var data=$("#tryform").serialize();
$.ajax({
type: "POST",
url: "editpost.php",
data: data
}).done(function( msg ) {
$("#table").html(msg);
});//ajax
});//delete
});
</script>
</body>
</html>
and this the PHP script that the code above redirect to.
<?php
include 'connection.php';
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
?>
I'm having this kind of error:
Undefined index: id in C:\xampp\htdocs\ckeditor\samples\postview.php on line 4
You need to check if argument "id" is passed to the php script first
<?php
include 'connection.php';
if( (isset($_GET['id'])) && ($_GET['id'] != '') ){ //check if the argument "id" is passed to the script
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
}
?>
Not so much an answer to your question, but probably a good suggestion to make your code a lot cleaner- try using PHP Alternative Syntax and moving in and out of PHP to make your HTML clean.
<?php while($row=mysqli_fetch_array($result)):?>
<tr class="record">';
<td><?php echo $row['articletitle'];?>
<td>Edit
<input type='hidden' name='id' value='<?php echo $row['articleid'];?>'></td>
<td>
<div align="center">
Delete
</div>
</td>
</tr>
<?php endwhile;?>
<form method="post" id="myForm" action="postview.php">
<input type="hidden" name="myID">
</form>
$sql="SELECT * FROM blog WHERE articleid='".$id."'";
try this line
That isnt an error, but a notice, which is lowlevel It simple means $_GET['id'] doesnt hav a value
echo $example['something']; // will give undefined index notice
$example['something'] = 'abc';
echo $example['something']; // No notices
Your website should be domain.ext/?id=123, if not, this notice will show.

Categories

Resources