Can you please tell me what is wrong with this code? I'm displaying a table using ajax, php and mysql. I'm utilizing the X-editable library for inline editing. My problem is when I click the delete button the swal delete confirm modal pops up, but when I confirm that I want to delete a row/record I get nothing.
I have checked my log file and js console, but I'm not seeing any noticeable errors. I somehow few that the problem is with my code. This is how my code looks. Can you please check and see where I have errors?
This is my script file:
<script>
// this function is used to display the table
function fetch_term(term) {
// body...
if (term != '') {
$.ajax({
url:"includes/ajax/fetch_term_grades.php",
method:"post",
data:{"term":term},
dataType:"text",
success:function(data){
$("#result").html(data);
$('#dataTable').DataTable();
//$('table').attr('id', 'dataTable');
}
});
} else {
$('#result').html('');
}
}
// this is used to delete records
function swal_delete(id){
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
url: 'delete_score.php',
type: 'POST',
data: 'delete='+id,
dataType: 'json'
})
.done(function(response){
swal('Deleted!', response.message, response.status);
fetch_term(term);
})
.fail(function(){
swal('Oops...', 'Something went wrong with ajax !', 'error');
});
});
},
allowOutsideClick: false
});
}
$(document).ready(function() {
var term = $('#term').val();
fetch_term(term);
$('#term').on('change', function() {
var changeTermVal = $('#term').val();
fetch_term(changeTermVal);
});
$(document).on('click', '#delete_score', function(event) {
/* Act on the event */
var id = $(this).data('id');
swal_delete(id);
event.preventDefault();
});
});
</script>
This is the file that returns the table to be display(fetch_term_grades.php)
<?php
$term = mysqli_escape_string($connection, $_POST['term']);
$result = term_select_all($term);
$output = '';
if (mysqli_num_rows($result) > 0) {
# code...
$output .= '<table class="table table-bordered" id="dataTable">
<thead>
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Class</th>
<th>Score</th>
<th>Action</th>
</tr>
</thead>';
$output .= '<tbody>';
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tr>';
$output .= '<td>'.$row["first_name"]." ".$row["middle_name"]." ".$row["surname"].'</td>';
$output .= '<td>'.$row["subject_name"].'</td>';
$output .= '<td>'.$row["class_name"].'</td>';
$output .= '<td>'.$row["score"].'</td>';
$output .= '<td>';
$output .= '<a class="btn btn-info btn-sm" href="edit_grade.php?student='.$row["id"].'" data-target="#scoreModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">';
$output .= '<i class="fa fa-edit"></i>';
$output .= '</a>';
$output .= ' ';
$output .= '<a class="btn btn-danger btn-sm" id="delete_score" data-id="'.$row["id"].'" href="javascript:void(0)">';
$output .= '<i class="fa fa-trash"></i>';
$output .= '</a>';
$output .= '</td>';
$output .= '</tr>';
}
$output .= '</tbody>';
$output .= '</table>';
echo $output;
} else {
echo "Data not found";
}
?>
This is the file that is used to delete records.
<?php
$response = array();
$id = intval($_POST['delete']);
var_dump($id);
$sql = "DELETE from period_one WHERE id = {$id} LIMIT 1 ";
$result = mysqli_query($connection, $sql);
if($result && mysqli_affected_rows($connection) == 1){
$response['status'] = 'success';
$response['message'] = 'Product Deleted Successfully ...';
}
else {
$response['status'] = 'error';
$response['message'] = 'Unable to delete product ...';
}
echo json_encode($response);
?>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I tried to create a boostrap modal including a chat inside and using chatgpt.
I have just a problem after the message is sent, maybe my js is not well set or the orientation I take is not the good approach.
I need some help to close this point
What I need to change ?
No idea if I am int the good way. Please let me know
Thank you
My modal
$content = '<!-- Gpt start -->';
$content .= '<link rel="stylesheet" href="http://localhost/admin/css/chatgpt.css">';
$content .= '' . $this->app->getDef('text_gpt') . '';
$content .= '<!-- The Modal -->';
$content .= '<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">';
$content .= '<div class="modal-dialog modal-lg">';
$content .= '<div class="modal-content">';
$content .= '<!-- Modal Header -->';
$content .= '<div class="modal-header">';
$content .= '<h4 class="modal-title">Chat Box</h4>';
$content .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>';
$content .= '</div>';
$content .= '<!-- Modal body -->';
$content .= '<div class="modal-body">';
$content .= '<div class="chat-box">';
//the question
$content .= '<div class="chat-box-header">';
$content .= '<span class="col-md-10">';
$content .= HTML::inputField('msg', null, 'placeholder="Type a message..."');
$content .= '</span>';
$content .= '<span class="col-md-2">';
$content .= HTML::button($this->app->getDef('text_send'), null, null, 'success', ['params' => 'id="ajax_message_gpt" list="chatgpt_list"']);
$content .= '</span>';
$content .= '</div>';
// $content .= '</form>';
$content .= '<div class="chat-box-body">';
//the response
$content .= '<div class="chat-box-message" id="message">';
$content .= '<datalist id="chatgpt_list"></datalist>';
$content .= '<p class="message-text">Hello! How can I help you?</p>';
$content .= '<p class="message-time">12:00 PM</p>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '<!-- Gpt end -->';
// Call my ajax
$chtgpt_ajax = CLICSHOPPING::link('ajax/chatGpt.php');
//the javascript
//AS you see I have some problem inside
==> addEventListener("keyup", function(event) Keyup need to be change I think
==> `option.value = item.prompt;
Below all the script
$output = <<<EOD
<script>
window.addEventListener("load", function(){
// Add a keyup event listener to our input element
document.getElementById('ajax_message_gpt').addEventListener("keyup", function(event){hinterchatGpt(event)});
// create one global XHR object
// so we can abort old requests when a new one is make
window.hinterchatGptXHR = new XMLHttpRequest();
});
// Autocomplete for form
function hinterchatGpt(event) {
var input = event.target;
var ajax_message_gpt = document.getElementById('chatgpt_list'); //datalist id
// minimum number of characters before we start to generate suggestions
var min_characters = 0;
if (!isNaN(input.value) || input.value.length < min_characters ) {
return;
} else {
window.hinterchatGptXHR.abort();
window.hinterchatGptXHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse( this.responseText );
ajax_message_gpt.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item.prompt;//get name
ajax_message_gpt.appendChild(option);
});
}
};
window.hinterchatGptXHR.open("GET", "{$chtgpt_ajax}?q=" + input.value, true);
window.hinterchatGptXHR.send()
}
}
</script>
EOD;
Below my ajax
if (isset($_GET['q'])) {
$terms = HTML::sanitize(mb_strtolower($_GET['q']));
$client = OpenAI::client(CLICSHOPPING_APP_CHATGPT_CH_API_KEY);
$result = $client->completions()->create([
'model' => 'davinci',
'prompt' => $terms,
'temperature' => 0.9,
'max_tokens' => 150,
'frequency_penalty' => 0,
'presence_penalty' => 0.6
]);
# JSON-encode the response
$json_response = json_encode($result); //Return the JSON Array
# Return the response
echo $json_response;
}
I have a problem trying to send some data from a table that I made, I get an error, it says that the update I am doing to the database is correct but the fields are not updated and it sends me this error
parsererror
SyntaxError: Unexpected token I in JSON at position 0
at JSON.parse (<anonymous>)
at n.parseJSON (jquery.min.js:4)
at vc (jquery.min.js:4)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
I really don't know what this error was because when I click on the send button I get this error and the fields are not updated ... this is the scrip I have
<script>
function viewData(){
$.ajax({
url: '../A30.php?p=view',
method: 'GET',
}).done(function(data){
$('tbody').html(data)
tableData()
})
}
function tableData(){
$('#tabledit').Tabledit({
url:'../A30.php',
eventType: 'dblclick',
editButton : true,
deleteButton : false,
columns:{
identifier:[0,'ID'],
editable: [[0,'ID'],[1, 'Empleado'],[5,'Monto']]
},
buttons:{
style: 'width:150px;',
edit:{
class: 'btn btn-sm btn-success' ,
html: '<span class="fa fa-pencil-square-o" ></span> Editar',
action: 'edit'
},
delete:{
class: 'btn btn-sm btn-default',
html: '<span class="glyphicon glyphicon-trash"></span> Trash',
action: 'delete'
},
save:{
class: 'btn btn-sm btn-info',
html: '<span class="fa fa-floppy-o "></span> Guardar'
},
restore:{
class: 'btn btn-sm btn-warning',
html: 'Restore',
action: 'restore'
},
confirm:{
class: 'btn btn-sm btn-danger',
html: 'Confirm'
},
},
onSuccess: function(data, textStatus, jqXHR){
viewData()
},
onFail: function(jqXHR, textStatus, errorThrow){
console.log('onFail(jqXHR, textStatus, errorThrow)');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrow);
},
onAjax: function(action, serialize){
console.log ('onAjax(action, serialize)');
console.log(action);
console.log(serialize);
}
});
}
</script>
here I have the code in php where I receive the variables to send it to my database but it is not sent it only tells me that it has been inserted successfully but in the database they were not updated
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
if ($input['action'] === 'edit') {
$actualizar ="UPDATE sysnom_nomina_det_tmp SET monto='".$input['Monto']."' where ID='".$input['ID']."' AND empleado = '".$input['Empleado']."' AND monto = '".$input['Monto']."' ";
$resul = sqlsrv_query($conexion, $actualizar);
if(!$resul){
echo "Error al Actualizar";
echo $actualizar;
echo $resul;
} else {
echo "Insertado exitosamente......";
echo $resul;
}
}
sqlsrv_close($resul);
echo json_encode($input);
}
I would really appreciate it if you can help me since I don't know what I have wrong
<?php
require ('recursos/conexion.php');
$page = isset($_GET['p'])? $_GET['p'] : ''
; if ($page=='view') {
$sql = "exec sp_sys_nom_autoriza2 'A30',1";
$stmt = sqlsrv_query($conexion, $sql);
$select = "select * from sysnom_nomina_det_tmp where suc = 'A30'";
$stm = sqlsrv_query($conexion, $select);
$totalVU = sqlsrv_num_rows($stm);
while($row = sqlsrv_fetch_array($stm, SQLSRV_FETCH_ASSOC)) {
if ($row['notas'] !== "AHORRO" ) {
if ($row['notas'] !== "PRESTAMO DE AHORRO") {
?>
<tr style="width:1900px" >
<td style="width:141px;"><?php echo $row["ID"]?> </td>
<td style="width:141px;"><?php echo $row["empleado"]?></td>
<td style="width:141px;"><?php echo $row["nombre"]?> </td>
<td style="width:141px;"><?php echo $row["depto"]?> </td>
<td style="width:141px;"><?php echo $row["percepcion"]?></td>
<td style="width:141px;"><?php echo $row["monto"]?></td>
<td style="width:141px;"><?php echo $row["notas"]?> </td>
<?php
$autorizar = rtrim($row['autorizar']);
if ($autorizar == 1) {
echo "<td id='autorizar'><input type ='checkbox' name='checkbox' id='checkbox' value='1' style='width:30px; height:30px;' checked></td>";
}else{
echo "<td id='autorizar'><input type ='checkbox' name='checkbox' id='checkbox' value='1' style='width:30px; height:30px;'></td>";
}
}
}
}
}else{
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
$respone = [
"message"=>"",
"data"=>[]
];
if ($input['action'] === 'edit') {
$actualizar ="UPDATE sysnom_nomina_det_tmp SET monto='".$input['Monto']."' where ID='".$input['ID']."' AND empleado = '".$input['Empleado']."' AND monto = '".$input['Monto']."' ";
// you can use prepeared statetments for sql injection threats
$resul = sqlsrv_query($conexion, $actualizar);
if(!$resul)
$respone["message"] = "Error al Actualizar";
else
$respone["message"] = "Insertado exitosamente......";
}
sqlsrv_close($resul);
$response["data"]["query"] = $actualizar;
$response["data"]["result"] = $resul;
$response["data"]["input"] = $input;
echo json_encode($response);
}
?>
You must use json_encode function for all outputs(also error messages).
try this version :
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
$respone = [
"message"=>"",
"data"=>[]
];
if ($input['action'] === 'edit') {
$actualizar ="UPDATE sysnom_nomina_det_tmp SET monto='".$input['Monto']."' where ID='".$input['ID']."' AND empleado = '".$input['Empleado']."' AND monto = '".$input['Monto']."' ";
// you can use prepeared statetments for sql injection threats
$resul = sqlsrv_query($conexion, $actualizar);
$response["data"]["result"] = $resul;
if(!$resul)
$respone["message"] = "Error al Actualizar";
else
$respone["message"] = "Insertado exitosamente......";
}
sqlsrv_close($resul);
$response["data"]["query"] = $actualizar;
$response["data"]["input"] = $input;
echo json_encode($response);
}
This will work if you send the your json as string. use
JSON.stringify(ur_object here)
Here is my problem, I have a AJAX function which is working on my local server but don't return anything when I put it on my online server.
Here is my code :
Here the page where I call the function showEspece() :
echo "<div class='tableau'>";
echo "<table class='tableAnimal'>\n";
echo "<thead>\n";
echo "<td class='tdAnimal'><b> Nom </b></td>\n";
echo "<td class='tdAnimal'><b> Nombre </b></td>\n";
echo "</thead>\n";
while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr class='trAnimal'>\n";
foreach ($row as $item) {
echo " <td class='tdAnimal'>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
} ?>
<td class='tdAnimal' onclick="showEspece(<?php echo "'";echo $row['ESPECE'];echo "'";?>, <?php echo "'";echo $categorie;echo "'";?>,this);" ><a class='lightbox'><img src='images/loupe.png'/></a></td> <?php
echo "</tr>\n";
}
echo "</table>\n\n";
echo '</div>';
Here is the Ajax function :
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
alert('ok');
var tableau = data;
$('#output').html(tableau);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
}
Here is the page call by the Ajax function :
<?php
include("/includes/connexionBD.php");
include("includes/entetepage.php");
$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");
oci_execute($requete);
$table = "<table>\n";
$table .= "<thead>\n";
$table .= "<td><b> Nom </b></td>\n";
$table .= "<td><b> Sexe </b></td>\n";
$table .= "<td><b> Date naissance </b></td>\n";
$table .= "</thead>\n";
while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
$table .= "<tr>\n";
foreach ($row as $item) {
$table .= " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
}
$table .= "</tr>\n";
}
$table .= "</table>\n\n";
echo json_encode($table);
?>
And that is what error I get on the consol :
VM1130:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.error (ajax.js:16)
at i (jQuery.js:2)
at Object.fireWith [as rejectWith] (jQuery.js:2)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)
Does someone know where the problem can come from and can help me ?
Sorry fo my bad english :/
The issue here is that your JSON response is malformed, you could try getting the output JSON and put it through a linter to find where the problem actually is:
https://jsonlint.com/
I would recommend not building the HTML (your table) in PHP but building it using Javascript and injecting the data from the Ajax request into the table.
Change php response code with the following,
<?php
include("/includes/connexionBD.php");
include("includes/entetepage.php");
$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");
oci_execute($requete);
$table = "<table>\n";
$table .= "<thead>\n";
$table .= "<td><b> Nom </b></td>\n";
$table .= "<td><b> Sexe </b></td>\n";
$table .= "<td><b> Date naissance </b></td>\n";
$table .= "</thead>\n";
while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
$table .= "<tr>\n";
foreach ($row as $item) {
$table .= " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
}
$table .= "</tr>\n";
}
$table .= "</table>\n\n";
echo json_encode(array("table"=>$table, JSON_UNESCAPED_SLASHES));
?>
change ajax code with the following
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
alert('ok');
var tbl = $.parseJSON(data);
var tableau = tbl.table;
console.log(tableau);
$('#output').html(tableau);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
}
Sorry if this is a poor description, I am relatively new to this.
I am developing a web tool which displays the results of mysql data filtered by a date range in an html table. I have an input and button which allows the user to input an email address to send the table data to. The problem is I am having trouble passing the html table data correctly to my php page to be emailed.
I've tried various methods with AJAX and Javascript, but nothing is working. At one point I was able to pass the table data, but not the inputted email (or vice versa); never both simultaneously. I need to be able to pass both the email that has been inputted as well as the data in the html table preferably reserving the table format as well for a cleaner look). Any help and/or insight is greatly appreciated. Apologies if this code is improper and/or wrong.
Relevant PHP:
<!-- download2csv button -->
<div>
<form action="getCSV.php" method="post">
<input type="hidden" name="csv_text" id="csv_text_computers">
<button class="btn btn-app btn-primary btn-xs no-radius" type="submit" onclick="getCSVDataComputers()">
<i class="icon-save"></i></button>
</form>
<!-- email button -->
<form action="mailto.php" method="post">
Email: <input type="text" name="einame" id="eiid" placeholder="example#example.com">
<button class="btn btn-app btn-info btn-xs no-radius" type="submit" name="ebname" id="ebid" onclick="mailer()">
<i class="icon-envelope"></i></button>
</form>
</div>
</div>
<!-- data table header -->
<div class="table-responsive">
<table id="table-computers1" name="table-computers" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Item Name</th>
<th>RFID Number</th>
<th>Link</th>
<th>Delivery Date</th>
</tr>
</thead>
<tbody>
<?php
foreach ($infocoms as $infocom)
{
//variables for glpi url
$itemtype = $infocom['itemtype'];
$items_id = $infocom['items_id'];
$url = "https://null.null.com/front/" . $itemtype. ".form.php?id=" . $items_id;
?>
<tr>
<?php
// database connection
$conn = mysqli_connect('null', 'null', 'null');
mysqli_select_db($conn, 'glpi');
if ($infocom['itemtype'] == "peripheral") {
$query = "SELECT glpi_peripherals.name AS devicename, TRIM(LEADING '0' FROM glpi_peripherals.otherserial) AS otherserial FROM glpi_peripherals INNER JOIN glpi_infocoms ON glpi_peripherals.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'peripheral'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$devices = $result->fetch_assoc();
echo "<td>$devices[devicename]</td>";
echo "<td><center>$devices[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "computer") {
$query = "SELECT glpi_computers.name AS compname, TRIM(LEADING '0' FROM glpi_computers.otherserial) AS otherserial FROM glpi_computers INNER JOIN glpi_infocoms ON glpi_computers.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'computer'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$computers = $result->fetch_assoc();
echo "<td>$computers[compname]</td>";
echo "<td><center>$computers[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "monitor") {
$query = "SELECT glpi_monitors.name AS viewname, TRIM(LEADING '0' FROM glpi_monitors.otherserial) AS otherserial FROM glpi_monitors INNER JOIN glpi_infocoms ON glpi_monitors.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'monitor'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$monitors = $result->fetch_assoc();
echo "<td>$monitors[viewname]</td>";
echo "<td><center>$monitors[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "networkequipment") {
$query = "SELECT glpi_networkequipments.name AS netname, TRIM(LEADING '0' FROM glpi_networkequipments.otherserial) AS otherserial FROM glpi_networkequipments INNER JOIN glpi_infocoms ON glpi_networkequipments.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'networkequipment'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$networks = $result->fetch_assoc();
echo "<td>$networks[netname]</td>";
echo "<td><center>$networks[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "printer") {
$query = "SELECT glpi_printers.name AS printname, TRIM(LEADING '0' FROM glpi_printers.otherserial) AS otherserial FROM glpi_printers INNER JOIN glpi_infocoms ON glpi_printers.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'networkequipment'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$printers = $result->fetch_assoc();
echo "<td>$printers[printname]</td>";
echo "<td><center>$printers[otherserial]</center></td>";
} else {
// error handling for null entries
echo "1 or more items were not found";
}
// end data loop and close mysql connection
mysqli_close($conn);
?>
<td><a target=_blank href=$url><?php echo $url; ?></a></td>
<td><center><?php echo $infocom['ddate']; ?></center></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
</div>
<?php
} else {
echo "<center><p style='font-size:125%;'>Please select a date range to submit.</p></center>";
}
error_log("\n");
?>
Relevant Javascript:
<script type="text/javascript">
jQuery(function($) {
var oTable1 = $('#table-computers').dataTable( {
"aLengthMenu": [[10, 25, 100, -1], [10, 25, 100, "All"]],
"iDisplayLength": -1,
"aoColumns": [
{ "bSortable": true },
null, null,null,
] } );
})
function getCSVDataComputers(){
var csv_value=$('#table-computers').table2CSV({delivery:'value'});
$("#csv_text_computers").val(csv_value);
}
</script>
<script type="text/javascript">
function mailer()
{
var tableContent=document.getElementById("table-computers").innerHTML;
alert(tableContent); // This works, but data does not echo in mailto.php
$.post('mailto.php',{content:tableContent},function(data) {
});
}
</script>
Mailto PHP page:
<?php
$mailto = $_POST['einame'];
$table = $_POST['tableContent'];
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Test <test#example.com>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if (isset($mailto)) {
mail($mailto,"GLPI Notifications",$table,$headers);
echo "Mail sent successfully to $mailto." . "\r\n";
} else {
echo "Mail was not sent." . "\r\n";
}
?>
<br>
Home Page
<br>
<?php
echo $table; // Displays nothing
error_log("\n");
?>
finally figured it out. updated code:
function mailer() {
var tableContent=document.getElementById("table-computers").innerHTML;
// alert(tableContent); confirmation
$.post("mailto.php",{ "content": $("#bmailto").val(tableContent) },function(data) {
});
}
My delete function isn't working.
This is my table with the delete button.
// retrieve table contents
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td class='text-align-center'><input type='checkbox' name='item[]' class='checkboxes' value='{$employeeid}' /></td>";
echo "<td>{$name}</td>";
echo "<td>{$title}</td>";
echo "<td>{$phone}</td>";
echo "<td>{$supplier_name}</td>";
echo "<td>{$created}</td>";
echo "<td>";
// update record
echo "<a href='update_product.php?employeeid={$employeeid}' class='btn btn-info margin-right-1em'>";
echo "<span class='glyphicon glyphicon-edit'></span> Rediger";
echo "</a>";
// delete record
echo "<a delete-employeeid='{$employeeid}' delete-file='delete_product.php' class='btn btn-danger delete-object'>";
echo "<span class='glyphicon glyphicon-remove'></span> Slet";
echo "</a>";
echo "</td>";
echo "</tr>";
}
//end table<br>
echo "</table>";
This is my delete function
// delete single record
$(document).on('click', '.delete-object', function(){
// php file used for deletion
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-id');
var q = confirm("Are you sure?");
if (q == true){
$.post(delete_file, {
object_id: id
}, function(data){
location.reload();
}).fail(function() {
alert('Unable to delete.');
});
}
return false;
});
I got the code from a tutorial that I modified a lot. Everything else is working, except the delete function.
PHP CODE
<?php
// check if value was posted
if($_POST){
// include database and object file
include_once 'config/database.php';
// delete query
$query = "DELETE FROM employeestest WHERE employeeid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['object_employeeid']);
if($stmt->execute()){
// redirect to read records page and
// tell the user record was deleted
echo "Medarbejderen er slettet.";
}else{
echo "Medarbejderen kunne ikke slettes.";
}
}
?>
Change
var id = $(this).attr('delete-Id');
to
var id = $(this).attr('delete-employeeid');
And, Change $.post to $.ajax as i've given
<script>
$(document).on('click', '.delete-object', function(){
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-employeeid');
var q = confirm("Are you sure?");
if (q == true)
{
$.ajax({url:delete-file,cache:false,success:function(result){
alert('Successfully Deleted');
}});
}
return false;
});
</script>
Maybe you just made grammar mistake
'delete-id' => 'delete-employeeid'