JQuery Remove Table Row After Ajax Function - javascript

I'm aware that there are other questions similar to this one, however the way I've executed my code is much different and so it's complicated in how I'm supposed to implement the code into the script.
After executing an Ajax function when I click a button to delete a row, I want that row to fade out however each time I add to code to fade out there's always an error in the console.
Here is the HTML
<tr class="shift_type1">
<td>Date</td>
<td>Location</td>
<td>Name</td>
<td>Time One</td>
<td>Time Two</td>
<td class="controlbuttons">
<div class="settings">
<span class="icons"><img src="http://i.imgur.com/nnzONel.png" alt="X" /></span>
<span class="icons" onclick="deleteRow('rowcodehereinphp')">Delete</span>
<div class="icons">Edit</div>
<div class="icons">Fill</div>
</div>
</td>
</tr>
Here is the jQuery I use to delete the entry from my SQL database
<script type="text/javascript">
function fadeTr(code) {
$(this).closest('tr').find('td').fadeOut(1000,
function(){
// alert($(this).text());
$(this).parents('tr:first').remove();
});
}
function deleteRow(code) {
var proceed = true;
if (proceed) {
post_data = {'code': code};
$.post('DeletePush.php', post_data, function (response) {
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
}
if (response.type == 'error') {
$("#result").hide().html(output).slideDown();
}
else {
$("#result").hide().html(output).slideDown().fadeTr(code);
}
}, 'json');
}
};
Console Log Error
Uncaught TypeError: undefined is not a function
(anonymous function)
j
k.fireWith
x
b

Do this in a little different and easier way :
Suppose your html markup is like this below.
Just add the code to the class or the row. For example
<tr class="shift_type1_<?php echo $rowcodehereinphp; ?>">
.
.
.
</tr>
After this in your jquery or javascript
$(".shift_type1_"+code).fadeOut(slow);
Here "code" is the parameter which you will receive in your deleteRow(code) function.
Hope that helps.. Cheers..

you have to pass the selector of the row to be deleted and remove live function in fadeTr function. You can do something like this
<script type="text/javascript">
function deleteRow(code) {
var proceed = true;
if (proceed) {
post_data = {'code': code};
$.post('DeletePush.php', post_data, function (response) {
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
}
if (response.type == 'error') {
$("#result").hide().html(output).slideDown();
}
else {
$("#result").hide().html(output).slideDown().live(fadeTr(this));
}
}, 'json');
}
};
</script>
<script>
function fadeTr(row) {
$(row).closest('tr').find('td').fadeOut(1000,
function(){
// alert($(this).text());
$(this).parents('tr:first').remove();
});
}
</script>

Related

How to load a grid in javascript using HTML

I'm using the following function to ready and draw the grid as soon as the HTML page is clicked
$(document).ready(function () {
FillGrid();
});
And I'm using the following FillGrid function to draw and show the data from the MSSQL
function FillGrid() {
//if ($('#grid').length == 1) {
// $('#grid tr').not(':first-child').remove();
$.ajax({
//beforeSend: function () {
// $('.grid').show();
// $("#loadingProjects").show();
//},
//complete: function () {
// ShowGrid();
// $("#loadingProjects").hide();
//},
// method: 'POST',
success: function (data) {
//if (data.length == 0) {
// $('<tr><td colspan="4">No Record Found</td></tr>').appendTo($('#grid'));
//}
$.each(data, function (index, item) {
$('<tr>' +
'<td>' + item.ReservationDate + '</td>' +
'<td>' + item.Name1 + '</td>' +
'</tr>').appendTo($('#grid'));
});
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
And this is my HTML code of the grid.
<table class="table table-striped" id="grid" style="display:none;">
<tr>
<th>Reservation No</th>
<th>Name</th>
</tr>
</table>
But the grid is never been drawn when its loaded.
Is this correct or am I'm doing something wrong.
Can anyone help me? This is for a school project.

AJAX appending results duplicates

I'm developing a live search function in a Laravel application, but I'm having some problems because i'm getting duplicate appends, for example I type in "Andrew".
Every key I hit starting with "A" until "W", im appending the results over and over, so Andre creates 6 table rows, but I want it to be only one.
The second problem is that if I delete all the input, I'm trying to show my "initial_table", but that doesn't work.
I tried changing $('#ajax').append(row); from append to html, but then I have only one result no matter how many matches I get.
<table id="usertable">
<thead>
<tr>
<th>Name</th>
<th>Tier</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Tier</th>
</tr>
</tfoot>
<tbody id="ajax">
{{-- search results here --}}
</tbody>
<tbody id="initial_table">
#foreach ($users as $user)
<tr>
<td>{{$user->username}} </td>
<td>{{$user->tier}}</td>
</tr>
#endforeach
</tbody>
</table>
This is my Javascript
<script>
});
// })
document.getElementById("search").addEventListener("keyup", searchUsers);
document.getElementById("search").addEventListener("change", searchUsers);
function searchUsers(){
if(this.value != '') {
$.ajax({
url: '/admin/searchUsers?search=' + this.value,
method: 'GET'
}).done(function(response){
console.log(typeof response);
console.log(response);
if(response.length < 1) {
$('#ajax').append('<span class="text-center">No results found!</span>');
$('#initial_table').hide();
}
else {
$.each(response, function(index, obj){
var row = $('<tr>');
row.append('<td> <a href="/admin/user/' + obj.id + '">' + obj.username + ' AJAX' + '</td>');
row.append('<td>' + obj.tier + '</td>');
$('#ajax').append(row);
$('#initial_table').hide();
});
}
});
}
}
</script>
Tried to add some comments to explain . Hope it helps
document.getElementById("search").addEventListener("keyup", searchUsers);
document.getElementById("search").addEventListener("change", searchUsers);
function searchUsers(){
if((this.value.trim()) != '') // even for extra space it should not allow in
{
$.ajax({
url: '/admin/searchUsers?search=' + this.value,
method: 'GET'
}).done(function(response)
{
console.log(typeof response);
console.log(response);
$('#ajax').empty(); //for 1st query :-on every ajax call it will first empty "#ajax" tbody
$('#initial_table').hide();
if(response.length < 1)
{
$('#ajax').append('<span class="text-center">No results found!</span>');
}
else
{
$.each(response, function(index, obj)
{
var row = $('<tr>');
row.append('<td> <a href="/admin/user/' + obj.id + '">' + obj.username + ' AJAX' + '</td>');
row.append('<td>' + obj.tier + '</td>');
$('#ajax').append(row);
});
}
});
}else // for 2nd query :- your code missing this part to show initial tbody if search text is all blank
{
$('#initial_table').show();
$('#ajax').hide();
}
}

Javascript Scope Issue Possibly

Having trouble with my variable 'html'. I think i have the scope correct but something weird happens when I run this code. the first alert of the 'html' variable produces a blank result and then I populate my select list with the same 'html' variable and it works, then i alert the 'html' variable again and the options show up.
If I remove the two alerts the list is not pop
function populateMakes(years)
{
var makes = new Array();
var html = "";
$.each(years, function () {
var uri = "/api/make?year=" + this;
$.getJSON(uri, function (data) {
$.each(data, function () {
if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
{
makes.push(this.Id);
html += "<option value=" + this.Id + ">" + this.Value + "</option>";
}
});
});
});
alert(html);
$("#Make").html(html);
alert(html);
$("#MakeSection").removeClass("hidden");
};
Document Ready Script
$(document).ready(function () {
populateYears();
$("#Year").change(function () {
$("#MakeSection").addClass('hidden');
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateMakes($("#Year").val());
});
$("#Make").change(function () {
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateModels($("#Year").val(), $("#Make").val());
});
$("#Model").change(function () {
$("#SubModelSection").addClass('hidden');
//
});
$("#Clear").click(function () {
$("#YearSection").addClass('hidden');
$("#MakeSection").addClass('hidden');
$("#ModelSection").addClass('hidden');
$("#SubModelSection").addClass('hidden');
populateYears();
})
});
.getJSON is async and i overlooked the timing. i needed to add the .done callback and set the output there. the script simply wasn't finished yet.
$.getJSON(uri, function (data) {
$.each(data, function () {
if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
{
makes.push(this.Id);
html += "<option value=" + this.Id + ">" + this.Value + "</option>";
}
});
}).done(function () {
$("#Make").html(html);
$("#MakeSection").removeClass("hidden");
});
I also didn't send an array in the event handler on the code I posted in the question. I fixed that first.

How to load JSON data associated with each link onclick?

I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.

Remove alert from a javascript

I've the below code from a tutorial,i want the action but i just want to remove the alert,
here is the code:
<script type="text/javascript">
setTimeout('read()', 10000);
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
I've tried this:
<script type="text/javascript">
setTimeout('read()', 10000);
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post';
}
</script>
but not worked, thanks
If what you're trying to do is just to ignore the response (remove the alert dialogs):
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post',
function(response) {});
}
If you're not using the alert() function anywhere else, you can simply override it so it does nothing:
window.alert = function() {};

Categories