How can I pass php variable into ajax function - php

How can I pass id="'.$row["courseid"].'" into the ajax function,
I'm trying data:{'courseid':deleteId}, but is not working any ideas on how to fix this problem.
<?php
echo "<table width='100%'>";
echo "<tr>
<th>Course name</th>
<th>Delete</th>
<th>Edit</th>
</tr>";
?>
<?php foreach($rows as $row):
echo "<tr>";
echo '<td>' . htmlentities($row['coursename'], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td><button onclick="deleteC(' . $row['courseid'] . ')");"><font color="#e70404"> Delete </font> </button></td>';
echo '<td><a class="delete" id="'.$row["courseid"].'">Delette</a></td>';
echo "</tr> ";
endforeach;
echo "</table>";
?>
And this is the ajax function which is in the same page
<script type="text/javascript">
function deleteC(deleteId){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data:{'courseid':deleteId},
success: function(result){
if(result=='correct'){
window.location='index.php';
}else {
window.location='coursesData.php';
}
}
});
}
</script>
This is the deleteCourse.php
<?php
require("connect.php");
if (isset($_GET['courseid']) && is_numeric($_GET['courseid']))
{
$id = $_GET['courseid'];
echo"$courseid";
$con=mysqli_connect("localhost","root","","independentstudyclass");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM courses WHERE courseid=$id");
echo "correct";
mysqli_close($con);
echo "correct";
}
else
{
header ("Location: ../index.php");
}
?>

Instead of this:
echo '<td><font color="#e70404"> Delete </font> </td>';
Just pass the id to the JS function as a parameter and use it:
PHP:
echo '<td><font color="#e70404"> Delete </font> </td>';
JS
function deleteC(deleteId){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data:{'courseid':deleteId},
success: function(result){
if(result=='correct'){
window.location='index.php';
} else {
}
}
});
}

Related

Query String PHP

I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>

delete button is not working

I am going to delete the particular row of my database, but when i delete the button it tells me that undefined display in deletebookajax.php on line no 54..
So can u please tell me where i have gone wrong...
here is my code
book.php is for displaying the entire book details....
<?php
include('assets/page_header.php');
include('db/db.php');
?>
<html>
<head><title></title>
<style>
h1 {
text-align:center;
}
</style>
</head>
<h1>BOOKS PAGE</h1>
<?php
error_reporting(0);
$str="select * from books";
$query1=mysql_query($str);
$q=mysql_num_rows($query1);
//$query2=mysql_query("select status from bookrentalinfo where bookid=$bookid");
//echo $query2;
//$res=mysql_fetch_array($query2);
echo "<table align='center'>";
echo "<tr><th>BookID</th><th>Title</th><th>Author</th><th>Publisher</th><th>Numcopies</th><th>Shelfno</th><th>Status</th><th colspan=2 >Action</th></tr>";
while($rows=mysql_fetch_array($query1))
{
echo "<tr>";
echo "<td>".$rows['bookid']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td>".$rows['author']."</td>";
echo "<td>".$rows['publisher']."</td>";
echo "<td>".$rows['numcopies']."</td>";
echo "<td>".$rows['shelfno']."</td>";
echo "<td>".$rows['status']."</td>";
echo "<td><button class='button1' data-toggle='tooltip' title='Delete' id=".$rows['bookid']." value='delete' name='delete'><img id='image' src='./images/trash.png'/></button></td>";
echo "<td><a id='colour' class='tooltip' href='edit1form.php?book_id=".$rows['bookid']."'><img id='image' src='./images/small.gif'/><span class='tooltiptext' >Edit</span></a></td>";
echo "</tr>";
}
echo "</table>";
?>
<div id="display">
</div>
<!--echo "<td><button type='button'>delete</button></td>";
/*if($res['status']=="BORROWED")
{
echo "Sorry You Can't Delete The Book";
}
else
{
echo "The Row Is Deleted";
}*/-->
<script type="text/javascript">
$('document').ready(function() {
$(".button1").click(function(e) {
$('[data-toggle="tooltip"]').tooltip();
var strconfirm = confirm("Are you sure you want to delete?");
if(strconfirm)
{
var bookid=$(this).attr("id");
alert(bookid);
dataString='book_id='+bookid;
alert(dataString);
// AJAX Code To Submit Form.
$.ajax({
type: "GET",
url: "db/deletebookajax.php",
data: dataString,
cache: false,
success: function(result){
alert("submitted"+result);
$('#display').html(result);
window.location.href="books.php";
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
else {
return false;
}
});
});
</script>
</body>
</html>
deletebookajax.php
<?php
if(isset($_GET['book_id']))
{
$bookid = $_GET['book_id'];
echo $bookid;
}
include('../assets/page_header.php');
?>
<input type="hidden" name="bookid" value=<?php if(isset($bookid)) echo $bookid; ?>>
<?php
include('db.php');
//if(isset($_POST['bookid']))
//
//$bookid=mysql_real_escape_string($_POST['bookid']);
$delete = "delete from books WHERE bookid=$bookid";
$query1=mysql_query($delete);
echo $query1;
if($query1)
{
$q=mysql_query("select * from books");
echo $q;
$display="<table>";
$display.="<tr><th>BookID</th><th>Title</th><th>Author</th><th>Publisher</th><th>numcopies</th><th>shelfno</th><th>status</th><th>Action</th></tr>";
while($row=mysql_fetch_array($q))
{
$display.="<tr>";
$display.= "<td>".$row['bookid']."</td>";
$display.= "<td>".$row['title']."</td>";
$display.= "<td>".$row['author']."</td>";
$display.= "<td>".$row['publisher']."</td>";
$display.="<td>".$row['numcopies']."</td>";
$display.="<td>".$row['shelfno']."</td>";
$display.="<td>".$row['status']."</td>";
$display.= "</tr>";
}
$display.="</table>";
}
else
{
$display.= "U can't delete The book";
}
//echo "nothing";
echo $display;
?>
</body>
</html>
Change Your deletebookajax.php code
<?php
if(isset($_GET['book_id']))
{
$bookid = $_GET['book_id'];
echo $bookid;
}
include('../assets/page_header.php');
?>
<input type="hidden" name="bookid" value=<?php if(isset($bookid)) echo $bookid; ?>>
<?php
//include('db.php');
//if(isset($_POST['bookid']))
//
//$bookid=mysql_real_escape_string($_POST['bookid']);
$user="root";
$server="localhost";
$password="";
$db="library book";
$dbconn = mysqli_connect($server,$user,$password,$db);
$delete = "delete from books WHERE bookid=$bookid";
$query1=mysqli_query($dbconn, $delete);
echo $query1;
if($query1)
{
$q=mysqli_query($dbconn, "select * from books");
echo $q;
$display="<table>";
$display.="<tr><th>BookID</th><th>Title</th><th>Author</th><th>Publisher</th><th>numcopies</th><th>shelfno</th><th>status</th><th>Action</th></tr>";
while($row=mysqli_fetch_array($dbconn, $q))
{
$display.="<tr>";
$display.= "<td>".$row['bookid']."</td>";
$display.= "<td>".$row['title']."</td>";
$display.= "<td>".$row['author']."</td>";
$display.= "<td>".$row['publisher']."</td>";
$display.="<td>".$row['numcopies']."</td>";
$display.="<td>".$row['shelfno']."</td>";
$display.="<td>".$row['status']."</td>";
$display.= "</tr>";
}
$display.="</table>";
}
else
{
$display = "U can't delete The book";
}
//echo "nothing";
echo $display;
?>
</body>
</html>

Update using checkbox using jquery

I'm trying to update my course_code into my database when the checkbox checked but it fail. I tried to modify from others but seem like I make mistake. can anyone tell me what is the problem?
here is my assigncourse.php
<?php require_once("../includes/session.php"); ?>
<?php require_once("sessioncourse.php"); ?>
<?php $course_codefac = $_SESSION['course_code'] ; ?>
<?php confirm_logged_in(); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function Change(id) {
$.ajax({
type: "GET",
url: "updateassigncourse.php",
data: {"id": id},
'success': function (response) {
console.log(response);
//TODO: use server response
}
});
};
</script>
<?php include("includes/header.php"); ?>
<div id="main">
<div class="full_w">
<?php
$querysel = "SELECT * FROM tblstudent ORDER BY student_id " ;
$resultsel = mysql_query($querysel, $connection);
echo "<h2><div class=\"h_title\">Please tick the student to join this
".$course_codefac." course</div></h2>";
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th scope=\"col\">Matric ID</th>";
echo "<th scope=\"col\">Name</th>";
echo "<th scope=\"col\">Assign</th>";
echo "</tr>";
echo "</thead>";
while($rowsel = mysql_fetch_array($resultsel)){
if($rowsel['course_code'] == NULL){
$id = $rowsel['id'];
echo "<tr>";
echo "<tr>"."<td class=\"align-center\">".$rowsel['student_id']."
</td>";
echo "<td class=\"align-center\">".$rowsel['name']."</td>";
echo "<td class=\"align-center\">";
echo "<input type=\"checkbox\" onchange=\"javascript:
Change($id);\">";
echo "</td>";
}
}
echo "</table>";
?>
</div>
</div>
<?php include("includes/footer.php"); ?>
then here is my updateassigncourse.php
<?php require_once("../includes/session.php"); ?>
<?php require_once("sessioncourse.php"); ?>
<?php $course_codeapp = $_SESSION['course_code'] ; ?>
<?php confirm_logged_in(); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$id = $_GET['id'];
$course = $course_codeapp;
$sql="UPDATE tblstudent set course_code = ". mysql_real_escape_string($course)
." WHERE id = " .mysql_real_escape_string($id);
$result = mysql_query($sql);
?>
If this is your exact code, then there is a missing ';'
$course = $course_codeapp
it should have been
$course = $course_codeapp;

jquery table reload after ajax call

I am trying to reload a table instead of reloading the whole page
here is my code
<link href="assets/css/bootstrap.min.css" rel="stylesheet" >
<script src="assets/js/bootstrap.min.js"></script>
<input id="check" value="" placeholder="Enter your number here" />
<button type="button" id="go_check" class="btn btn-success" data-loading-text="Loading..." > <i class="icon-ok icon-white"></i> Check</button>
<span id="button"></span>
<br/>
<div id="response">
</div>
<script>
jQuery(document).ready(function() {
jQuery('#go_check').click(function() {
jQuery('#go_check').button('loading');
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "check",
number: jQuery('#check').val()
}),
dataType: "json",
success: function(data) {
jQuery('#button').html(data.btn);
jQuery('#go_check').button('reset');
jQuery('#response').html(data.html);
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
});
});
function delete_item($id) {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "delete",
number: $id
}),
dataType: "json",
success: function(data) {
jQuery('#button').html('');
window.location.reload(); // would like to replace this line with the table refresh
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
}
</script>
<link href="assets/css/jquery.dataTables.css" rel="stylesheet" media="screen">
<link href="assets/css/jquery.dataTables_themeroller.css" rel="stylesheet" media="screen">
<script src="assets/js/jquery.dataTables.min.js"></script>
<table class="table" id="tad">
<thead>
<th>
Order Id
</th>
<th>
Ticket Name
</th>
<th>
Ticket Number
</th>
<th>
Product
</th>
<th>
Model
</th>
<th>
Option Name
</th>
<th>
Option
</th>
<th>
Customer
</th>
<th>
Email
</th>
<th>
Telephone
</th>
<th>
Date
</th>
</thead>
<tbody>
<?php
include "config.php";
$con = mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
mysql_select_db(DB_DATABASE, $con);
$result = mysql_query("select * from order_serial ", $con);
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['order_id'];
echo "</td>";
echo "<td>" . $row['serial_name'];
echo "</td>";
echo "<td>" . $row['product_serial'];
echo "</td>";
echo "<td>" . $row['name'];
echo "</td>";
echo "<td>" . $row['model'];
echo "</td>";
echo "<td>" . $row['option_name'];
echo "</td>";
echo "<td>" . $row['option_value'];
echo "</td>";
echo "<td>" . $row['firstname'] . " " . $row['lastname'];
echo "</td>";
echo "<td>" . $row['email'];
echo "</td>";
echo "<td>" . $row['telephone'];
echo "</td>";
echo "<td>" . $row['date'];
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<script>
jQuery(document).ready(function() {
$('#tad').dataTable({
"sDom": 'R<"H"lfr>t<"F"ip>',
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
</script>
</tbody>
</table>
I have searched for the answer and cant seem to find one it seems a bit silly to reload the whole page instead of just the table ?
Here we can separate the table loading as a separate method and call it on both the go_check button click and after successful deletion of the item.
jQuery(document).ready(function() {
function loadTable(){
jQuery('#go_check').button('loading');
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "check",
number: jQuery('#check').val()
}),
dataType: "json",
success: function(data) {
jQuery('#button').html(data.btn);
jQuery('#go_check').button('reset');
jQuery('#response').html(data.html);
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
}
jQuery('#go_check').click(loadTable);
});
function delete_item($id) {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "delete",
number: $id
}),
dataType: "json",
success: function(data) {
jQuery('#button').html('');
loadTable();
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
}
Use the sAjaxSource of datatables rather than seperate ajax call to ajax.php
"sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php"

Set approval for admin with checkbox using php,jquery and ajax

I am working in a project where i want to show only those products to user which are selected by admin from database. Actualy i want to set the approval 1 or 0 in database when admin check or unchecked that checkbox.
jobs.php
$(document).ready(function(){
$('input.check').click(function(){
if($("input.check").is(':checked'))
{
$id = $(this).attr("id");
$.post("handle.php",{action:"checked",id:$id},function(data){
alert("Peoduct is set to display...");
});
}
else
{
alert("unchecked");
$id = $(this).attr("id");
$.post("handle.php",{action:"unchecked",id:$id},function(data){
alert("Peoduct is un-set to display...");
});
}
});
});
<?php
$dbqry = mysql_query("select * from job_category");
echo "<table width='50%', border='2'>
<tr>
<th>Catergory ID</th>
<th>Category Name</th>
<th>Remove</th>
<th>Update</th>
<th>Approval</th>
</tr>";
if($dbqry)
{
while($row = mysql_fetch_array($dbqry))
{
echo "<tr>";
echo "<td align='center'>" . $row['c_id'] . "</td>";
echo "<td align='center'>" . $row['cat_name'] ."</td>";
$cid = $row['c_id'];
$aprv = $row['approval'];
echo "<td align='center'><a href='remove.php?action=cat_remove&cid=$cid'>Remove</a></td>";
echo "<td align='center'>
<a href='Update-form.php?action=cat_update&cid=$cid'>Update</a></td>";
?>
<td align="center">
<input type='checkbox' name='approval' value='approval' id ="<? echo $cid; ?>" class="check"/>
</td>
</tr>
<?
}
echo "</table>";
echo '<br/>';
echo "<a href='add.php?action=cat_add'>Add New Category</a>";
}
else
{
die(mysql_error());
}
?>`
handle.php
`<?php
include 'include/connection.php';
$action = $_POST['action'];
$id = $_POST['id'];
//echo $action;
if($action == "checked")
{
$query = "update job_category set approval=1 where c_id=$id";
$result = mysql_query($query);
if(!$result)
{
echo die(mysql_error());
}
}
else if($action == "unchecked")
{
$query = "update job_category set approval=0 where c_id=$id";
$result = mysql_query($query);
if(!$result)
{
echo die(mysql_error());
}
}
?>`
Its working but when i refresh the page or seletc the URL and press enter then all the checked data appears unchecked even after that it does not change value of approval from 1 to 0 in database, but still it make me confuse about which items are checked or unchecked. Any suggestion will be appreciated.
modify checkbox line to show checked if approval=1 in database... try this
<input type='checkbox' name='approval' value='approval' <?php if($row["approval"]==1){ echo "checked=\"checked\"";}) ?> id ="<? echo $cid; ?>" class="check"/>
html
<input type='checkbox' name='approval' value='approval' <?php echo $row["approval"]?"checked=\"checked\"":'';?> id ="<? echo $cid; ?>" class="check"/>
then add js
$(function(){
$('input[type=checkbox]').each(function(){
if($(this).attr('checked') && $(this).attr('checked')=='checked'){
$(this).attr('checked', true);
}else{
$(this).attr('checked', false);
}
})
})
and
if($("input.check").is(':checked'))
to
if($(this).is(':checked'))

Categories