display a table of employees with delete button - php

I would like to know why my following code piece displays nothing in the browser (http://localhost/display.php). I would like to generate a template for my table to display all employees in my database (id, firstname, lastname) and use HTTP verb DELETE via jquery ajax method to delete a user if I click the delete button on the display table.
Here is my display.php
<table id="employees" border="1">
</table>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$document.ready(function()
{
var $employees = $("#employees");
$.ajax({
url: "delete.php",
contentType: "json",
success: function(data){
$.each(data, function(index, item){
var $row = $("#templates").find(".row-template").clone();
$row.find(".firstName").html(item.FirstName);
$row.find(".lastName").html(item.LastName);
$row.find(".delete").click(function() {
$.ajax({
url: "delaction.php" + item.Id,
type: "DELETE",
success: function()
{
$row.remove();
}
});
});
$employees.append($row);
});
}
});
});
</script>
<div id="templates" style="display: none">
<table>
<tr class="row-template">
<td class="firstName" style="width: 100px;"></td>
<td class="lastName" style="width: 100px;"></td>
<td>
<input type="button" value="X" class="delete" />
</td>
</tr>
</table>
</div>
and my delete.php looks like this
<?php
define('DB_HOST','localhost');
define('DB_ROOT','root');
define('DB_PASS','');
define('DB_NAME','employees');
$conn=mysqli_connect(DB_HOST,DB_ROOT,DB_PASS) or die("Unable to connect to your selected db.Error ".mysqli_error());
if(null!=$conn)
{
mysqli_select_db($conn,DB_NAME);
$query=("SELECT * FROM empl");
$result=mysqli_query($query);
foreach($result as $res)
{
}
mysqli_close($conn);
}
?>
Thank you a lot.

What's in 'delaction.php'?
Anyway, to pass itemId to delaction.php with the item to delete, change:
url: "delaction.php" + item.Id,
to:
url: "delaction.php?itemId=" + item.Id,

Related

How to run a first instance of ajax jquery when page loads

I have a jquery and ajax that performs a query and shows a table when a button is clicked. The problem is that when the page loads for first time, the query not run and do not shows anything, so the button has to be clicked to start showing the query result.
Is there a way that the query runs when page loads? and then just use the button.
My code is:
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
Thanks in advance!
Just call click() on the element to simulate a click.
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}).click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
You could extract the function you're calling in the click handler and call it within ready.
$(document).ready(function() {
const displayContent = () => {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}
displayContent();
$("#display").click(displayContent());
});

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

Ajax multiple input not showing all data?

I'm stuck in multiple input. My code is not showing all data. below is the html I am using:
<form id="matkul" class="form-horizontal" method="POST">
<table class="table table-condensed">
<thead>
<tr>
<th>Matakuliah</th>
<th>Data Lain</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="post" type="submit">Save</button>
<button id="get">Get Data!</button>
below is the code to get the data
<script>
$(document).ready(function() {
$("#get").click(function() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22https%3A%2F%2Funisys.uii.ac.id%2Fuii-ras%2Fmatakuliah.asp%3Fidx%3D1%26session_id%3DxxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511%26no_mhs%3D%22&format=json';
$.getJSON(url,
function(data) {
var id = data.query.results.body.table.tr.td.table.tr[2].td.table.tr;
for (var i = 1; i <= id.length; i++) {
$("<tr> <td> <input name='fmatakuliah' value='"+id[i].td[1].a.content+"'> </td> <td> <input name='fdata' value='" + id[i].td[1].a['href'] + "'> </td> </tr>").appendTo("#matkul tbody");
};
});
});
});
</script>
from the above code output will be
Matakuliah Data Lain
StringOne OtherData
StringTwo OtherData
below is the ajax post code, but when it is already sending the data, the alert does not show all the data
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
string = $("form").serialize();
alert(string); // this alert is normal, show all data
$.ajax({
type: "GET",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
});
});
</script>
below is the code on save.php
print_r($_GET);
The latest response is showing like this
Array
(
[fmatakuliah] => Wide Area Network
[fdata] => matakuliahdetail.asp?session_id=xxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511&mk=52323605&kur=2010
)
My question is how to show all data and save it to the database?
It looks like you need to change the AJAX type from GET to POST:
$.ajax({
type: "POST",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});

multiple select with checkbox in php

i am making a website in which i am to embbed the functionality of delete using multiple checkbox. here is my code. my problem is
1. Ajax call is not working.
2. how can i make search from database for array .
<?php
if(isset($_POST['Delete']))
{
$array=$_POST['check_box'];
}
?>
<form method="post" id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while($selectnumberarr=mysql_fetch_array($selectnumber))
{
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" id="<?php $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}?>
<input type="submit" name="Delete" id="delete">
</table>
</form>
and below is my ajax and javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
any help would be appriciated
your code is almost correct. You need to remove `onChange="show()" for input checkbox, because if you have jquery then you don't need to put events on HTML elements.
Use jquery 'on' method for compatibility for latest php library.
Replace your jquery code with following jquery code :-
<script>
$(document).ready(function(){
$('#delete').on('click',function()
{
var cat_id = $('.check_box:checked').map(function() {
return this.id;
}).get().join(',');
console.log(cat_id);
$.ajax({
type: "POST",
url: "checkbox.php",
data: { "kw ":cat_id },
datatype:'json',
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
Use ".check_box" instead of "element" in jquery to prevent checks for all checkboxes, instead of desired ones.
Hope it helps.
Why you don't use an array for sending the checkboxes like:
HTML part:
<?php
if (isset($_POST['check_box'])) {
var_dump($_POST['check_box']);
echo "ajax call is working";
}
?>
<form id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while ($selectnumberarr = mysql_fetch_array($selectnumber)) {
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" value="<?php echo $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}
?>
</table>
<input type="button"name="delete" id="delete" value="Delete" />
</form>
JQuery part:
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
So you can easily get an array of the selected checkboxes in php with:
$idsArray = $_POST["check_box"];
this looks now like:
array(
"1", "2","etc.."
);
so this array contains all the ids of the selected checkboxes for delete.

How to delete all entry from table using checkBox clickall after confirmation is true? jQuery Ajax PHP

I am trying to delete all records from the table using the checkbox. When the user checked the topmost checkbox, it will check all other checkboxes inside the loop then a confirmation box will appear about deleting the records. if the user click OK, the the all the records will be deleted using $.ajax, if he clicked Cancel, then, the page will return to the same state, and the checkboxes are not checked anymore.
<?php
include 'dbconn.php';
?>
<table border="1" >
<tr><td align="center" width="20"><input type="checkbox" name='checkALL' id='checkALL'></td><td>Name</td>
</tr>
<?php
$sql=mysql_query("SELECT * FROM names ORDER BY names ASC") or die(mysql_error());
while($rows=mysql_fetch_assoc($sql)){
?>
<tr>
<td><input type="checkbox" name="id[]" id="id[]" value="<?php print $rows['id'];?>">
</td><td>Name</td>
</tr>
<?php
}
?>
</table>
JQUERY
<script>
$(function(){
//click all
$('#checkALL').click(function(){
$(':checkbox').attr({checked: 'true'});
var del=confirm("You checked all the box. Delete All?");
if(del==true){
//delete here using $.ajax
}
else{
window.location.reload(false);
$('#checkAll').attr({checked: 'false'});
}
});
});
</script>
Place this in your if block.
$.ajax({
type: "GET",
url: '<php file which truncates table>',
success: function (data) {
if (data == 'truncated') {
alert('success');
} else {
alert('not truncated');
}
}
});
Return the string truncated from your php file on success.
Here U- PageUrl, A- Action on page, P- Parameter
if (confirm('Are you sure to delete this record?')) {
Operation(U, A, P);
}
function Operation(U, A, P) {
$.ajax({
type: "POST",
url: U + '/' + A,
data: P,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
}
});
}
You can use something like this in your HTML check all page
<html>
<head><title>Select/Delete ALL with jQuery/PHP</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<table border="1" cellpadding="5">
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="100" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="200" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="300" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
var checked = false;
$('#checkAll').click(function(){
if (checked == false){
checked = true
} else {
checked = false
}
$('input.check').attr("checked",checked);
var confirmDelete=confirm("You checked all the box. Delete All?");
if (confirmDelete==true){
var csv = '';
$('.check').each(function() {
csv += $(this).attr("value") + ",";
});
$.ajax({
type: "POST",
url: "delete.php",
data: { tobeDeleted: csv }
}).done(function( msg ) {
console.log( "Data has been deleted: " + msg );
});
} else {
$('#checkAll').attr("checked", false);
$('input.check').attr("checked", false);
}
});
});
</script>
</body>
</html>
and use something like this in your PHP script
<?php
$postDeleted = substr($_POST['tobeDeleted'], 0, strlen($_POST['tobeDeleted'])-1);
$arrDeleted = explode(",", $postDeleted);
$sql = "DELETE FROM employee WHERE 1=1 ";
foreach($arrDeleted as $key=>$value){
$sql .= "OR employee_id = $value ";
}
echo $sql;
?>
if(del==true){
$.ajax({
type: "POST",
url: 'your_file_url',
async:false,
cache: false,
success: function(data){
if (data == 1) {
alert('success');
} else {
alert('Error');
}
}
});
}
In your php file, echo 1 for successful delete and 0 for some error

Categories