JavaScript table doesn't render in table - javascript

I have this JavaScript
function pickdet(Id) {
//alert(Id);
var dd = Id;
$.ajax({
cache: false,
url: "/PVSigns1/GetDetails",
data: { 'Id' : Id },
type: "GET",
dataType: "json",
success: function (data) {
//alert('i dey here')
var row = "";
var baseurl = '#Url.Action("Edit","PVSigns1")' + '?Id=';
$.each(data, function (index, item) {
var clickUrl = baseurl + item.PVSignId;
//row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue + "</td><td> <input type= 'button' onclick= location.href = + '<Url.Action("Create", "PVSigns1", new { Id = item.PVSignId }) ' />" + "</td></tr>";
row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue +
"</td><td> <button class='editbtn btn btn-xs btn-success' data-url = '" + clickUrl + "'> <i class='fa fa-edit fa-lg'></i> Edit</button></td></tr>";
});
$("#pvv").html(row);
},
error: function (result) {
$("#pvv").html('Nothing to show <br /> <p />' + result);
}
});
}
$(function () {
$("button.editbtn").click(function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
});
When I run it, it display perfectly on the browser, but the link created don't work, and when I view the page source, the tbody part which the code above is supposed to inject, doesn't get rendered.
This is what I get, Click on any of the green buttons
in the top table, it loads the second table. The issue is with the second table.
Note: I am using JQuery Datatables.
This the rendered output from page source
<div>
<h3> Details</h3>
<table id="Pv" class="table table-condensed">
<thead>
<tr>
<th>Sign</th>
<th> Value </th>
<th></th>
</tr>
</thead>
<tbody id="pvv">
</tbody>
</table>
Notice <tbody id="pvv"> is empty, not table elements there. What is the issue?

You need to use delegation of dom element for click event. which element generated after binding event after existing dom
$("#Pv").on('click','button.editbtn', function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});

Related

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

Change text of td element when click on it using jquery

I am getting Json data in output and appended to table with edit option, so what I want is when click on Edit of td then clicked td element text should change from 'Edit' to 'Save' and when click on 'save' again it change to edit, but at time one td element should change from 'Edit' to 'Save' at atime only one 'Save' should active and others remain 'Edit' .
<table class="append_data">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
<th>Action</th>
</tr>
</table>
//script to get data:
$.ajax({
url: "<?= base_url('controller/get_users') ?>",
type: 'POST',
data: {
},
success: function (myJSON) {
var output = myJSON;
var html = '';
$.each(output, function (key, value) {
html += '<tr>';
html += '<td>' + value.name + '</td>';
html += '<td>' + value.mobile + '</td>';
html += '<td>' + value.id + '</td>';
html += '<td><span class="change_res' + value.id + '">Edit</span></td>';
html += '</tr>';
});
$('.append_data tbody').append(html);
},
error: function (xhr) {
alert(xhr.status);
}
});
//script to change text
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$(this).text('Save').siblings().text('Edit');
});
getting output:
Expected output:
you can try
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$('.edit_user').not(this).text('Edit'); // back all the edit_user to Edit but not this
$(this).text(($(this).text().trim() == 'Save') ? 'Edit' : 'Save'); // change the text for this between Edit or Save
});
Explanation :
$('.edit_user').not(this).text('Edit'); back all other elements text to Edit
$(this).text().trim() == 'Save') ? 'Edit' : 'Save' is a short hand method of if statement .. means if the text of the element is Save set it to Edit and vice versa .. and about .trim() here for double check that the text is exactly equal the string

Reduce Code While Showing ajax loading bar for tables

i use the below code to call results from a mysqli database and display them on a page with a live search function.. while loading the results it displays <div id='ajax_request'></div> basicaly a loading gif and on completion it hides that div and shows the div <div id='ajax_results_table'></div> to show the results
I'm curious to know if there is a better method out there for doing the same thing as I could have multiple requests on one page and I need each div to display loading while it's performing its own ajax request
so far I would copy the same code and change the id's for the divs
I'm completely new to ajax and would like to learn more so far this is what I have got.
The Html Code...
<input type='text' class='form-control' onkeyup='showResult(this.value)' placeholder='Search Results'>
<div id='ajax_request'><img src='/ajax-loader.gif' class='text-center'> Fetching Data ...</div>
<div id='ajax_error'>Something went wrong with our ajax request</div>
<table id='ajax_results_table'>
<thead>
<tr>
<th> SMS ID</th>
<th> Time Stamp</th>
<th> Mobile Number</th>
<th> Message</th>
<th> Message Status</th>
</tr>
</thead>
<tbody id='ajax_results'>
</tbody>
</table>
The Ajax Code:
<script>
function showResult(str) {
$.ajax({
url: '/getjson.php?search=' + str,
type: 'POST',
dataType: 'json',
Timeout: 3000,
beforeSend: function() {
$('#ajax_request').show();
$('#ajax_results_table').hide();
$('#ajax_error').hide();
},
success: function(response) {
var trHTML = '';
$.each(response, function(key, value) {
trHTML +=
'<tr><td>' + value.ID +
'</td><td>' + value.Timestamp +
'</td><td>' + value.Number +
'</td><td>' + value.Message +
'</td><td>' + value.Status +
'</td></tr>';
});
$('#ajax_results').html(trHTML);
$('#ajax_request').hide();
$('#ajax_results_table').show();
},
error: function() {
$('#ajax_request').hide();
$('#ajax_error').show();
}
});
}
showResult('');
</script>

Empty data in html append table

I have the following script which populates a table with data when a dropdown value is selected :
<script>
$(document).ready(function(){
$('#commodity_name').change(function (){
//picks the value of the selected commodity_name from the dropdown
option = $(this).find('option:selected').val();
html='';
htmlhead='';
// alert(option)
$.ajax({
type:"GET",
//gets data from the url specified based on the selected commodity_name in the dropdown
url:"<?php echo base_url();?>user_transactions/return_details/"+option,
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++){
//Loops through the data to give out the data in a table format
//alert(data[i].transaction_type)
html += '<tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="'+data[i].commodity_name+'"/></td>\n\
<td><input type="text" id="transaction_type' + i + '" name="transaction_type[]" value="'+data[i].transaction_type+'"/></td>\n\
<td><input type="text" id="total_quantity' + i + '" name="total_quantity[]" value="'+data[i].total_quantity+'"/></td>\n\
<td><input type="text" id="remarks' + i + '" name="remarks[]" value="'+data[i].remarks+'"/></td>\n\
<td><input type="text" id="unit_cost' + i + '" name="unit_cost[]" value="'+data[i].unit_cost+'"/></td>\n\
<td></td><td></td></tr> ';
}
htmlhead+='\n\
<th>Commodity Name</th>\n\
<th>Transaction Type</th> \n\
<th>Available Quantity</th> \n\
<th>Available Quantity</th> \n\
<th>Department</th>\n\
<th>Requestor Name</th>\n\
';
//alert(html);
//alert(htmlhead);
$('#thead').append(htmlhead);
$('#you').append(html);
//delegated submit handlers for the forms inside the table
$('#issue_1').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url()?>transactions/issues', $('#Issues_Form').serialize(), function () {
//success do something
alert("Success");
var url = "<?php echo base_url()?>transactions/view_request";
$(location).attr('href',url);
}).fail(function () {
//error do something
alert("Failed please try again later or contact the system Administrator");
})
})
},
error:function(data){
}
})
});
});
</script>
How can I clear the data from the html table that has been appended when I select the next commodity_name in the drop down list , I get only the data returned from the new select I have picked from the drop down list.
Just empty the html before appending.
...
$('#thead').empty();
$('#you').empty();
$('#thead').append(htmlhead);
$('#you').append(html);
...
Try to use the .detach() method of Jquery. Here the link: http://api.jquery.com/detach/

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.

Categories