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()
Related
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.
I have trying to export showing result statement in below of datatable in Excel.
Here is my code:
table = $('#loadmaincat').DataTable({
"ajax" : {
"url" : "model/productListReport.php",
"type" : "POST",
"data" : {
"list" : "list",
"dataSrc": "data",
"type" : "all"
}
},
exportOptions: {
modifier: {
search: 'applied',
order: 'applied',
}
}
});
Can anybody help me?
Thanks in advance.
I have simple trouble in json
This is my Json code
{ "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" }
And this it the ajax code I am getting the data
function load_res()
{
$.ajax({
url: 'data.js',
type: 'POST',
dataType: 'json',
success: function(data) {
var div_data='';
$.each(data, function(index, element) {
div_data +="<div ><a href='"+data.name+"'>"+data[index].name+"</a></div>";
});
$('#9lessonsLinks').append(div_data);
}
});
}
HTML part
<a onclick="load_res()">Button</a>
<div id="9lessonsLinks"></div>
Above code it working well and data retrieve and display. But my problem is, when I add a new row to JSON file and I click on load_res() function, it will show old printed data with new data again, multiple printing with multiple clicking. I only want to get the newly added data as last line.
please help me to resolve this. appreciate your great ideas.
Thanks!
Easy fix: change .append to .html
$('#9lessonsLinks').html(div_data);
Empty the list before adding the items to it...
$('#9lessonsLinks').empty().append(div_data);
With javascript like this:
document.getElementById("9lessonsLinks").innerHTML = div_data;
I try to retrieve data to create a table with tablesorter like here :
http://mottie.github.io/tablesorter/docs/example-widget-build-table.html ( sections : "Setup - Object (javascript variable)" )
The HTML code ( a simple DIV ) :
<div id="list_user"></div>
Here is the JS script :
jQuery(document).ready(function() {
function get_users_list(){
return $.post(
"/mysql/function_users.php",
{
'type_request' : 'list_users'
},
"json"
);
};
get_users_list().done(function(data){
return data;
});
$(document).ajaxComplete(function( event,request, settings ) {
if (settings.url == "/mysql/function_users.php") {
var dataOject = request.responseText;
alert(dataOject);
$('#list_user').tablesorter({
debug:true,
theme : 'blue',
sortList: [[0,0]],
widthFixed: false,
widgets: ['zebra','filter'],
data : dataOject,
widgetOptions : {
build_objectRowKey : 'rows',
build_objectHeaderKey : 'headers',
filter_hideEmpty : false
}
});
};
});
});
When I check what is return from the php script "function_users.php", I get the following structure :
{
"headers":[
[
"Name",
"Surname",
"email",
"region",
"date creation",
"last modification",
{"text":"","class":"not_sort filter-false toclean"},
{"text":"","class":"not_sort filter-false toclean"},
{"text":"","class":"not_sort filter-false toclean"}
]
],
"rows":[
["toto","toto","toto#toto.com","latam","1410142447","1410142537"],
["tata","tata","tata#tata.com","emea","1410142447","1410142537"],
["titi","titi","titi#titi.com","asia","1410142447","1410142537"],
["tutu","tutu","tutu#tuttu.com","latam","1410142447","1410142537"]
]
}
If you have any lead please. Thank you
I was intrigued by your question, and I am eager to make use of this tablesorter tool in the future. I have created a couple of possible approaches to the problem.
See http://jsfiddle.net/terrywbrady/4my61h6d/9/
The first approach (commented out) requests the data from a GIST.
var gisturl = "https://gist.githubusercontent.com/terrywbrady/eb75d9097e633682539e/raw/798bd947404dbcc388fc8954d5d557dec13d0ef7/result.json";
function get_users_list(){
$('#list_user').tablesorter({
theme: 'blue',
widgets: ['zebra'],
widgetOptions: {
build_type : 'json',
build_source : {
url: gisturl,
dataType: 'json'
}
}
});
};
The second approach uses the jsfiddle echo service to return the result.
var DATA = {
"headers":[
[
"Name",
"Surname",
"email",
"region",
"date creation",
"last modification",
{"text":"","class":"not_sort filter-false toclean"},
{"text":"","class":"not_sort filter-false toclean"},
{"text":"","class":"not_sort filter-false toclean"}
]
],
"rows":[
["toto","toto","toto#toto.com","latam","1410142447","1410142537"],
["tata","tata","tata#tata.com","emea","1410142447","1410142537"],
["titi","titi","titi#titi.com","asia","1410142447","1410142537"],
["tutu","tutu","tutu#tuttu.com","latam","1410142447","1410142537"]
]
};
var JDATA = {
json : JSON.stringify(DATA)
}
function get_users_list2(){
$('#list_user').tablesorter({
theme: 'blue',
widgets: ['zebra'],
widgetOptions: {
build_type : 'json',
build_source : {
url: "/echo/json/",
data: JDATA,
contentType: "application/json",
type: "POST",
dataType: 'json'
}
}
});
};
For simplicity, I removed a few of your display options from the table configuration.
In the model:
public function groups($getGroupId) {
$cols = array('group_id','name');
$sql = $this->select ()
->from ( $this->_name, $cols )
->where ( 'parent_id=?', $getGroupId );
$groupDetails = $this->fetchAll ( $sql );
//$childGroupName = $groupDetails['name'];
return $groupDetails->toArray();
}
groupDetails.php page:
$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
When printing the jsonResonse (print_r($jsonResponse)). I'm getting response like this
[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]
how to generate a jstree using json response
By jstree demo i written a code like this for getting tree structure but i am unable to get a tree.
Please help me
jQuery(document).ready(function(){
//alert("get tree view");
jQuery("#treeView").jstree({
// This example uses JSON as it is most common
"json_data" : {
// This tree is ajax enabled - as this is most common, and maybe a bit more complex
// All the options are almost the same as jQuery's AJAX (read the docs)
"ajax" : {
// the URL to fetch the data
"url" : "groupDetails.php",
// the `data` function is executed in the instance's scope
// the parameter is the node being loaded
// (may be -1, 0, or undefined when loading the root nodes)
"data" : function (n) {
// the result is fed to the AJAX request `data` option
return {
"operation" : "get_children",
"id" : n.attr ? n.attr("id").replace("node_","") : 1
};
}
}
},
"ui" : {
"select_limit" : 1
},
"themes" : {
"theme" : "default",
"dots" : true,
"icons" : true
},
"types" : {
// I set both options to -2, as I do not need depth and children count checking
// Those two checks may slow jstree a lot, so use only when needed
"max_depth" : -2,
"max_children" : -2,
// I want only `drive` nodes to be root nodes
// This will prevent moving or creating any other type as a root node
"valid_children" : [ "drive" ],
"types" : {
// The default type
"default" : {
// I want this type to have no children (so only leaf nodes)
// In my case - those are files
"valid_children" : "none",
// If we specify an icon for the default type it WILL OVERRIDE the theme icons
"icon" : {
"image" : "./file.png"
}
},
// The `folder` type
"folder" : {
// can have files and other folders inside of it, but NOT `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./folder.png"
}
},
// The `drive` nodes
"drive" : {
// can have files and folders inside, but NOT other `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./root.png"
},
// those prevent the functions with the same name to be used on `drive` nodes
// internally the `before` event is used
"start_drag" : false,
"move_node" : false,
"delete_node" : false,
"remove" : false
}
}
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu" ]
})
});
Your json should look like this:
[
{
"data" : {
"icon" : <optional>,
"title" : <node name>
},
"attr" : {
"rel" : <the type you defined in the js (maybe "group")>,
"title" : <node title>,
"id" : <the node's id / group id>
},
"state" : "closed"
}
]
You can put anything you want at the "attr" hash, basically it can hold other information you might need.