Append AJAX Output to HTML table - javascript

I have done my research and I can't seem to find the appropriate answer.
Here is the problem. First off, this question may be broad. And I am new to ajax. I am using laravel and I have just created a controller which handles two dates whereBetween to find the result set and ajax is handling the get request. I am having two issues.
First being, I have no idea on how to append to my existing table. The other issue is a bit complicated. Currently i am using carbons diffForHumans() to display the time taken.
Also using if else statements. Here is how my current table looks like (this is looped from controller for sample data. this is not ajax):
<table class="table">
<thead>
<tr>
<th>Room Number</th>
<th>Cleaned By</th>
<th>Total Time</th>
<th>Supervised</th>
<th>Issues</th>
<th>Cleaned</th>
<th>View</th>
</tr>
</thead>
<tbody>
#foreach($clean as $cleans)
<tr>
<td>{{$cleans->roomnumber}}</td>
<td>{{$cleans->users->name}}</td>
<td>{{$cleans->roomnumber}}</td>
#if($cleans->verified == 1)<td class="verified">Yes</td>#else()<td class="notverified">No</td>#endif
#if($cleans->img1 || $cleans->img1 || $cleans->img1 == !null)<td class="verified">Yes</td>#else()<td class="notverified">No Issues</td>#endif
<td>{{$cleans->created_at->diffForHumans()}}</td>
<td><i class="lnr lnr-eye"></i></td>
</tr>
#endforeach
</tbody>
</table>
As shown above, i have used with() in my controller to get the users name using user_id column. And the diffForHumans(). Also some if else statements.
Here is my AJAX so far:
$(function() {
$('.form').submit(function(event) {
// get the form data in value key pair using jquery serialize
var data = $(this).serialize();
// get the url we are posting to from the forms action attribute
//var url = $(this).attr('/admin/search');
// process the form
var search = $.ajax({
type: "POST", // define the type of HTTP verb we want to use (POST for our form)
url: "search", // the url where we want to POST
data: data, // the url where we want to POST, set in variable above
dataType: "json", // what type of data do we expect back from the server
encode : true
})
// using the done promise callback (success)
search.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});//submit function
});//doc ready end
So how can I append to the above table and still maintain those diffForHumans(), if else statements and most importantly the user name using user_id column (relation)?
Update (Controller):
public function search(Request $request){
$data = $request->only(['from', 'to']);
$data['to'] .= ' 23:59:59';
$output = Clean::whereBetween('created_at', $data)->get();
//return view('admin/search-test', compact('output'));
//return Response($output);
return Response::json(array($output));
}

Related

Create html table from array from ajax response

In my Laravel app, I add ajax query (which work after pressed button). I get the result in ajax, I see it on console (it's array).
But I need to send an answer from js to PHP for creating a table
This is code of input:
<input type="text" name="check" id="check">
This is code of button:
<button type="button" class="check-client btn btn-success">Find</button>
This is code of ajax (JS):
$(document).on("click", ".check-client", function () {
const data = $("#check").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: {
'data': data
},
url: '/checkValues',
success: function (result) {
console.log(result);
const dataForTable = result;
}
});
});
For creating table I try to do this:
send response to php+html:
$(".testClass").append(result);
get this value:
<div class="testClass"></div>
and create a table, using foreach:
<div class="testClass"></div>
<table class="table table-bordered text-center">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Person</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tbody>
#foreach($dataForTable as $item)
<tr>
<th scope="row">$item['id']</th>
<td>$item['person']</td>
<td>$item['cost']</td>
</tr>
#endforeach
</tbody>
</table>
So, it doesn't work. How to create a table from ajax response?
The problem is that you trying to run jQuery at the client side to uses the return of ajax request (dataForTable) at the server side, it's out of PHP context server. PHP works only server side, meanwhile jQuery is working on browser client, if you want to run javascript in the server side you have to search for other technology, like Node, look at node.js.
Wether you want to update a table on client side using ajax request you have to update a table iterate de variable (dataForTable) on client side, after the request, like this:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
There are many other examples like this above in jQuery.
Finally, you have to work at Client side wether you want to use jQuery, or work at server side using the PHP helpers.

Ajax Request is working on first element BUT not working on other requests? [duplicate]

This question already has answers here:
Does ID have to be unique in the whole page?
(14 answers)
Closed 4 years ago.
I'm implementing delete functionality via AJAX but when i hit delete icon from the table, first element deletion request works fine and at first click it deletes the record, but it doesn't send deletion request for the 2nd or 3rd elements.
JS Ajax Request:
// Delete symptom which is linked with a Remedy ( Causes page )
$("#linked-symptom").click(function(e) {
e.preventDefault();
var symptom_id = $("#linked-symptom").attr('data-id');
var dataString = '&id='+symptom_id;
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-symptom') ?>',
success: function(data) {
$("#successMessage").show().delay(5000).fadeOut();
}
});
});
HTML Markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($symptoms as $key => $symptom){ ?>
<tr>
<td class="all"><?php echo $symptom['title']; ?><br></td>
<td><a class="cx-action row-delete" href="javascript:void(0)" data-id="{{symptom['id']}}" id="linked-symptom"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Function:
public function deldeleteLinkedSymptomAction(){
// Get the Evaluation Symptom Id (if any)
$symptomId = $this->request->get('id', null);
$symptom = CxEbEvaluationSymptomCause::getLinkedSymptomEntryForDeletion($symptomId);
if( $symptom ){
$symptom->delete();
return true;
}else{
return false;
}
}
HTML ID should be unique across the page, but you have multiple instances that you then try to use for a jQuery action. It will only affect the first one it finds. Try using this instead:
// Delete symptom which is linked with a Remedy ( Causes page )
$("a.row-delete").click(function(e) {
e.preventDefault();
var symptom_id = $(this).data("id");
var dataString = '&id='+symptom_id;
...
});

Ajax success function only updating values for first click

Okay I have a html table given below:
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th colspan="2">Total</th>
</tr>
</thead>
<tbody id="cart_table">
...
</tbody>
<tfoot>
<tr>
<th colspan="2">Total</th>
<th colspan="2">$446.00</th>
</tr>
</tfoot>
</table>
I am using ajax to append values clear tbody at every click of a button and refill the tbody with multidimensional session array. It works fine for 1st turn, but does not work for 2nd click
My jquery code is given below
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
<?php
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item):
$item = $each_item['item'];
$price=$each_item['price'];
$quantity=$each_item['quantity'];
?>
$('#cart_table').append("<tr><td><?php echo $item; ?></td><td><?php echo $quantity; ?></td><td><?php echo $price; ?></td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
<?php
endforeach;
?>
}
});
});
});
</script>
I have checked my session values are updated. However, the change is not shown on my table except for first click.
As pointed out in comments PHP is server side language, for it to reflect the changes, your page needs to reload but because you are using ajax page is not going to reload (Or rather we don't need it to reload).
It work for the first time because for the first time when page is loaded, the current data will already be present in your JavaScript function :
Right here :
$('#cart_table').append(<?php echo "<tr><td>".$item."</td><td>".$quantity."</td><td>".$price."</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>";?>);
So what happens here is that when you click for the first time, your ajax will execute and success function is called, this function will add the already presented data because it will not update unless your page is reload. So every time you click, your session will be updated and success function is also called but your table will not reflect the changes.
So, You need to change your PHP code To JavaScript, Here the basic idea of what to do, (Here i have assumed your response is JSON, And also note that following code will not work out of the box because i didn't tested it.)
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
//New JavaScript code, make appropriate changes.
jQuery.each(response, function(key, row) {
$('#cart_table').append("<tr><td>" + row.item + "</td><td>" + row.quantity + "</td><td>" + row.price + "</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
});
}
});
});
});

Django data updation in the table

I am using Django to enter some data into my database. After entering the data I want to edit it. Now, what I am trying is, the user should not go to any other page to change the data. So I have implemented a javascript method which edits the text on the front end.
How do I reflect the changes made by the user in the database?
The related code is given below:
<html>
{% csrf_token %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table id="table">
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
{% for record in queryset %}
<tr>
<td onClick="clickable(this)"> {{record.first}} </td>
<td onClick="clickable(this)"> {{record.second}}</td>
</tr>
{%endfor%}
</table>
<script>
function clickable(ele)
{
var value = prompt("Enter the details");
if(value)
{
ele.id='edited'
ele.innerHTML = value;
//I want to send the request to my django view to edit the database here
//The data has been updated.
}
You should send a Ajax request to your server using jQuery you are using. with Ajax request request you should send your updated data .
Simple Ajax request can be .
$('#click_place').click(function() { // when click is placed
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the content here Ex. {'name': 'test', 'phone': '123'}
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // request url
success: function(response) { // on success..
// display your message
}
});
return false;
});
You can follow How to POST a django form with AJAX & jQuery .
http://coreymaynard.com/blog/performing-ajax-post-requests-in-django/ .
Edit :
You can simply call below function at any event .
function myajaxhit() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the content here Ex. {'name': 'test', 'phone': '123'}
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // request url
success: function(response) { // on success..
// display your message
}
});
}
just call myajaxhit() at any place . Please change it as per your requirement .

ASP.NET MVC 3 - Ajax update table - model

I am trying to update a record list with ajax, represented on a table, where each record as an javascript delete link. If I preload the table, the RemoveLink works fine, but once the div "RecordListPartialView" is updated via ajax, It no longer works.
I checked with firebug that the generated html code is correct for each row. It looks like the browser isn't aware of the new code and so it doesn't trigger the javascript links.
Can someone please explain me what is going on?
(1) Here is the View code:
$(".RemoveLink").click(function () {
var _id = $(this).attr("data-id");
var recordToDelete = { id: _id };
var json = $.toJSON(recordToDelete);
$.ajax({
url: '/MortagePayment/RemoveMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
}
});
});
$(".AddLink").click(function () {
var _year = $("#NewRecord_year").val();
var _month = $("#NewRecord_month").val();
var _mortageValue = $("#NewRecord_mortageValue").val();
var newRecord = { year: _year, month: _month, mortageValue: _mortageValue };
var json = $.toJSON(newRecord);
$.ajax({
url: '/MortagePayment/AddMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
$("#NewRecord_year").val(0);
$("#NewRecord_month").val(0);
$("#NewRecord_mortageValue").val(0);
}
});
});
<div id="RecordListPartialView">
#Html.Partial("MortageRecordList", Model.MortageRecordList)
</div>
(2) the Partial View
<table id="mortageRecordListTable">
<tr>
<th colspan=4>Current reductions</th>
</tr>
<tr>
<th>Year</th>
<th>Month</th>
<th>Value</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr id="row-#item.mortageRecordId">
<td>
#item.year
</td>
<td>
#item.month
</td>
<td>
#item.mortageValue
</td>
<td>
<p class="RemoveLink" data-id="#item.mortageRecordId">Remove</p>
</td>
</tr>
}
</table>
(3) and the Controller:
[HttpPost]
public ActionResult AddMortageRecord(MortageRecord newRecord) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
if (ModelState.IsValid)
mortageRecordSet.AddMortageRecord(newRecord);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Success = true, Message = partialViewHtml });
}
[HttpPost]
public JsonResult RemoveMortageRecord(int id) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
mortageRecordSet.RemoveMortageRecord(id);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Sucess = true, Message = partialViewHtml });
}
If I understand you correctly.
If I preload the table, the RemoveLink works fine, but once the div
"RecordListPartialView" is updated via ajax, It no longer works.
Change your your .click event with .live
$(".RemoveLink").live("click",function(){
//any click event code comes here
});
I think you might need to call the click handler again in order to reattach it to the new DOM elements, since jQuery iterates through all the elements with the correct class when you actually call the $(".RemoveLink").click() and $(".AddLink").click() functions, not lazily whenever something is clicked.
OK, do you have a jquery event in a separate .js script file and have attached an event to an element inside a PartialView?
well! if yes, whenever the PartialView renders itself again (no matter what is the reason) all of it's bound events will be gone! then you should rebind them again after rendering the PartialView.
there are different approaches, for example:
In the Ajax.ActionLink (or any ajax call that makes the
PartialView re-render ) set OnSuccess to a jquery function that
rebinds PartialView's events.
Move all of your jquery event bindings codes from separate .js
script file to the inside of your PartialView's file (cstml). in
this case every time PartialView has been rendered, those events
will be bound again.

Categories