Create html table from array from ajax response - javascript

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.

Related

Append AJAX Output to HTML table

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

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

Laravel simple crud with jquery ajax

I am trying to delete a row from a table using jquery ajax. After couple of trying I cant figure out why my code (deleting part) is not working as I am new with ajax and javascript. Loading data with ajax from server works fine and the script has no console error. When I press delete, I see nothing on network tab. Here is my code:
routes.php
Route::delete('users/{id}','AjaxController#destroy');
AjaxController.php
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
}
view:
<table id="users" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="abc">
</tbody>
</table>
script:
$(document).ready(function(){
var $tbody = $('#abc');
// getting data from server
$.ajax({
type : 'GET',
url : 'api/users',
success: function(users) {
$.each(users, function(i, user){
$tbody.append('<tr id="user_' + user.id + '"><td>'+user.name+'</td><td>'+user.phone+'</td><td><button type="button" class="btn btn-xs btn-danger" id="delete" value="'+user.id+'" name="button">Delete</button></td></tr>');
});
},
error: function(){
alert('error loading data');
}
});
// deleting data
$('#delete').on('click', function(e){
var user_id = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
var user = {
id : user_id
};
$.ajax({
type: 'DELETE',
url : '/user/'+user.id,
success : function(deleteUser)
{
$("#user_" + user_id).remove();
},
error : function()
{
alert('error deleting data');
}
});
}); // deleting block ends
});
});
The problem here is that you're using the same id over and over. However this issue is further compounded by the fact that you are dynamically inserting the content, but your event binding is only observing elements available at page load. Let's fix all of this. First, we need to do-away with the ID.
class="btn btn-xs btn-danger" id="delete" value="'+user.id+'"
Needs to be changed to
class="btn btn-xs btn-danger btn-delete" value="'+user.id+'"
Great. We've used btn-delete. This isn't specific to this particular user functionality. The way that CRUD works, you should be able to re-use this code for every single Model that you interact with through the CRUD Controller.
Now we need to delegate our event binding, and we'll also make the button more generic as discussed in the previous paragraph. For the sake of post length, I'll only show what you -should- have your javascript set up like.
$('table').on('click', '.btn-delete', function(e){
e.preventDefault();
var $btn = $(this),
$table = $btn.closest('table');
$.ajax({
url: $table.data('resource') . '/' . $btn.val(),
type: 'delete'
}).done(function(response){
console.log(response);
}).error(function(x,t,m){
console.warn(x,t,m);
});
});
The token can be moved to the top of the file, it does not need to be nested:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Finally, we need to attach our data-resource property to our table:
<table ... data-resource="users"
Now you've got a reusable model and only need to attach a data-resource="model" property to your table, and a button with a class of btn-delete a value with the id of the entity.

How do you transfer data from a table to a server?

I am trying to fetch data from a table and push the selected data to my server.
I have tried selecting columns from my table then making an HTTP request, but it didn't work.
Can anyone help me?
This is my understanding
here is a procedure if you like to do
insert all you desire record set into an array
make a json using json_encode() method of php.
use curl post request and pass the json string
Here's an example of how to pull data from a HTML table, put it into a javascript array, convert it to json and send it to the server
https://jsfiddle.net/f958qokn/
<table id="MyTable">
<tr>
<td>1</td>
<td>Code Monkey</td>
</tr>
<tr>
<td>2</td>
<td>Code Elephpant</td>
</tr>
</table>
<input id="PostTableData" type="button" value="Post Table Data"/>
<script type="text/javascript">
$(document).ready(function() {
$( "#PostTableData" ).on( "click", function() {
var TableData = [];
$("#MyTable tr").each(function() {
var RowData = [];
var ColumnsData = $(this).find('td');
if (ColumnsData.length > 0) {
ColumnsData.each(function() { RowData.push($(this).text()); });
TableData.push(RowData);
}
});
alert(JSON.stringify(TableData));
jQuery.ajax({
type: 'POST',
url: "/SaveData.php",
data: JSON.stringify(TableData),
dataType: "json",
success: function(data){ alert(data); }
});
});
});
</script>

Adding data dynamically to HTML Table in PHP

I want to add data's from input fields to the HTML Table dynamically when clicking the Add button as shown in the sample image. How can I accomplish this? Can I do it with PHP? As I'm a
beginner I can't find the exactly matched results from here,
but I found a related thread, Creating a dynamic table using php based on users input data, but I think this process is done by 2 pages (1 page for inputs and another for showing that input data's in table) as per the code... Any help will appreciated.
Assuming you're using jquery (given your tag), something like the following will work:
$("button").click(function() {
var newRow = "<tr>";
$("form input").each(function() {
newRow += "<td>"+$(this).val()+"</td>";
});
newRow += "</tr>";
$("table").append(newRow);
});
There are better ways to do this, but this is probably a very simple place to start if you're just beginning to learn. The functions you should be interested in here are: .click, .each, .val, and .append. I'd recommend you check out the jquery docs - they will give you good examples to expand your knowledge.
If you can use jQuery you can do it like this. It's not the full code it's just to give you the idea how to start with it.
jQuery('#add').click(function(){
var memberName = jQuery('#memberName').val();
var address = jQuery('#address').val();
var designation = jQuery('#designation').val();
// Do some saving process first, using ajax and sending it to a php page on the server
// then make that php return something to validate if it's succesfully added or something
// before you show it on table. You can use ajax like
jQuery.ajax({
type: 'POST',
url: 'you php file url.php',
data: { name: memeberName, addr: address, desig: designation },
dataType: 'json', // any return type you like
succes: function(response){ // if php return a success state
jQuery('#tableID tbody').append('<tr><td>' + memberName + '</td><td>' + address + '</td><td>' + designation + '</td></tr>');
},
error: function(response){ // if error in the middle of the call
alert('Cant Add');
}
});
});
Be sure to change the id to the id you have in your html elements.
This is only on the front end side. If you have other processes like saving the newly added into the DB then you have to process that first before showing it on the table.
First, let's make this:
into table, like this:
<table id='mytable'>
<tr>
<tr>
<td>Member Name</td><td><input type="text" name="member[]"></td>
</tr>
<tr>
<td>Address</td><td><textarea></td>
</tr>
<tr>
<td>Designation</td><td>
<select>
<option value="asd">Asd</option>
<option value="sda">Sda</option>
</select></td>
</tr>
</tr>
</table>
<div>
<input name='buttonadd' type='button' id='add_table' value='Add'>
</div>
And add this javascript in head or body:
$("#add_table").click(function(){
$('#mytable tr').last().after('<tr><td>Member Name</td><td><input type="text" name="member[]"></td></tr><tr><td>Address</td><td><textarea></td></tr><tr><td>Designation</td><td><select><option value="asd">Asd</option><option value="sda">Sda</option></select></td></tr>');
});
Inside after(''); don't use enter, just type the code sideways.
Hope this can help you.
Ty jean for your instant reply..i tried that code, but i couldn't get +ve result,coz of my knowledge with javascript,jquery, etc are very poor.now my code is like this
so i expect you will help me coz of im just stepping into javascript and jquery.
$(document).ready(function()
{
$("#ser_itm").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax
({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(data)
{
$("#tbl").html(data);
}
});
});
});

Categories