jquery datatables "search" returns previously deleted data - javascript

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

Related

Search in .net MVC with AJAX. What can I do for the following code?

I want to do a search with AJAX. I simply did with the get method through passing search string in controller but that not I want
Below my controller code, where I get the search value from URL and return DATA (which is a list)
if (search != null)
{
if (search.ToLower().ToString() == "paid")
{
DATA = DATA.Where(a => a.Purchased_Price > 0).ToList();
}
else if (search.ToLower().ToString() == "free")
{
DATA = DATA.Where(a => a.Purchased_Price == 0).ToList();
}
else
{
DATA = DATA.Where(a => a.Purchased_File_Name.ToLower().StartsWith(search.ToLower()) || a.Purchased_Category.ToLower().StartsWith(search.ToLower()) || a.User1.Email.ToLower().StartsWith(search.ToLower()) || a.Purchased_Price.ToString().StartsWith(search)).ToList();
}
ViewBag.SoldList = DATA.ToPagedList(page ?? 1, pageSize); *this is what I actually did*
return Json(DATA , JsonRequestBehavior.AllowGet); *this is trial I do not know this work or not*
}
Below is the script which I wrote in view. Where I am going wrong? I'm not aware of that. I want whatever list comes with the help of whatever search I entered. To be printed in the table. Table is just above this script; I don't think it's needed so I did not include that.
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var search_value = $("#searchText").val();
alert(search_value);
var SetData = $("#tabledata"); *tabledata is id of tbody tag *
SetData.html("");
console.log("setddata");
console.log(SetData);
$.ajax({
type: "get",
url: "/Home/MySoldNotes?search=" + search_value, *home is controller, mysoldnotes is action*
contentType: "application/ json; charset = utf - 8",
dataType: "html",
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
You must pass object to controller from ajax call. Example
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var objParam = new Object();
objParam.search_value = $("#searchText").val();
$.ajax({
type: "POST",
url: "/Home/MySoldNotes"
contentType: "application/json; charset = utf-8",
data: JSON.stringify(objParam)
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
Then in your controller
public JsonResult MySoldNotes(string search_value)
{
// Do whatever and return json as result
}
List<BuyerReq> DATA = dc.BuyerReqs.Where(a => a.seller_id == ab && a.Status == true).AsQueryable().ToList();
return Json(DATA, JsonRequestBehavior.AllowGet);
while returning from the controller I am getting an error(not success my AJAX call).
but when I am doing this for testing purpose :
var aa = "checking"; return Json(aa, JsonRequestBehavior.AllowGet);
this works. I am not getting the exact error.

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();

filter duplicate rows with cake php and java script

I'm trying to filter table which is append using java script with cake php frame work .
and the following code is for adding this tables when i have click on add new magazine ,, but the problem is that , It's add double rows which has been added before . So i need to filter the added rows to delete the duplicated row.
/// function to show magazines data table
$('#add_researches_button').click(function () {
$("input[name='bstock_researchs_id[]']:checked").each(function (i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function (data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function (index, value) {
CountResearches++;
$("#researches").append("<tr><td>"
+ value.research_serial +
"</td><td>"
+ value.research_release_date +
"</td><td>"
+ value.research_release_hejry_date +
"</td><td>"
+ value.research_pages +
"</td><td>"
+ value.research_copies +
"</td></tr>"
);
});
/// function to show magazines data table
$('#add_researches_button').click(function() {
$("input[name='bstock_researchs_id[]']:checked").each(function(i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function(data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function(index, value) {
CountResearches++;
if ($("#researches tr[data-id='" + value.research_serial + "']").length == 0)
$("#researches").append("<tr data-id='" + value.research_serial + "'><td>" +
value.research_serial +
"</td><td>" +
value.research_release_date +
"</td><td>" +
value.research_release_hejry_date +
"</td><td>" +
value.research_pages +
"</td><td>" +
value.research_copies +
"</td></tr>"
);
});

Refresh AJAX function (gets PHP)

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>

MVC: Get JSON data from a controller using AJAX failed

I'm trying to query data using AJAX from a controller, my controller is:
[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();
return Json(allTests, JsonRequestBehavior.AllowGet);
}
And my javascript code in an extern file is:
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}
When I tried to debug this function, the code will never excute to
$("#ShowDetail").html(txt);
And my page will never be changed. How can I get it work? Thanks.
As you are using $.ajax(), which is asynchronous. Thus the $("#ShowDetail").html(txt) is called before the value is returned from API.
You should set the html() after the each block
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias.value }, //Use the value property here
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt); //Move code to set text here
}
});
}
Try the following function
function Filter() {
var userAlias = $("#UserAliasInput").val();//change this
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt);//place this in the success function
}
});
}

Categories

Resources