I have table like this
<table>
<tr>
<th>User</th>
<th>IP</th>
<th>Action</th>
</tr>
<tr>
<td>Jack</td>
<td>192.168.0.1</td>
<td><button id="check" name="192.168.0.1">Check</button></td>
</tr>
<tr>
<td>Eve</td>
<td>192.168.0.2</td>
<td><button id="check" name="192.168.0.2">Check</button></td>
</tr>
<tr>
<td>Smith</td>
<td>192.168.0.3</td>
<td><button id="check" name="192.168.0.3">Check</button></td>
</tr>
</table>
How to implementation to send POST data IP with AJAX?
I have tried with this code but does not work..
<script>
$('#check').click(function() {
var getIP = $('#check').name();
var dataIP = 'sendIP=' + getIP;
$.ajax({
url: 'url.php',
type: 'POST',
data: dataIP;
success: function () {
alert("Success");
}
});
});
</script>
[UPDATE]
This is Full code for my project.
<script>
$(document).ready(function() {
$('#reportrange span').on('DOMSubtreeModified', function () {
var dariRange = $(this).html();
var SplitRange = dariRange.split("~");
$('#datatable-keytable').DataTable( {
"destroy": true,
"processing": true,
"keys": true,
"order": [[ 6, "desc" ]],
"ajax": {
url: "view.php",
type : 'GET',
data : {
datedari : SplitRange[0].trim(),
datesampai : SplitRange[1].trim()
}
},
"columnDefs": [
{ "width": "5%", "targets": 0 },
],
"columns": [
{ "data": "click_username" },
{ "data": "click_cid" },
{ "data": "click_offer" },
{ "data": "click_ip" },
{ "data": "click_isp" },
{ "data": "click_posttime" },
{ "data": "click_ip",
"render": function (click_ip,data,row) {
var clickid = data.click_cid;
return ('<center><button class="check" id="'+click_ip+'" name="'+clickid+'">Check</button></center>'); //This for Button check
}
},
],
} );
} );
} );
</script>
<script type="text/javascript">
$(document).on('click', '.check',function() {
var dataID = 'sendCID=' + this.name;
var dataIP = this.id;
$.ajax({
url: 'send_data.php',
type: 'POST',
data: dataID;
success: function () {
window.open('http://whatismyipaddress.com/ip/'+dataIP);
}
});
});
</script>
I want to POST var dataID to send_data.php and then if success open new tab to http://whatismyipaddress.com/ip/'+dataIP but does not work with this code,
I hope someone help me to resolve this, thank you
You can't repeat ID's in a page , they are unique by definition, so will need to change to a class
Within an event handler this is the element the event occurred on so in your case this.name would be value needed
// use class selector
$('.check').click(function() {
var dataIP = 'sendIP=' + this.name;
$.ajax({
url: 'url.php',
type: 'POST',
data: dataIP;
success: function () {
alert("Success");
}
});
});
Related
I was able to get result from MVC controller using ajax, it returns me json data. Now i need to put it to html table in view, how can i do it?
function getClassificators(){
$.ajax({
url:"/Employee/GetClassificationLevels",
type:"GET",
success: function(result){
if(Array.isArray(result) && result.length > 0){
var eachRes = result.map(function(classificator, i){
return {
levels: classificator.Level,
name: classificator.Name,
score: classificator.Score,
sublevel_info : classificator.EmpEvaluation_SubLevelView.map(function(sublevelinfo, i){
return {sublevel_name: sublevelinfo.Name};
})
};
});
}
},
error: function(err){
console.log(err);
}
});
}
console shows:
[{
{levels:0, name: "level4", score:3, sublevel_info:{sublevel_name:"sublevel4"}}
}]
Expected output is html table.
Take a look at DataTables.js.
It has ajax support out of the box, and it's raelly easy to use.
Here an example
var dtTickets = $("#dtTickets");
datatable = $(dtTickets).DataTable(
{
"order": [[0, "desc"]],
"createdRow": function (row, data, index) {
$(row).data("userId", #id);
$(row).data("ticketId", data.id);
$(row).addClass("selectable");
},
"ajax": {
"url": "#Url.Action("TicketsAjax", "User")",
"type": "POST",
"data": function (d) {
// Set here variables for you AJAX POST message.
d.id = #id;
d.companyId = #summary.CompanyId;
d.filtersJson = searchParms.filtersToJson();
console.log(d);
},
"dataSrc": function (response) {
// You can process the response here if needed.
return response;
}
},
"columns": [
{
"className": "text-right"
"data": "id"
},
{ "data": "createDate" },
{ "data": "createUserName" },
{ "data": "title" },
{ "data": "status" },
{ "data": "actionDate" },
],
}
);
Make sure that your table is structured like this
<table>
<thead>
<tr>
<th>test</th>
<th>somecolumn</th>
</tr>
</thead>
-> I have a answer but in pure JS, not in jQuery – Mister Jojo
-> can u share it please? – Valery
it looks like that
suposed HTML:
<table id="my-table">
<thead>
<td>Level</td><td>Name</td><td>Score</td>
</thead>
<tbody></tbody>
</table>
JS:
const Url = '/Employee/GetClassificationLevels'
, myTableBody = document.querySelector('#my-table tbody')
fetch(Url)
.then(resp=> resp.json())
.then(data=>{
// ...
data.forEach(classificator=>{
let eRow = myTableBody.insertRow(-1)
, nCol = 0
eRow.insertCell(nCol++).textContent = classificator.Level
eRow.insertCell(nCol++).textContent = classificator.Name
eRow.insertCell(nCol++).textContent = classificator.Score
//...
})
})
im trying to import a json url to html in a table. The problem is when i get the data i get 25 rows i get this on the web console: Object { data: Array[25], paging: Object } I also have the following code which is designed for only one row i guess .And i understand i have Loop over each object, appending a table row with the relevant data of each iteration. The problem is i don´t how to do it, i´m not an expert . Thank you for your help!
This is the data i get on the json url :
{
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
And this my code
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>created time</td>
<td>permalink url</td>
<td>id</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=created_time,permalink_url,id,shares& access_token=mytoken",
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
error: function (){
console.log("Error");
}
});
});
});
</script>
</body>
</html>
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
should be
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td><td>'+d.id+'</td>'+s+'</tr>');
});
},
function create(t,attr,parent_node,innerdata){
var dom = document.createElement(t)
for(key in attr){
dom.setAttribute(key,attr[key])
}
dom.innerHTML = innerdata;
parent_node.appendChild(dom)
return dom;
}
window.onload = function () {
var d = {
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
]
}
var tb= document.getElementById('inputTable')
f = {"created_time":1,"permalink_url":1,"id":1,"shares":1}
d['data'].forEach(function(val){
tr_dom = create('tr',{},tb,'')
Object.keys(f).forEach(function(tr){
if(tr in val){
if('shares' == tr)
td_dom = create('td',{},tr_dom,val[tr]['count'])
else
td_dom = create('td',{},tr_dom,val[tr])
}else
td_dom = create('td',{},tr_dom,'')
})
})
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table border='1'>
<thead>
<th>Create Time</th>
<th>permalink_url</th>
<th>id</th>
<th>Share</th>
</thead>
<tbody id="inputTable">
</tbody>
</table>
</body>
</html>
I'm using datatable plugin and want to refresh table by ajax. I've read here to make my ajax return shows in table but it doesn't work. Here is my html code:
<button type="button" onclick="rld()">test</button>
<table id="sample_1">
<thead>
<tr>
<th> 1 </th>
<th> 2 </th>
<th> 3 </th>
</tr>
</thead>
</table>
My java function:
function rld(){
var table = $('#sample_1').DataTable( {
ajax: '<?php echo site_url('admin/test'); ?>',
deferRender: true,
columns: [
{ data: '1' },
{ data: '2' },
{ data: '3' }
],
rowId: 'extn',
select: true,
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
}
I can't get what the problem is. there in no alerts but in the console i get TypeError: f is undefined
and TypeError: c is undefined
Which i don't know why cause my json return is correct (checked in [JSONLint][3]).
Thanks in advance.
Thank you all for your attention :)
Found that i didn't call where the data goes when returned as json and the json field's name isn't equal to the column data field name. So make this adjustment:
function reload_table(){
var table = $('#sample_1').DataTable();
table.destroy();
var table = $('#sample_1').DataTable( {
"processing": true,
"dataType": 'json',
ajax: '<?php echo site_url('admin/relaod_table'); ?>',
deferRender: true,
columns: [
{ data: 'user_firstname' },
{ data: 'user_lastname' },
{ data: 'user_status' },
{ data: 'user_created_date' },
],
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
}
I have implemented responsive jquery datatable in one of my project.
At the end of each row there is edit/detail link.
If i click edit/detail link:
1)Large Screen - It picks the UseID(Which is first Column in a row), so that i can edit that User.
2)Small Screen - Because of responsiveness the row will splitted as show below. It doesnot pick that User ID.
Large Screen Edit/Detail is Last row
Large Screen after clicking Edit link
Small Screen See Edit/detail link which is splitted
I am not able to get the UserID alert when i click edit link whenever the screen is small.
My Code.
<table id="myExample" class="display responsive nowrap">
<thead>
<tr>
<th>User Name</th>
<th>First Name</th>
<th>LastName</th>
<th>Street</th>
<th>City</th>
<th>Zip</th>
<th>State</th>
<th>Email</th>
<th>Edit</th>
</tr>
</thead>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/dataTables.responsive.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var table = $('#myExample').DataTable({
"ajax": {
"url": "/Admin/LoadData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Usr_Nm", "autowidth": true },
{ "data": "FirstName", "autowidth": true },
{ "data": "LastName", "autowidth": true },
{ "data": "Street", "autowidth": true },
{ "data": "City", "autowidth": true },
{ "data": "Zip", "autowidth": true },
{ "data": "Sate", "autowidth": true },
{
data: null,
defaultContent: 'Edit/Detail',
orderable: false
}
]
});
$('#myExample').on('click', 'a.Edit', function (e) {
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
$.ajax({
url: '/Admin/UserEdit',
type: "GET",
data: { 'id': UserId },
dataType: "json",
success: function (response) {
// alert('1:');
// alert(response);
if (response.isRedirect) {
// alert('1');
window.location.href = response.redirectUrl;
//window.location.href = response.redirectUrl;
}
// }
},
error: function (response) {
alert("Some error");
}
});
});
})
</script>
To get UserID:
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
Inspect Element in Large Screen
Inspect Element in Small Screen:
You must go through the dataTables API in order to get data for columns not present in the DOM (removed due to responsiveness).
You can get the all values for a certain row by table.row(<tr-node>).data() :
$('#myExample').on('click', 'a.Edit', function (e) {
var data = table.row($(this).closest('tr')).data()
//if it is "User Name" / first column you are after
var userId = data[0]
...
})
First I have HTML:
<div class="showTable" style="display: none;">
<table id="example" class="table table-responsitive" cellspacing="0" width="100%" style="margin-top:30px;">
<thead>
<tr>
<th>ID</th>
<th>Broj računa</th>
<th>Kupac</th>
<th>Datum izdavanja</th>
<th>Rok za plaćanje</th>
<th>Status</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="showInfo" style="display: none">
</div>
After that I write JS:
$(document).ready(function() {
drawVisualization();
});
function drawVisualization() {
console.log('proba');
$.ajax({
url: "getracuni.php",
type: "POST",
async: true,
dataType: "html",
success: function(json) {
console.log(json);
if (!json.data){
json.data = [];
$('.showInfo').show();
} else {
var podaci = json.data;
$('.showTable').show();
showTable(podaci);
}
},
error: function(data) {
console.log(data);
}
});
};
so here I try to make this:
1. IF data from ajax is not empty then to create datatable with function showTable(podaci);
2. IF data from ajax is empty then just want to show div class 'showInfo'.
My showTable(podaci) function is:
function showTable(podaci) {
$('#example').dataTable({
data: podaci.data,
paging: false,
"dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">',
bfilter: false,
"oLanguage": {
"sInfo": 'Ukupno _END_ računa.',
"sInfoEmpty": 'Nema podataka o računima',
"sEmptyTable": "Nemate račune, dodajte klikom na dugme ispod.",
},
// end ,
"columns": [{
"data": "ID"
}, {
"data": "br"
},
{
"data": "kupac"
},
{
"data": "datum"
},
{
"data": "rok"
},
{
"data": "status"
},
{
"data": "akcija"
}
],
"columnDefs": [
{
"targets": 6,
"data": "akcija",
"render": function(data, type, full, meta) {
// return data;
return '<div style="float:right;"><div class="btn-group">Izmeni <span class="caret"></span><ul class="dropdown-menu"><li>Izmeni</li><li>Pošalji</li><li>Opomeni</li><li>Plaćeno</li><li>Stoniraj</li><li>Kopiraj</li><li>Obriši</li></ul></div> <i data-toggle="modal" data-target="#delete" class="fa fa-times"></i></div>';
}
},
{
"targets": 0,
"visible":false
}
]
});
}
Also I get data from ajax in this JSON format:
{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}
I think that I write everything fine but when I try to run this code I just get blank screen. SO anything wont to show there...
Change your condition
if (!json.data) to if (json.data!=null)