I am trying to display database into an html page. The data appears in my console but I cant figure out how to display it in an html table. I am not sure the function I need to add into console.log (data) for it to display onto to the page. This is what I have so far:
<button class="btn btn-primary" id="btn">Get Code</button>
<table class="table table-bordered">
<thread>
<tr>
<th>ID</th>
<th>City</th>
<th>Country</th>
<th>Rating</th>
</tr>
</thread>
<tbody id ="tdata">
</tbody>
</table>
<script>
$(function () {
$.getJSON("php.php", {tableName:"travel"}, function(data){
if (data["code"] == "error"){
console.log(data["message"]);
}
else{
console.log(data);
}
console.log("returned hh");
});
});
console.log("returned");
</script>
</body>
</html>
Its no json structure example so you will have to replace "value.a" with the correct json values names.
After json is loaded:
$.each(data,function(i,value){
$('.table').append('<tr><td>value.a</td><td>value.b</td><td>value.c</td><td>value.d</td></tr>')
})
Hope this helps
Related
I'm new to this forum and I would like to tell you my problem already.
I need a multiple search field, when I go to enter the first letters I get the results through an AJAX call made on a file in php, the problem is that in the second input field that I have cloned the AJAX scan does not work and I do not suggestions come out.
So how can I go about making multiple search fields work?
I am attaching the code to make you understand better. Thank you all.
<div class="cont">
<input type="text" class="form-control search" id="search">
<button id="add" onClick="add()">+</button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
function add(){
$("#search").clone().val("").attr("id", "search").appendTo(".cont");
}
$("#search").keyup(function(){
$.ajax({
type:'POST',
url:'search.php',
data:{
name:$(this).val(),
},
success:function(data){
$(".#output").html(data);
return data;
}
});
});
I did as you said, but the ajax call in the second input doesn't work, should I call the ajax function to make it work on the new input? How could I do?
Thanks a lot everyone, I solved it
You need to be identifying a class search .. You are calling an ID which is supposed to be unique
When cloning remove the ID attribute and use addClass('search')
$("#search").clone().val("").addClass("search").appendTo(".cont");
Then change your selector from: $("#search")
To $(".search")
in effect calling any element with the class search on keyup
UPDATE
as #ADyson mentioned in the comment .. You will need to bind the keyup action .. The easiest way to do this is using on() ( from the deprecated .live() ). IE:
$(document).on('keyup', '.search', function(){
FULL SNIPPET:
function add(){
$("#search").clone().val("").addClass("search").appendTo(".cont");
}
$(document).on('keyup', '.search', function(){
alert('Call AJAX');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cont">
<input type="text" class="form-control search" id="search">
<button id="add" onClick="add()">+</button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
Check out the API Documentation for a full list of events handled through .on()
I using Jquery to clear the table tbody and reinsert in via ajax call. after the data is showed, but the sorting function is not working properly. here is my codes..
<table class="table table-bordered table-striped table-condensed flip-content table-hover" style="table-layout:fixed;" id="datatable1">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="agtBody">
<?php
foreach($results as $result) :
?>
<tr>
<?php if(isset($game_name['gpname'])){?>
<td><?=$game_name['gpname']?></td>
<?php }else{ ?>
<td><?=$result['gpid']?></td>
<?php } ?>
<td style="text-align:right;"><?=Helper::money($result['betAmt'])?></td>
<td style="text-align:right;"><?=Helper::money($result['payout'])?></td>
<td style="text-align:right;"><?=Helper::money($result['winLoss'])?></td>
<td style="text-align:right;"><?=Helper::money($result['validbetamount'])?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot id ="agtFoot">
<tr style="background-color:#FFEEDD;">
<td>Total</td>
<td style="text-align:right;"><?=Helper::money($totalbetAmt)?></td>
<td style="text-align:right;"><?=Helper::money($totalpayout)?></td>
<td style="text-align:right;"><?=Helper::money($totalwinLoss)?></td>
<td style="text-align:right;"><?=Helper::money($totalvalidbetamount)?></td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
function search_agtdetail(agentcode) {
if($("#agt_StartTime").val() == "" || $("#agt_EndTime").val() == "") {
alert("<?php echo 'Not Valid' ?>");
} else {
$("#agtBody").empty();
$("#agtFoot").empty();
$.ajax({
type: "post",
url: "/report/agentBoxAjax",
dataType: "json",
data: {
start_date: $("#agt_StartTime").val(),
end_date: $("#agt_EndTime").val(),
agent_code : agentcode,
},
success: function (data) {
$('#datatable1').dataTable().fnDestroy();
$('#agtBody').html(data.html);
$('#agtFoot').html(data.html_foot);
$('#datatable1').css('width', '');
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
}
});
}
}
$(document).ready(function(){
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
});
</script>
Can someone help me? The sorting is not working properly..
Its look like using the old data for sorting it.
i had less experience on jquery, someone please help. Thank you so much.
Extending on Bhushan Kawadkar comment you need to use the API method for this.Also you should be using the ajax methods for your datatable.
For example, lets say that i get the server side data from a script called data.php, i would just call it like this:
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
"ajax": {
"url": "data.php",
"type": "GET"
}
});
the post.php needs to return the data in json format like this (using car as example):
{
"data":[
[
"Ford",
"Fiesta",
"2015"
],
]
}
in your success section in the ajax call instead of destroying the table just use:
$('#datatable1').ajax.reload()
Here's a snippet just in case.
$(document).ready(function() {
var table = $('#example').DataTable({
"ajax": 'https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/arrays.txt',
});
$("#reload_table").on("click",function(){
console.log("reloading data");
table.ajax.reload();
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<html>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Profession</th>
<th>City</th>
<th>Date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</body>
<input id="reload_table" type="button" value="RELOAD TABLE">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
</html>
I created a table with my PHP and database and added a delete button on the right of each of my element in my first column and I want this button to delete the row in my database but I don't know how to link my button to a PHP action
<table border="2" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col"><h6>Nom de l'Etape</h6></th>
<th scope="col"><h6>Description de l'Etape </h6> </th>
</tr>
</thead>
<?php
$req='SELECT * FROM Etape';
$resultat=$dbh->query($req);
while ($ligne=$resultat->fetch()) {
echo "<tr> <td>". $ligne[0]."<button type=\"button\" onclick=\"alert('Hello world!')\">delete</button></td><td>".$ligne[1]."</td> </tr>";
}
?>
</table>
The easiest way is to use ajax:
<?php
// Check if is background ajax query or user just enter page
// Is background ajax query, run PHP code
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'):
// RUN PHP CODE IN BACKGROUND (IN YOUR CASE: DELETE ROW FROM DB)
else:
// Is not ajax query - show HTML page
?>
<table border="2" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col"><h6>Nom de l'Etape</h6></th>
<th scope="col"><h6>Description de l'Etape </h6> </th>
</tr>
</thead>
<?php
// Your PHP function to get button from database
$req='SELECT * FROM Etape';
$resultat=$dbh->query($req);
while ($ligne=$resultat->fetch()) {
echo '<tr> <td>'. $ligne[0].'<button type="button" value="<?php echo $ligne[0]; ?>">delete</button></td><td>'.$ligne[1].'</td></tr>';
}
?>
</table>
<!-- Load jQuery -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
// Button click
$(document).on('click','button',function(e) {
// Get button value
var my_id = $(this).val();
// Prepare ajax query
$.ajax({
type: "POST",
dataType:"json",
// Set url to file itself
url: window.location.href,
// set data
data: "id=" + my_id,
beforeSend: function (data) {
alert('Sending');
},
success: function (data)
{
alert('Success');
},
error: function (data)
{
alert('Error');
}
});
});
</script>
<?php endif; ?>
Update, seems it is also happening when i go onto the next page (fullscreen this time).
I'm hoping someone could possible help me as this has been driving me crazy. I have a table full off orders which each row has a button. This button when submitted will show an alert.
I am using data-tables (Responsive), and when the table is all on the screen, the button works as intended. However, when the screen is resized and the button goes within the + icon to expand the row. The button is not running the jquery and is submitting the page.
I have no idea how to fix this and was wondering if there is a workaround. Here is a sample of the code if it helps.
<table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<form id="<?php echo $order['OrderNumber']; ?>">
<input type="submit" value="Submit">
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
At the bottom of the page:
<?php foreach ($orders as $order): ?>
<script>
$('#<?php echo $order['OrderNumber']; ?>').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<?php endforeach; ?>
Any help would be appreciated! I have no idea why it isn't working when the table is resized.
Use a delegated event handler instead :
$('#datatable-buttons').on('submit', '#<?php echo $order['OrderNumber'];?>', function() {
alert('Form submitted!');
return false;
});
Your event handler does not work because the form not exists in dom at the time of declaration.
But all those dedicated #id based event handlers is completely unnecessary. A single (delegated) handler is sufficient :
$('#datatable-buttons').on('submit', 'form', function () {
alert('Form ' + $(this).attr('id') + ' submitted!');
return false;
});
Hey mate you could try something like this for the alert
<table id="datatable-buttons" class="table table-striped table- bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<button type="button" class="btnPress" id="<?php echo $order['OrderNumber']; ?>">Submit</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Bottom
<script>
$('.btnPress').on('click', function () {
alert('Form submitted!');
alert(this.id);
});
</script>
I'm having trouble mounting a table using .load () jquery.
My table is as follows.
<table id="table_test">
<thead>
<tr>
<th> COLUNA 1 </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My file assembles the following output.
<tr>
<td>
<span> Value 2</span>
</td>
</tr>
I'm using the following function.
<script type="text/javascript">
$(document).ready (function () {
$('# table_test'). load ('modules/a/processa.php? opt = 2');
});
</ script>
However it is unable to mount the rows in the table.
http://jsfiddle.net/marcoscarraro/7NsNu/
Any suggestions?
I think your problem is with $.
This should work $('#table_test').load('modules/a/processa.php?opt=2');.
There is quite a few typos/syntax errors in your question. You can try this below. I'm not sure what your data returns, but I hope it does return text properly. Let me know if this works.
HTML Structure:
<table id="table_test">
<thead>
<tr>
<th> COLUNA 1 </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS Code:
$(document).ready(function () {
$('#table_test tbody').load("modules/a/processa.php?opt=2",
function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
});
});
JS Fiddle:
http://jsfiddle.net/QztST/3/