Refresh AJAX function (gets PHP) - javascript

Let me first say that I've been coding for less than a week. I'm trying to create a javascript that will refresh my data using an AJAX call that will spit out a PHP's JSON encoded file into a more readable file.
I've successfully spit out the json into an HTML table, however, I want to auto refresh this data so when the database changes, so will my HTML.
$(document).ready(function(){
refresh();
});
function refresh() {
setTimeout( function() {
dbupdates();
refresh();
}, 500);
}
function dbupdates(){
$.ajax({
url: 'fetchtest.php',
type: 'get',
dataType: 'JSON',
success: function(response){
// for loop to only write 10
for(var i=0; i<10; i++){
var id01 = response[i].id1;
var id02 = response[i].id2;
var id03 = response[i].id3;
// tr located in html
var tr_str = "<tr>" +
"<td align='center'>" + id01 + "</td>" +
"<td align='center'>" + id02 + "</td>" +
"<td align='center'>" + id03 + "</td>" +
"</tr>";
// table ID in html file
$("#HTMLTABLE").append(tr_str);
}
}
});
};
When I run the web page, it goes into an infinite loop where it just creates new 10 entries table of the same data (probably does change if db changes).
I know exactly why this happens but what function do I need to use to actually refresh only 10 table?
Thanks

No use append() replace into html() function use solved your problems
<div id="HTMLTABLE"></div>
<script>
$(document).ready(function(){
refresh();
});
function refresh() {
setTimeout( function() {
dbupdates();
refresh();
}, 1500);
}
function dbupdates(){
$.ajax({
url: 'fetchtest.php',
type: 'get',
dataType: 'JSON',
success: function(response){
// for loop to only write 10
var tr_str ='';
for(var i=0; i<response.length; i++){
var id01 = response[i].id;
var id02 = response[i].name;
var id03 = response[i].salery;
// tr located in html
tr_str += "<tr>" +
"<td align='center'>" + id01 + "</td>" +
"<td align='center'>" + id02 + "</td>" +
"<td align='center'>" + id03 + "</td>" +
"</tr>";
// table ID in html file
}
$("#HTMLTABLE").html(tr_str);
}
});
};
</script>

Related

jquery datatables "search" returns previously deleted data

Im using an onclick to delete selected rows from sql database and update the datatable simultaneously by sending an ajax to the php/server.
Responsible for deleting the record is some backend php.
So far so good.
However,when i try to search,it returns back the rows i have deleted,what should i do ?
$(document).on('click', '#delete', function() {
var id = $(this).parent().find("#id").text();
var name = $(this).parent().find("#name").text();
if(confirm("Are you sure you want to delete record " + id + " with name " + name + " ?")){
$.ajax({
method: "POST",
url: "http://localhost/indexDB/actions.php",
data: {
id: id,
deletename: name
}
})
.done(function(msg) {
alert(msg);
$("#dtVerticalScrollExample tbody").empty(); //EMPTY THE DB WINDOW
$.ajax({ //POPULATE DB WINDOW AGAIN
url: 'http://localhost/indexDB/ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
var contents = response[i].contents;
var date = response[i].date;
var ajaxbutton = response[i].button;
var button = document.createElement("i");
button.className = "far fa-trash-alt trashdb";
var tr_str = "<tr>" +
"<td id=id>" + id + "</td>" +
"<td id=name>" + name + "</td>" +
"<td id=date>" + date + "</td>" +
"<td id=buttonrow>" + button.outerHTML + "</tr>";
$("#dtVerticalScrollExample tbody").append(tr_str);
}
}
});
});
}else{
alert("Delete cancelled !")
}
}); //DELETE RECORDS FROM DB

I am working on appending row in javascript but I actually don't know how to append an image in row cell

[I am appending a row. everything appended but image not showing. I tried some ways but cant solve this problem][1]
function SearchDrivers() {
var Id = document.getElementById('driverSearch').value;
$.ajax({
url: "/Administration/SearchDrivers/" + Id,
type: "Get",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (response) {
var table = document.getElementById('DriverTable');
var drivers = response['users'];
for (var j = 0; j <= drivers.length; j++) {
var driver = drivers[j];
tr = "<tr>"
+ "<td>" + driver['email'] + "</td>"
+ "<td>" + driver['email'] + "</td>"
+ "<td>" + "033138445156666" + "</td>"
+ "<td>" + "<button class='table-btn'>unverified</button>" + "</td>"
this is the way i am appending an image and its style. I used some more ways to append a image but thay also not working for me.
+ "<td>" + "<a asp-action='DriverProfile'><img class='ml-2 icon-15' src='~/svg/visibility.svg'></a>" + "</td>"
+ "</tr>";
$('#DriverTable tbody').append(tr);
}
}
});
}
Your svg folder should be placed under wwwroot.
Then you need to change your path to
<img class='ml-2 icon-15' src='/svg/visibility.svg'></a>
Delete the ~.

Empty Div tag issue for dynamically rendered table

I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();

uncaught type error: can not read length is undefined

In the below JavaScript code cannot read length of undefined error please find out (I want take json array database values to print as a table format with image)
$(document).ready(function() {
$('#opt2').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if (this.checked) {
$.ajax({
method: "GET",
url: "<?php echo base_url(); ?>index.php/secondpage/sorting",
dataType: 'json',
success: function(data) {
var jsonObj = data;
$('#tbody').append('');
n = jsonObj.rooms.length;
for (i = 0; i < n; i++) {
var eachrow = "<tr>" + "<td>" + jsonObj.rooms[i].image_url + "</td>" + "<td>" + jsonObj.rooms[i].name + "</td>" + "<td>" + jsonObj.rooms[i].location + "</td>" + "<td>" + jsonObj.rooms[i].price + "</td>" + "</tr>";
$('#tbody').append(eachrow);
}
}
});
}
});
<table>
<thead>
<tr>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
y it should like the error will come in JavaScript file
and also how to display image with database(i.e phpmyadmin) in JavaScript file
please find out immediately i want answer quickly help me out

Selecting a row in a html table

I am trying to select a row in a table I have created and need use the values. The issue I am having is I created it using doms in javascript and got the values from a stored procedure which then populates the table.
so i use a simple div with an id -
<div id="Tab1" class="tab-pane fade in active"></div>
to create the table and populate it i use an ajax call -
function GetcarData() {
$.ajax({
type: "post",
data: JSON.stringify({
price: slidval,
}),
url: "/index.aspx/GetData",
dataType: "json",
contentType: "application/json",
success: function (object) {
responseData(object);
},
complete: function (object) {
},
error: function (object) {
}
});
}
function responseData(object) {
var stringed = JSON.stringify(object.d)
var arr = JSON.parse(stringed);
var i;
var out = "<table id='table' class='table table-striped'>";
var rowHeader = $("<tr></tr>").appendTo(out);
out += "<td><font size='4'>Make</font></td>";
out += "<td><font size='4'>Model</font></td>";
out += "<td><font size='4'>Version</font></td>";
out += "<td><font size='4'>Engine</font></td>";
out += "<td><font size='4'>(AV)Price new</font></td>";
out += "<td><font size='4'>(Av)Price used</font></td>";
out += "<td><font size='4'>Image</font></td>"
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Make +
"</td><td>" +
arr[i].Model +
"</td><td>" +
"£" + arr[i].version +
"</td><td>"+
arr[i].Engine_size +
"</td><td>" +
"£" + arr[i].price_new +
"</td><td>" +
"£" + arr[i].price_used +
"</td><td><img src="+arr[i].image_url+" width='150' height='100'>" +
"</td></tr>";
}
out += "</table>";
document.getElementById("Tab1").innerHTML = out;
}
Now the issue I have is I cant seem to select a row.
I tried
("#table tr").click(function(){
alert("selected");
});
but that did not work.
Anyhelp would be appreciated
You created a set of elements that weren't in the DOM when page and were only added after initial DOMContentLoaded
To listen for events on elements that are dynamically added, removed via JavaScript DOM manipulations, you need to use slightly different event listener.
$(document).on('%eventName%', '%selector%', function() { // do your stuff });

Categories

Resources