How to delete record using ajax? - javascript

I am trying to delete record from database using AJAX. The confirmation window does not appear so that the record can be deleted. here is the code..
<?php
$q = $_GET['q'];
$p = $_GET['p'];
$sql="SELECT * FROM course_details WHERE sem='" . $q . "' AND branch='" . $p . "' ORDER BY course_codes ASC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
echo '<tr class="record">';
echo "<td>" . $row['course_codes'] . "</td>";
echo "<td>" . $row['course_names'] . "</td>";
echo "<td>" . $row['course_instructors'] . "</td>";
echo "<td>" . $row['course_credits'] . "</td>";
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
echo "</table>";
mysql_close($bd);
?>
Here $p and $q are send by an AJAX script from another page. It is working fine. The records are displayed as expected. Deletion works using AJAX if i do not use AJAX to display records.The script I am using to delete is:
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
deleteCourse.php
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = '$id'";
$result = mysql_query($del);

The problem is because you are creating dynamic elements so you have to use a delagate $(document).on() inorder to bind the click event to the elements.
Here is the corrected code
<script type="text/javascript">
$(function() {
$(document).on('click','.delbutton',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data: info,
success: function(){ }
});
}
return false;
});
});
</script>
and your deletCourse.php
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = ".$id."";
$result = mysql_query($del);
Hope this helps, Thank you

try this one
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
delete
delete
delete
delete
delete
javascript
function del(id)
{
var info = 'id=' + id;
if(confirm("Are you sure you want to delete this Record?")){
var html = $.ajax({
type: "POST",
url: "delete.php",
data: info,
async: false
}).responseText;
if(html == "success")
{
$("#delete").html("delete success.");
return true;
}
else
{
$("#captchaStatus").html("incorrect. Please try again");
return false;
}
}
}
ajax file
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = '$id'";
$result = mysql_query($del);
if($result)
{
echo "success";
}

Try this:
<script type="text/javascript" src="jquery.js"></script>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function del(id)
{
var info = 'id=' + id;
if(confirm("Are you sure you want to delete this Record?")){
var html = $.ajax({
type: "GET",
url: "deletCourse.php",
data: info,
async: false ,
success: function() {
window.location.reload(true);}
}).responseText;
}
}
</script>
<?php
$link=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("cart");
$sql=mysql_query("SELECT * FROM `details`");
echo "<table>";
echo "<tr><th>Name</th><th>NO of Items</th></tr>";
while($row = mysql_fetch_assoc($sql)){
echo '<tr class="record">';
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['num'] . "</td>";
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
echo "</table>";
mysql_close($link);
?>

Related

Function is not defined when the html is load from another page with ajax

I have a table in one page and i fetch with the rows of a database with ajax, i have a button and onclick he does a function named deleteRow() but when i click says that deleteRow() is not defined.
Page where i want to show the table:
<table>
<thead>
<td>Id</td>
<td>Nome</td>
<td>email</td>
<td>numero</td>
<td>data</td>
<td>hora</td>
</thead>
<tbody>
</tbody>
</table>
<script>
$(document).ready(function(){
update();
setInterval(function(){update()}, 10000);
function update(){
$.ajax({
type: 'post',
url: 'getReservas.php',
success: function (response) {
$("table").children("tbody").html(response);
}
});
}
function deleteRow(elem){
console.log("oi");
var isto = elem;
var id = isto.attr("id");
$.ajax({
type: "POST",
url: "deleteReserva.php",
data: id,
success: function(data){
isto.remove();
}
});
}
});
</script>
getReservas.php
<?php
include "conexaoBaseDados.php";
$query = $mysqli->query("SELECT * FROM reservas");
$dados = array();
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$dados[] = $row;
}
foreach($dados as $r){
echo "<tr>";
echo "<td onclick='deleteRow(this);' id=". $r["id"] .">" . $r['id'] . "</td>";
echo "<td>" . $r['nomeCliente'] . "</td>";
echo "<td>" . $r['emailCliente'] . "</td>";
echo "<td>" . $r['numeroCliente'] . "</td>";
echo "<td>" . $r['dataReserva'] . "</td>";
echo "<td>" . $r['horaReserva'] . "</td>";
echo "</tr>";
}
}
?>
The deleteRow() function is defined inside the ready callback, so it only exists inside that callback's scope.
You need to move the deleteRow function code to an outer scope.
For example -
<script>
function deleteRow(elem){
console.log("oi");
var isto = elem;
var id = isto.attr("id");
$.ajax({
type: "POST",
url: "deleteReserva.php",
data: id,
success: function(data){
isto.remove();
}
});
}
$(document).ready(function(){
update();
setInterval(function(){update()}, 10000);
function update(){
$.ajax({
type: 'post',
url: 'getReservas.php',
success: function (response) {
$("table").children("tbody").html(response);
}
});
}
});
</script>

Passing value from JS to PHP

Passing a table cell value from javascript variable into php variable.
<script>
$(document).on('ready',function(){
$('#business_list_table').on('click','.view_btn',function (){
$.ajax({
url: "test.php",
method: "POST",
data:{business_id : "6510-1"},
success: function (data){
$('#business_permit_table').html(data);
}
});
});
});
<?php
$business_id = $_GET["business_id"];
echo $business_id;
You cannot use JS variable directly to PHP like that. use ajax instead:
JS
$("#business_list_table").on('click', '.view_btn', function post() {
// get the current row
var currentRow = $(this).closest("tr");
var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
$.post('', {Business_ID: Business_id_value}, function(result){
$('table tbody').html(result);
});
});
PHP
if (isset($_POST['Business_ID'])) {
$Business_ID = $_POST['Business_ID'];
$conn = mysqli_connect("localhost", "root", "", "bpsystem");
if ($conn->connect_error) {
die("Database connection failed:" . $conn->connect_error);
} else {
$sql = "SELECT * FROM business_tb WHERE Business_ID='$Business_ID';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr >";
echo "<td>BUSINESS NAME</td>";
echo "<td>" . $row['Business_Name'] . "</td>";
echo "</tr>";
echo "<tr >";
echo "</tr>";
}
}
}
}
You can use the query string to pass the variable to PHP. Like this,
$("#business_list_table").on('click', '.view_btn', function post() {
// get the current row
var currentRow = $(this).closest("tr");
var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
window.location.href = 'http://your_url?b_id=' + Business_id_value;
});
Now you can access the Business_id_value varible in your PHP script using $_GET['Business_id_value']

How to insert PHP row record into AJAX url

I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});

Pass MYSQL row id to javascript variable

I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!

Creating jQuery array variable and Transferring array to another page PHP

I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];

Categories