I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.
Related
I used ajax to create a live search connected to the database(site e-commerce). when there is a value in the input several suggestions are fetched in the screen . I want to take the id when the client click in a suggestion. The suggestions cant be clickable i dont know why!! here is my jquery code :
$('.clicked').click(function() {
console.log($("#input_value").val());
});
var x;
var value = $("#input_value").val();
$('.clicked').click(function() {
$.ajax({
type:'GET',
// // url: 'test.php?name=' + $("#testo").val(),
data: { name : value },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function()
{
window.location.href = 'un_produit.php?id=' + $("#input_value").val();
}
});
I tried to add the class to a div and it works when i click but it doesnt work with the suggestions of the live search .
Instead of using an AJAX request you could use JQUERY autocomplete.
This is an easy example on how this works, your URL source should return the data in this format:
[{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}]
I used this url as reference: https://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/
$(function() {
$("#autocomplete").autocomplete({
source: [{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}], // this can be an url as well
select: function( event, ui ) {
var label = ui.item.label;
if (label === "no results") {
// this prevents "no results" from being selected
event.preventDefault();
}
else {
/* do something with the selected result */
$("#autocomplete").val(ui.item.label);
event.preventDefault();
// or get the id
$("#autocomplete").val(ui.item.value);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<input type="text" id="autocomplete">
The problem is solved, I had to add the class="clicked" into the the child element of the suggestion div and not to the div itself. thank you
I'm using https://www.devbridge.com/sourcery/components/jquery-autocomplete/
I want to get results grouped by category when using ajax.
this only work when using: lookup: teams like this:
var teams = [
{ value: 'Chicago Blackhawks', data: { category: 'NHL', link: 'website.com' } },
{ value: 'Chicago Bulls', data: { category: 'NBA', link: 'site.com' } }
];
but i want to use it with "serviceUrl:" (ajax).
This is my PHP output:
$suggestions = "[{ value: 'Chicago Blackhawks', data: { category: 'NHL', link: 'website.com' } },
{ value: 'Chicago Bulls', data: { category: 'NBA', link: 'site.com' } }
]";
return json_encode($suggestions);
but it troughs and javascript error: "TypeError: e is undefined"
Thanks.
I am trying to get DataTables to read the column names from an AJAX data source but it seems that there must be something that I must be missing here.
I made a fiddle fiddle in which I can manually define the data and columns that are being used by the table.
The table is declared in the HTML and there is no no need to define the column names (<thead>..</thead>):
<table id="example" class="display table table-striped table-bordered"
cellspacing="0" width="100%"></table>
In the JS we manually define the data:
var data = [
[ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
[ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
Then manually define the column names or titles:
var columns = [
{ "title":"One" },
{ "title":"Two" },
{ "title":"Three" }
];
Then when we initialise the table we simply pass the previously declared information across for DataTables to use:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
data: data,
columns: columns
});
});
Which results in:
Now my question is how would I get this to work if the data is included in the AJAX server side response?
I have tried this in various ways and forms but nothing really seems to work out here and I am battling to find relative documentation on this.
For example if the server side processing sent back a JSON response which includes the column names at the end:
{
"data": [
{
"id": "1",
"One": "Row 1 - Field 1",
"Two": "Row 1 - Field 2",
"Three": "Row 1 - Field 3"
},
{
"id": "2",
"One": "Row 2 - Field 1",
"Two": "Row 2 - Field 2",
"Three": "Row 2 - Field 3"
}
],
"options": [],
"files": [],
"columns": [
{
"title": "One",
"data": "One"
},
{
"title": "Two",
"data": "Two"
},
{
"title": "Three",
"data": "Three"
}
]
}
Given this is the response, I tried to configure DataTables to use an AJAX data source for the row information as follows:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
"ajax": '/test.php',
columns: columns
});
});
But obviously columns is undefined here.
So I get the column data before hand:
function getPromise() {
var deferred = $.Deferred();
var dataUrl = document.location.origin+'/text.php';
$.getJSON(dataUrl, function(jsondata) {
setTimeout(function() {
deferred.resolve(jsondata);
}, 0);
}).fail(function( jqxhr, textStatus, error ) {
// ********* FAILED
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
return deferred.promise();
}
// Get the columns
getPromise().done(function(jsondata) {
columns = jsondata.columns;
console.log(columns);
});
And pass it to DataTables as above. But this time all I get when running the example is an error in the console saying TypeError: p is undefined.
So then how could I make use of the dynamically generated columns that are being returned within the server side response? Is there not a simpler way to achieve this?
EDIT:
DataTables Editor code for server side processing / to generate the JSON response mentioned above:
<?php
// DataTables PHP library
require_once '/path/to/DataTables.php';
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
$out = Editor::inst( $db, 'example' )
->fields(
Field::inst( 'id' )->set(false),
Field::inst( '`One`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Two`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Three`' )->validator( 'Validate::notEmpty' )
)
->process( $_POST )
->data();
// On 'read' remove the DT_RowId property so we can see fully how the `idSrc`
// option works on the client-side.
if ( Editor::action( $_POST ) === Editor::ACTION_READ ) {
for ( $i=0, $ien=count($out['data']) ; $i<$ien ; $i++ ) {
unset( $out['data'][$i]['DT_RowId'] );
}
}
// Create the thead data
if (count ($out) > 0) {
$columns = array();
foreach ($out['data'][0] as $column=>$relativeValue) {
// Add all but the id value
if ($column !== 'id') {
// Add this column name
$columns[] = array(
"title"=>$column,
"data"=>$column
);
}
}
}
// Add the the thead data to the ajax response
$out['columns'] = $columns;
// Send the data back to the client
echo json_encode( $out );
If you don't use the built in DataTables ajax it should be easy enough given the structure of your data:
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data: {
json: JSON.stringify(jsonData)
},
success: function(d) {
$('#example').DataTable({
dom: "Bfrtip",
data: d.data,
columns: d.columns
});
}
});
});
Like this JSFiddle, you're limited then to loading all the data at once but that shouldn't be a huge issue... unless you alter it get the columns from the initial ajax call and once the DataTable is initiated then add the built-in ajax - I've not tried this though...
You must create the table in html without header
<table id="tablaListadoExpediciones" class="table table-bordered table-striped dt-responsive"> </table>
Now you have to generate the columns array dynamically. In this way, the columns will always be generated automatically even if the AJAX response varies over time.
function PintarTablaDinamicamente(datos) {//object "datos" comes from AJAX response
//I take the keys of the object as columns of the table
var arrColumnas = Object.keys(datos[0])
////In case you wanted to hide a column
//var indiceColumna = arrColumnas.indexOf("nameOfTheColumnToHide")
//if (indiceColumna !== -1) {
// arrColumnas.splice(indiceColumna, 1)
//}
var columns = []
//columns must be in JSON format-->{data:'keyToSearchInJSON',title:'columnTitle'}
for (var i in arrColumnas) {
//if (arrColumnas[i] == "SELECCIONAR") { //if you want to add a checkbox in one colunm (for example column named SELECT
// columns.push({
// data: null,
// defaultContent: '',
// className: 'select-checkbox',
// orderable: false
// });
//} else {
columns.push({ data: arrColumnas[i], title: arrColumnas[i] });
//}
}
tabla = $('#tablaListadoExpediciones').DataTable({
dom: "Blfrtip",
data: datos,
//order: [[0, 'desc']],
"pageLength": 25,
"scrollX": true,
columns: columns
,
buttons: [
{
extend: 'copy'
},
{
extend: 'excel'
},
{
extend: 'print'
}
],
//select: {
// style: 'os',
// selector: 'td:first-child'
//}
});
}
Using ammaps' dataLoader, is there a way to pass post parameters to an external file?
I'm creating a report that contains a map, which when clicked, will provide a list of news articles from a MySQL table. I'm pulling in json data using dataLoader. However, I need to be able to pass a value (reportId) to the script that generates the json file.
here's my code:
var map = AmCharts.makeChart("mapdiv", {
type: "map",
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false//,
// tried this:
//"type" : "post",
//"data" : {"reportIdFromPost" : 1}
},
. . . //the rest of the map config
And this is maparticlesfeed.json.php:
<?php include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$POST['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"_comment" : "Here, instead of hard-coding the headlines, we will iterate through $articlesList",
"areas" : [
{ "title" : "Virginia",
"id" : "US-VA",
"selectable" : true,
"numArticles" : 4,
"articles" : [
{ "headline" : "This is the first headline",
"link" : "link url"
},
{ "headline" : "This is the second headline",
"link" : "link url"
},
{ "headline" : "This is the third headline",
"link" : "link url"
},
{ "headline" : "This is the fourth headline",
"link" : "link url"
}
]
},
{ "title" : "Tennessee",
"id" : "US-TN",
"selectable" : false,
"numArticles" : 6
}
]
}
I went the jQuery route to solve this. I'd still like to know if there's a way to do this with dataLoader, but here's a workaround in case anyone else has this issue in the future:
$.ajax({
dataType: "json",
url: "maparticlesfeed.json.php",
data: { reportIdFromPost: 1 },
type: "post",
success: function(data){
console.log(data); // for debugging
makeMap(data);
},
error: function(data) {
console.log('it did not work.');
console.log(data.responseText);
}
});
function makeMap(theData) {
var map = AmCharts.makeChart("mapdiv", {
type: "map",
/* DON'T NEED THIS ANYMORE:
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false
},*/
// replace instead with this:
"dataProvider" : theData,
// ... the rest of the map config ...
}
});
And, in maparticlesfeed.json.php:
<?php
include('database-connect.php');
$con=Database::connect();
if(!empty($_POST) && isset($_POST['reportIdFromPost']) ) {
$postedReportId= $_POST['reportIdFromPost'];
}
include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedReportId ");
$query->execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"areas" : [
// Code to json_encode the results from $articlesList
]
}
It may be that you're posting json data and then not decoding it when you're trying to use the value in your php script.
Try this at the top of maparticlesfeed.json.php:
<?php
include('database-connect.php');
$postedValues = json_decode($POST['reportIdFromPost'], true);
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedValues['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
You'll also need to uncomment the two lines in the map config:
"type" : "post",
"data" : {"reportIdFromPost" : 1}
Maybe you could add the parameters in the "url" parameter of the dataloader.
"url": "urlA.do?param1=" + $('.selector').val()
and then in some trigger (ie. button click) modify the url and reload
var url = "same URL with different parameters values";
chart.dataLoader.url = url;
chart.dataLoader.loadData()
I created a json with this structure
var data =
{
"people": [
{ "name" : "John", "id" : 1 },
{ "name" : "Marc", "id" : 2 }
]
}
Now here's how i send the data to the php
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: data,
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
Now when i tried to handle the data in the php it doesn't have any values, i know that the values are sending well, because i see the data sending with charles debugging proxy.
This is how i tried the get the value in the php
$array = json_decode(stripslashes($_POST['ventas']), true);
Am i sending the values corrected??
change
ventas: data,
to
ventas: ordenDeCompra,
Use:
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: ordenDeCompra,
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: ordenDeCompra, // shouldn't it be ordenDeCompra than data
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);