How to clear previous search result shown by ajax success? - html

I wanted to clear all the search result shown by ajax search like when the user type for next query it will update it.
$(document).ready(function(){
var text;
$("#button").on('click',function (e) {
e.preventDefault();
var q=$("#q").val();
$.ajax({
url: "/search",
data: {q:q},
type: "GET",
dataType : "json",
success: function(result) {
var event_data = '';
for (var i = 0; i < result.length; i++) {
event_data += '<tr>';
event_data += '<td>' + '<img src=' +result[i]['video']['thumbnail_src']+ '></img>' +'</td>';
event_data += '<td>' +result[i]['video']['title']+'</td>';
event_data += '<td>' +result[i]['video']['duration']+ '</td>';
event_data += '<td>' + '<a href' +result[i]['video']['url']+ '>'+ "Download" +'</a>' +'</td>';
event_data += '</tr>';
} $("#list_table_json").append(event_data);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
},
always: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
});
This is my html file for table where i was appending result from ajax success, can you guys let me know another technique for this. I wanted to clear previous result and update the new result.
Search
<table class="table table-responsive table-hover table-bordered" id="list_table_json">
<thead>
<tr>
<th>Thumbnail</th>
<th>Title</th>
<th>Duration</th>
<th>Download</th>
</tr>
</thead>

On the start of the success handler, use the below code if you want to keep the first tr (headings) and remove the rest of the data
$("#list_table_json").find("tr:gt(0)").remove();
or use if you want to remove everything
$("#list_table_json").empty();
or another way to remove everything
$("#list_table_json").html('');
How to use?
success: function(result) {
$("#list_table_json").find("tr:gt(0)").remove();
var event_data = '';

Related

How to sort data according to date using jquery

l have data JSON coming from URL and l displayed those data in a table.
As you see l have different time dates. l want to add a new element above '12:15 am' to display the full date to make the user know that is a new day as the image below.
Code :
function airport() {
var airport_data = ""
$.ajax('my_airport.json', {
type: 'GET',
dataType: 'json',
timeout: 5000,
cache: false,
}).done(function (data, textStatus, jqXHR) {
data.forEach(element => {
if (element.flight.status.generic.status.text == 'scheduled') {
airport_data += '<tr>';
airport_data += '<td><p>' + element.flight.airline.name + '</p></td>';
airport_data += '<td><p>' + element.flight.identification.number.default + '</p></td>';
if (element.flight.aircraft == null) {
airport_data += '<td><p>N/A</p></td>';
} else {
airport_data += '<td><p>' + element.flight.aircraft.model.code + '</p></td>';
}
airport_data += '<td><p>' + element.flight.airport.origin.position.region.city + '</p></td>';
/// time is here
airport_data += '<td><p>' + moment.unix(element.flight.time.scheduled.arrival).format("h:mm a") + '</p></td>';
airport_data += '<td><p>' + element.flight.status.generic.status.text + '</p></td>';
if (!element.flight.time.scheduled.arrival) airport_data += "<tr><td><p>N/A</p></td></tr>";
}
document.getElementById("data").innerHTML = airport_data
var rows = $("#data");
rows.hide();
$('.row-data:last-child').after(rows);
rows.fadeIn(500);
});
})
}
html :
<div class="table-responsive">
<table class="table table-condensed text-center table-hover"">
<thead>
<tr>
<th>AIRLINES</th>
<th>CALLSIGN</th>
<th>TYPE</th>
<th>FROM</th>
<th>TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody id="data" class="data">
</tbody>
</table>
</div>
If the rows comes already sorted you just have to insert the additional rows every time the date is going to change. Do it this way:
before entering the forEach initialize a variable called prevDate with an empty string;
inside the foreach, before appending the flight row, format the arrival as YYYYMMDD and assign it to a variable called currentDate;
compare currentDate with prevDate, if they differ then add the date header;
assign currentDate to prevDate.
That's all.
EDIT
First, let me say you have a syntax error in your html, you have closed the double quote 2 times on the table class.
Second, your js code is iterating over the root of the json returned by the ajax call, but the json you have added in the comment has a more nested structure, the array is located down to "data.result.response.airport.pluginData.schedule.arrivals.data".
So, after resambling the above, your code should become like this:
<html>
<head>
<script src="jquery-2.x-git.min.js"></script>
<script src="moment.js"></script>
<script>
$(airport);
function airport() {
var airport_data = ""
$.ajax('my_airport.json', {
type: 'GET',
dataType: 'json',
timeout: 5000,
cache: false,
}).done(function (data, textStatus, jqXHR) {
var prevDate = '';
data.result.response.airport.pluginData.schedule.arrivals.data.forEach(element => {
var curDate = moment.unix(element.flight.time.scheduled.arrival).format("YYYYMMDD");
if (curDate != prevDate) {
airport_data += '<tr><td colspan="5">ARRIVALS - '+
moment.unix(element.flight.time.scheduled.arrival).format("dddd, MMM D")+
'</td></tr>';
prevDate = curDate;
}
if (element.flight.status.generic.status.text == 'scheduled') {
airport_data += '<tr>';
airport_data += '<td><p>' + element.flight.airline.name + '</p></td>';
airport_data += '<td><p>' + element.flight.identification.number.default + '</p></td>';
if (element.flight.aircraft == null) {
airport_data += '<td><p>N/A</p></td>';
} else {
airport_data += '<td><p>' + element.flight.aircraft.model.code + '</p></td>';
}
airport_data += '<td><p>' + element.flight.airport.origin.position.region.city + '</p></td>';
/// time is here
airport_data += '<td><p>' + moment.unix(element.flight.time.scheduled.arrival).format("h:mm a") + '</p></td>';
airport_data += '<td><p>' + element.flight.status.generic.status.text + '</p></td>';
if (!element.flight.time.scheduled.arrival) airport_data += "<tr><td><p>N/A</p></td></tr>";
}
document.getElementById("data").innerHTML = airport_data
var rows = $("#data");
rows.hide();
$('.row-data:last-child').after(rows);
rows.fadeIn(500);
});
})
}
</script>
<head>
<body>
<div class="table-responsive">
<table class="table table-condensed text-center table-hover">
<thead>
<tr>
<th>AIRLINES</th>
<th>CALLSIGN</th>
<th>TYPE</th>
<th>FROM</th>
<th>TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody id="data" class="data">
</tbody>
</table>
</div>
</body>
</html>
The rest is a matter of styling.

How to delete post from table row using ajax for asp.net mvc?

I need to implement a delete function for posts. I'm showing all the posts in a table. I can't seem to find a better way to show all the post.
This is the html:
<table border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQuery code for loading posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button
onclick='deletepost("+data[i].PostId+")'>Delete me</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
Incomplete JQuery Code for Delete Post
var deletepost=function(){
$.ajax({
url:"http://localhost:12091/api/post/"+deleteid, <--how should I get this id from the table?
method: "DELETE",
header:"Content-Type:application/json",
data:post,
complete:function(xmlhttp, status){
if(xmlhttp.status == 204)
{
alert("Post Deleted");
}
else{
console.log(xmlhttp.status+":"+xmlhttp.statusText);
}
}
})
}
Finally my Code in controller
public IHttpActionResult Delete(int id)
{
postRepository.Delete(id);
return StatusCode(HttpStatusCode.NoContent);
}
Now my questions:
Is there a better way to show posts in webpage except table? I need to show user id, post id, post
how should I get the post ID from html and use it to delete the post?
**
Update:
I've completed the delete function like suggested:
var deletepost=function(deleteid){
$.ajax({
url:"http://localhost:12091/api/post/"+deleteid,
method: "DELETE",
header:"Content-Type:application/json",
data:deleteid,
complete:function(xmlhttp, status){
if(xmlhttp.status == 204)
{
alert("Post Deleted");
}
else{
console.log(xmlhttp.status+":"+xmlhttp.statusText);
}
}
})
}
The error that I'm getting:
Uncaught ReferenceError: deletepost is not defined
Tables are a long debate and depends on framework you are using. In bootstrap they use it : Bootstrap tables
You just need to add your id in you delete function :
var deletepost=function(deleteid){
...
}
Then add a column to your table for displaying a delete button :
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td>";
str += "<button onclick='deletepost("+data[i].PostId+")'>Delete me</button>";
str += "</td>";
str += "</tr>";
}
You shouldn't use complete method but sucess and error. Complete is for executing code in both case.
$.ajax({
success: function (data) {
box.html(data);
},
error: function() {
box.html("Sorry.");
}
});

How do I get the form data in Codeigniter controller using ajax?

http://zivite.com/salary/
Hi, Guys please visit the link above mentioned.
Whenever choosing the designation from the dropdown, it will be listed all the data associated with that particular designation.
In the loop data, I have added form around the tr and submit button as well as added some additional fields like attendance, loan, rate etc. Whenever hit the submit button for a particular person. it should be stored in my database table which called the salary table.
Now my problem is not getting the data inside the model when we hit the submit button,
If you inspect it you can see array is creating there but no data from the submitted form
see this image link below
https://ibb.co/h11SgMV
// view
<?php include "template/header.php"; ?><!-- Start Page content -->
<div class="content">
<div class="container-fluid">
<div class="card-box">
<form action="%3C?php%20echo%20base_url('con_employee/employeeSearch');%20?%3E" class="form-inline" method="post">
<div class="form-group" style="padding-right:10px; width:100%;">
<select class="custom-select" id="empDesignation" name="empDesignation">
<option selected>
Designation
</option><?php foreach($categories as $category){ ?>
<option value="<?php echo $category['cat_id']; ?>">
<?php echo $category['cat_name']; ?>
</option><?php } ?>
</select>
</div>
</form><br>
<div class="row">
<table class="table table-hover table-centered m-0 table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Account Number</th>
<th>Attendance</th>
<th>Rate</th>
<th>Loan</th>
<th>Action</th>
</tr>
</thead>
<tbody id="salaryData"></tbody>
</table>
</div>
</div>
</div><!-- container -->
</div><!-- content -->
<!-- end row -->
<script>
$(function() {
$('#empDesignation').change(function() {
var user_designation = $(this).val();
if (user_designation == '') {
$('#empName').prop('disabled', true);
} else {
$('#empName').prop('disabled', false);
$.ajax({
url: "<?php echo site_url(); ?>con_salary/add_salary_for_employee",
type: "POST",
data: {
'user_designation': user_designation
},
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<form class="" id="myform">' +
'<td>' + data[i].emp_name + ' <\/td>' +
'<td>' + data[i].cat_name + '<\/td>' +
'<td>' + data[i].emp_account_number + '<\/td>' +
'<td>' +
'<input type="text" class="form-control" name="attendance" placeholder="Attendance" required>' +
'<\/td>' +
'<td>1<\/td>' +
'<td>' +
'<input type="text" class="form-control" name="loan" placeholder="Loan" required>' +
'<\/td>' +
'<td>' +
'<a href="javascript:;" class="btn btn-primary item-edit" id="btnSave">Submit<\/a>' +
'<\/td>' +
'<\/form>' +
'<\/tr>';
}
$('#salaryData').html(html);
// $('#salaryData').html(data);
},
error: function() {
alert('No Data');
}
});
}
});
});
//insert data to salary table
$('#salaryData').on('click', '.item-edit', function() {
$('#myform').attr('action', '<?php echo base_url() ?>con_salary/addSalary');
var url = $('#myform').attr('action');
var data = $('#myform').serialize();
var attendance = $('input[name=attendance]');
var loan = $('input[name=loan]');
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response) {
},
error: function() {
}
});
});
</script> <?php include "template/footer.php"; ?>
// controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Con_salary extends CI_Controller
{
public function __construct(){
parent:: __construct();
$this->load->model('queries_salary');
}
public function index()
{ $data['categories'] = $this->queries_salary->fetchCategory();
$this->load->view('employee_salary_view',$data);
}
public function add_salary_for_employee()
{
$designation_id=$this->input->post('user_designation');
$users = $this->queries_salary->fetchEmployeeforsalary($designation_id);
echo json_encode($users);
}
public function addSalary()
{
$result = $this->queries_salary->addSalary();
// $msg['success']=false;
// $msg['type']='add';
// if($result){
// $msg['success']=true;
// }
// echo json_encode($msg);
}
//end
}
?>
// model
<?php
class Queries_salary extends CI_Model
{
public function fetchCategory()
{
$query= $this->db->get('category');
return $query->result_array();
}
public function fetchEmployeeforsalary($designation_id)
{
$this->db->where('emp_designation_id',$designation_id);
$this->db->join('category','employee.emp_designation_id = category.cat_id');
$query=$this->db->get('employee');
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
// $this->db->where('emp_designation_id',$designation_id);
// $query=$this->db->get('employee');
}
public function addSalary()
{
$field = array(
'salary_attendance'=>$this->input->post('attendance'),
'salary_loan'=>$this->input->post('loan')
);
print_r($field);
exit();
// $this->db->insert('salary',$field );
// if($this->db->affected_rows()>0)
// {
// return true;
// }
// else{
// return false;
// }
}
//end
}?>
A form is not allowed to be a child of a table, tbody or tr HTML elements.
If attempting to put one there will tend to cause the browser to move the form to it appears after the table.So in your case form results an empty data.
Here i adjusted code your code little bit and will work for you.
for (i = 0; i < data.length; i++) {
html += '<tr class="user_data" >' +
'<td>' + data[i].emp_name + ' <\/td>' +
'<td>' + data[i].cat_name + '<\/td>' +
'<td>' + data[i].emp_account_number + '<\/td>' +
'<td>' +
'<input type="text" class="form-control attendance" name="attendance" placeholder="Attendance" required>' +
'<\/td>' +
'<td>1<\/td>' +
'<td>' +
'<input type="text" class="form-control loan" name="loan" placeholder="Loan" required>' +
'<\/td>' +
'<td>' +
'<a href="javascript:;" class="btn btn-primary item-edit" id="btnSave">Submit<\/a>' +
'<\/td>' +
'<\/tr>';
}
Bottom side script
$('#salaryData').on('click', '.item-edit', function() {
var url = '<?php echo base_url() ?>con_salary/add_salary_for_employee';
var current_row = $(this).closest('.user_data');
var data = { attendance: current_row.find('.attendance').val(), loan: current_row.find('.loan').val() };
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response) {
},
error: function() {
}
});
});
One important note is that if you are using single form and using same type of input with same name use it as Array.
Eg : name="loan[]"

Pass parameter to href of a table cell in ajax

I'm new to use ASP.net for web app programming. I'm using the following ajax function aiming to send a parameter to the controller with the name of yyy. However, no matter how I manipulate the variable {id} in this case, the controller either get the string {id} or null. The variable of {id} is actually storing an integer value, for example, 3. I want to pass the integer 3 to the controller. Please help! Thanks!
$.ajax({
type: "GET",
url: "http://localhost:8086/xxx",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var testData = '';
$.each(data, function (key, value) {
testData += '<tr>';
var id = value.testDataID.toString();
testData += '<td style="cursor:pointer">' + '<a href="http://localhost:8087/xxx/yyy?param="+{id}>' + value.serialNumber + '</a>' + '</td>';
testData += '<td>' + value.testDataID + '</td>';
testData += '<td>' + value.sN + '</td>';
testData += '</tr>';
});
$('#testDataTable').append(testData);
}
});

Populate HTML table with JSON data

We would be grateful for some guidance, [we are early into coding] and have looked at lots of examples but can cannot get our JSON to import into the table.
At that moment we have the table data in-line however a correctly formatted JSON file is now available and automatically updates and we want to load it into the table on the fly when the page is loaded.
This is an example of what were currently use:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
var data = [
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
</script>
There are a lot more lines of data, the table has CSS styling and applies the sortTable(n) function to the Headers. It displays perfectly, looks and functions like we want,
We've Googled [lots] and tried various load / populate scripts and attempted to get the example on w3schools working - https://www.w3schools.com/js/js_json_html.asp - alas we're fairly new to this.
Our JSON file /assets/sample.JSON is correctly formatted and meets the requirements.
How do we do a simple import of the JSON to populate the table id="gable"?
Ok, so in this solution I am going to assume that your external json file is called 'example.json'
Your external file should look something like this
example.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
The html remains the same all the changes have been made in the script tags. I split the functionality into 2 new functions. The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table.
I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.
here is the code for the html file:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
}
</script>
you can have a function to create the table independent from your data fields:
function updateTable(tableId, jsonData){
var tableHTML = "<tr>";
for (var headers in jsonData[0]) {
tableHTML += "<th>" + headers + "</th>";
}
tableHTML += "</tr>";
for (var eachItem in jsonData) {
tableHTML += "<tr>";
var dataObj = jsonData[eachItem];
for (var eachValue in dataObj){
tableHTML += "<td>" + dataObj[eachValue] + "</td>";
}
tableHTML += "</tr>";
}
document.getElementById(tableId).innerHTML = tableHTML;
}