This is my index.php view were my table is placed
<table class="striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Created at</th>
</tr>
</thead>
<tbody id="showdata">
<!--<tr>
<td>1</td>
<td>Alvin</td>
<td>Eclair</td>
<td>$0.87</td>
<td>
Edit
Delete
</td>
</tr>-->
</tbody>
</table>
This my ajax script placed on index.php
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url(); ?>index.php/Employee/showAllEmployee',
async: false,
dataType: 'json',
success: function(data) {
//console.log(data);
var html = '';
var i;
for (i=0; i<data.length; i++) {
html += '<tr>'+
'<td>'+data[i].emp_id+'</td>'+
'<td>'+data[i].name+'</td>'+
'<td>'+data[i].address+'</td>'+
'<td>'+data[i].created_at+'</td>'+
'<td>'+
'Edit'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get data from database');
}
});
}
This is what i have on my employee controller
public function showAllEmployee()
{
$result = $this->em->showAllEmployee();
echo json_encode($result);
}
This is my model
public function showAllEmployee()
{
$this->db->order_by('created_at', 'desc');
$query = $this->db->get('tbl_employees');
if($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Whenever i refresh the page the data wont display instead i run into an error could not get the data from the database which is the condition i set on my ajax script what could be wrong pls help
set header as JSON type in the controller
change your controller to
public function showAllEmployee(){
$result = $this->em->showAllEmployee();
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
}
Related
Screenshot
<?php
if(isset($_GET['View']) && $_GET['View']=="HistoryEntry"){
echo '
<h2>History Of Entries</h2>
<table id="table" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date In</th>
<th scope="col">Date Out</th>
<th scope="col">Rfid</th>
<th scope="col">Plate #</th>
</tr>
</thead>
<tbody>';
global $connection;
$query = "SELECT * FROM history_entries";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>
<th scope="row">'.$row['Entry_ID'].'</th>
<td>'.$row['Date_in'].'</td>
<td>'.$row['Date_out'].'</td>
<td>'.$row['Acc_rfid'].'</td>
<td>'.$row['Plate_num'].'</td>
</tr>';
}
echo ' </tbody>
</table>
<center>
<button>Delete</button>
</center>
<div class="line"></div>';
}
?>
?>
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
});
$("#Sample").click(function() {
var value = $(".selected th:first").html();
value = value || "No row Selected";
});
As you can see this my codes, i already know how to select the row and get the ID but cant pass the ID "value" to php in order to do the delete function in database. can i use here $.POST function here? or is it better to use GET function here but i think it wouldn't be secure.
This is how you can do it without get param :
1/ Your FRONT :
HTML (just an example)
<table>
<tr id="row_id">
<td>Data 1</td>
<td>Data 2</td>
...
</tr>
...
</table>
<button id="delete_row" type="button">Delete</button>
JS / jQuery
var current_row_id = "";
// You select the row
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
current_row_id = $(this).attr("id"); // Here you get the current row_id
});
// You delete the row
$("#delete_row").on("click", function() {
$.ajax({
type: "POST",
url: "delete.php",
data: {"id" : current_row_id }, // You send the current_row_id to your php file "delete.php" in post method
dataType: 'json', // you will get a JSON format as response
success: function(response){
// you do something if it works
},
error: function(x,e,t){
// if it doesn't works, check the error you get
console.log(x.responseText);
console.log(e);
console.log(t);
}
});
});
2/ Your BACK
PHP "delete.php" file
<?php
$id = $_POST['id']; // You get the 'current_row_id' value
// Now you do your DELETE request with this id :
$sql = "DELETE ... WHERE id = :id";
etc...
$result = array(); // You can prepare your response and send information about what you did
$result['row_deleted'] = $id;
$result['message'] = "The row with id = " . $id . " was deleted with success";
$result['type'] = "success";
//etc....
echo json_encode($result); // You send back a response in JSON format
3/ Back to the FRONT
Your ajax call, the success part :
success: function(response){
// You can display a success message for example using your response :
alert(response.message); // You will get 'The row with id = {the row id} was deleted with success' here for example
},
Is it what you are looking for?
here is a simple Ajax request
var data = {
rowId: 1
};
$.ajax({
type: "POST",// GET|POST
url: 'delete.php', // Where you want to send data like url or file
data: data, // this is what you want to send to server, in this case i send data with id = 1 to server
dataType: 'json' // here we say what data type we want "json"
success: function(response) {
alert(response);
}, // this is the callback were u will get response from your server
});
delete.php here is how u can handle this ajax
$rowId = htmlspecialchars($_POST['rowId']);
if ($rowId) {
global $connection;
$query = "DELETE FROM history_entries WHERE Entry_ID = " . $rowId;
$result = mysqli_query($connection, $query);
$response = array(
'success' => true
);
echo json_encode($response);
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
Hope this will help you to understand how to use Ajax
I am trying some things regarding Ajax, Jquery and PHP.
My JavaScript code (the pop.php is located correctly)
<script type="text/javascript">
$('.nameclick').click(function()) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id=$(this).data("formid")}
success: function(result){
alert(result);
} else {
alert("test");
}
});
});
</script>
Part of my html/php code in the same page (this code works fine to print out the table I am looking for):
<table class="data-table">
<thead>
<tr>
<th>Servicenummer</th>
<th>Kund</th>
<th>Uppgift</th>
<th>Status</th>
<th>Inlämnad</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td><div id="clickMe">'.$row['service'].'</div></td>
<td>'.$row['name'].'</td>
<td>'.$row['Drakt1'].'<br>'.$row['Drakt2'].'<br>'.$row['Drakt3'].'<br>'.$row['Drakt4'].'<br>'.$row['Drakt5'].'<br>'.$row['Drakt6'].'<br>'.$row['reg1'].'<br>'.$row['flaska1'].'<br>'.$row['dator1'].'</td>
<td>'.$row['Service_Status'].'</td>
<td>'.$row['date'].'</td>
</tr>';
$no++;
}?>
</tbody>
</table>
And my pop.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$telephone = $conn->real_escape_string($_POST['telephone']);
$sql = 'SELECT name, email, telephone FROM Service_Form WHERE id = "10"';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<?php
while ($row = mysqli_fetch_array($query))
{
echo $row['name'];
echo $row['email'];
echo $row['telephone'];
}
?>
At the moment when I click my link in my normal page I don't get anything, no alerts at all, but my pop.php prints out the values correctly, I hope... I know I have to change my id="10" to something but i am not certain to what, could it be formid?
What am I doing wrong here?
What I want:
a table with the values below from a table in the database
when I click the name in the table it should show an alert (or something similar) that shows the name, email and telephone number (these are stored as well in the database table but not on the website table).
your ajax function is having some errors
so use this
<script type="text/javascript">
$('.nameclick').click(function(ev) {
ev.preventDefault();
var id = $(this).data("formid");
$.ajax({
type: "POST",
url: "pop.php",
data: {
"id":id
},
success: function(result){
alert(result);
},
error:function (error) {
alert(error);
}
});
});
</script>
I am editing your jquery part please try
<script type="text/javascript">
$('.nameclick').click(function(ev)) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id:$(this).attr("data-formid")}
success: function(result){
if(result){
alert(result);
} else {
alert("test");
}
}
});
});
</script>
This is my table which is dynamic, with this I am getting three tables with different ids.
<?php
echo "<table class='table table-hover table-bordered' ondrop='drop(event,this)' ondragover='allowDrop(event)' id='".$type."'>";
if(empty($players))
echo "<tr><td></td></tr>";
foreach($players as $p)
{
echo "<tr data-id='".$p['to']."' data-fixture='".$p['fixture']."' data-team='".$p['team']."' draggable='true' ondragstart='drag(event,this)' id='".$type."aa'>";
echo "<td >".$p['name']."</td>";
echo "</tr>";
}
echo "</table>";
?>
My Javascript is this:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev,str) {
//alert(str);
var temp = str.parentNode;
child = temp.children;
if(child.length==1)
{
$(temp).append("<tr><td></td></tr>");
}
ev.dataTransfer.setData("text", ev.target.id);
ev.dataTransfer.setData("val", ev.target.getAttribute('data-id'));
ev.dataTransfer.setData("fixture", ev.target.getAttribute('data-fixture'));
ev.dataTransfer.setData("team", ev.target.getAttribute('data-team'));
}
function drop(ev,str) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var id = ev.dataTransfer.getData("val");
var fixture = ev.dataTransfer.getData("fixture");
var team = ev.dataTransfer.getData("team");
ev.target.appendChild(document.getElementById(data));
//alert(fixture);
if(str.id=='avl')
status=1;
else if(str.id=='uavl')
status=2;
$.ajax({
url: "<?php echo base_url();?>index.php/teams/update_players/"+status+"/"+id+"/"+fixture+"/"+team,
type: 'GET',
success: function(data) {
//$("#a_p").html(data);
//alert(data);
},
});
}
when dropping table rows from one table to another.. tr got dropped to td not in table.
like this
<table>
<tr>
<td>
<tr> (this is a dropped row)
<td></td>
</tr>
</td>
</tr>
</table>
Your drop function appends a child to ev.target. Try using console.log to check the tagName for ev.target. If it's TD, then that's your problem.
Not providing this in the comment section, because I don't have enough reputation for submitting comments.
I have ajax response code here that dataCompetence has value 2,5. I Tried to find same id in column comp_id and then set checkbox checked. Here is my html code:
<table id="competence_list" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="1%"><input name="select_all_competence" class="case" id="example-select-all-competence" type="checkbox"></th>
<th hidden>ID</th>
<th width="10%">Aspect</th>
<th width="40%">Description</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
if ($this->competenceList) {
foreach ($this->competenceList as $data) {
?>
<tr>
<td><input type="checkbox" name="idcheckbox_competence" id="idcheckbox_competence" class="case"></td>
<td hidden id="comp_id"><?php echo $data['competence_id']; ?></td>
<td><?php echo $data['aspect']; ?></td>
<td><?php echo $data['descriptions']; ?></td>
</tr>
<?php
$i++;
}
}
?>
</tbody>
</table>
And this what i tried to set checkbox checked :
var dataCompetence = jsonData.dataCompetence;
if(jsonData.success){
$.gritter.removeAll();
$.each(dataCompetence.split(","), function(i,e){
$("#competence_list input[value='" + e + "']").prop("checked", true);
});
I don't know ow to find the same value and then set the checkbox checked, help me. Thanks
#Nike please try and follow these steps.......
Html
<div id="dvCheckBoxListControl"></div>
Jquery
<script>
$(document).ready(function () {
PopulateCheckBoxList();
})
function PopulateCheckBoxList() {
$.ajax({
type: "POST",
url: '#Url.Action("GetCheckBoxDetails", "Home")',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
//error: AjaxFailed
});
}
function AjaxSucceeded(result) {
BindCheckBoxList(result);
}
function BindCheckBoxList(result) {
CreateCheckBoxList(result);
}
function CreateCheckBoxList(checkboxlistItems) {
var table = $('<table></table>');
var counter = 0;
$(checkboxlistItems).each(function () {
table.append($('<tr></tr>').append($('<td></td>').append($('<input>').attr({
type: 'checkbox', name: 'chklistitem', value: this.Value, id: 'chklistitem' + counter, checked:this.IsSelected
})).append(
$('<label>').attr({
for: 'chklistitem' + counter++
}).text(this.Name))));
});
$('#dvCheckBoxListControl').append(table);
}
Please create a model CheckBoxItem in your project like this..
Model
public class CheckBoxItem
{
public string Name { get; set; }
public string Value { get; set; }
public bool IsSelected { get; set; }
}
Controller
[HttpPost]
public ActionResult GetCheckBoxDetails()
{
List<CheckBoxItem> chkListAppointments = new List<CheckBoxItem>(){
new CheckBoxItem{ Value="1",Name="Jaipur", IsSelected=true},
new CheckBoxItem{ Value="2",Name="Ajmer",IsSelected=false},
new CheckBoxItem{ Value="3",Name="Sikar",IsSelected=true},
};
return Json(chkListAppointments, JsonRequestBehavior.AllowGet);
}
I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.