I am programming in php,
I want to take an array I have (which is extracted from mysql result set), convert it to JSON and then use it in dojox.grid.DataGrid.
I got an idea from this link:
I used the following on the array (in a file called getJSON.php)
echo $ajax = "{identifier: 'db_id', 'items':".json_encode($array)."}";
Then I try doing this (in my main page):
var store = new dojo.data.ItemFileWriteStore({ url: 'getJSON.php' });
Everything else is exactly as the Dojo documentation specifies.
The grid shows up, but doesn't load the data and instead writes Sorry, an error occurred
Does anyone know the reason? Hopefully I gave you enough to go on.
i don't use ItemFileWriteStore for that ! They changed a lot since Dojo 1.6 , so maybe you looked at something not up to date.
Try this code:
// Load the neccessary components (This is dojo with AMD ) !
require(["dojo/aspect",'dojo/_base/lang', 'dojox/grid/DataGrid'
,'dojo/dom' , 'dojo/store/JsonRest','dojo/data/ObjectStore',
'dojo/domReady!'],
function(aspect,lang, DataGrid, dom,JsonRest,ObjectStore){ // Map components to vars...
var store = new JsonRest({
target: "getJSON.php" // Use a URL that you can open up in a browser.
});
/*layout for the grid, you will have to adapt this to your columns !!!*/
var layout = [[
{'name': 'Filename', 'field': 'documentName', 'width': '300px'},
{'name': 'Size', 'field': 'fileSize', 'width': '100px'},
{'name': 'Id', 'field': 'id', 'width': '200px'}
]];
dataStore=ObjectStore({objectStore: store}); // Transform to Objectstore !
/*Now we create a new grid*/
var grid = new DataGrid({
id: 'grid',
store:dataStore, // Connect the store
autoWidth:false,
structure: layout, // Connect the layout
rowSelector: '0px'});
grid.placeAt("yourTargetDivId"); // Has to be an existing DOM Element with id !
grid.startup(); // START IT !
});
Please try this code by echoing something simple like this first:
echo '[{"id":"1","fileSize":"100kb","documentName":"Lucian !"},
{"id":"2","fileSize":"900kb","documentName":"Pew Pew !"}]';
And after that with your own JSON...
Related
I'm a noobie of PHP and AngularJS.
I have a webpage that communicates to a web serves with PHP - AJAX. It queries a database, and echoes the result (a big table) in an html placeholder.
I want to print the content of that table in a downloadable PDF file when the user pushes a button.
I want to use PDFmake and now it works well for test purpose, but how can I pass that content of my table to AngularJS' app?
Maybe should I pass table's id to docDefinition content? In that case I don't know how to do that.
Note: Maybe my approach is uncorrent cause I have to relegate PHP to different tasks and use AngularJS to query the Database, but for now I want to mantain this approach.
Thank You
I suggest you use an angular service (as explained in the docs
)
var bigTableApp = angular.module('bigTable',[])
bigTableApp.factory('BigTableSrv', ['$resource',
function($resource) {
return $resource('URL_to_php_backend', {}, {
query: {
method: 'GET',
params: {param1: 'value 1', param2: 'value 2'},
isArray: true
}
});
}
]);
Then, you can use it in a controller to fetch data from the back-end and build a table structure in PDFmake's table format:
bigTableApp.controller('BigTableController', ['$scope', 'BigTableSrv',
function BigTableController($scope, BigTableSrv) {
$scope.bigTable = BigTableSrv.query();
$scope.pdfMakeTable = {
// array of column widths, expand as needed
widths: [10, *, 130],
body: []
};
$scope.printTable = function() {
pdfMakeTable.body = $scope.bigTable.map(el => {
// process each element of your "big table" to one line of the
// pdfMake table, size of return array must match that of the widths array
return [el.prop1, el.prop2, el.prop3]
});
// create the pdfMake document
let docDefinition = {
content: [ pdfMakeTable ]
}
// print your pdf
pdfMake.creatPdf(docDefinition).print()
}
}
]);
Please, explain to me how to run snippet CookieList with ajax?
I tried next:
1. Created snippet ajaxCookieList:
<?php
if (isset($_POST["action"])) {
$values = $modx->runSnippet('addToCookieLIst',array(
'value' => $_POST['action']
));
$output = $modx->runSnippet('pdoResources',[
'parents' => 6,
'resources' => $values,
'tpl' => 'popup.favorites.item',
'includeTVs' => 'header.bgImage,franchise.logo,franchise.price,title,subtitle',
'prepareTVs' => '1',
'hideContainers' => '1'
]);
return $output;
}
Then i created chunk with this code:
<script>
jQuery(function($){
$('a.franchise-pin, a.franchise-favorite-add').click(function(e){
var value = $(this).data('value');
$.post(document.location.href, {action: value}, function(data) {
$('#favorites').html(data);
$('#favorites').modal('show');
});
e.preventDefault();
});
});
</script>
But response is all page..
What is wrong?
What I usually do in such cases:
I place a snippet call ([[!ajaxCookieList]]) on a service page
accessible via URL like /page-with-snippet/
In JS (ajax) I use that URL to which I send parameters
The snippet has to get the parameters I send. So, I really call it like this: [[!ajaxCookieList? &action=[[!#POST.action]]]]
Access to parameters in snippets is possible like this: $option = $modx->getOption('action', $scriptProperties, 'default_value', true);
I do my stuff in the snippet
But in your case, I think, everything can be simpler. You use one of the pdoTools snippets and if I am not mistaken, you can just place pdoResources snippet call on a page (/page-with-snippet/) like this:
[[pdoResources?
&parents=`6`
&resources=`[[!addToCookieLIst? &value=`[[!#POST.action]]` ]]` // your snippet should return comma-separated list of resources` ids that you pass then to pdoResources
&tpl=`popup.favorites.item`
&includeTVs=`header.bgImage,franchise.logo,franchise.price,title,subtitle`
&prepareTVs=`1`
&hideContainers=`1`
]]
and now you can send parameters to this page (/page-with-snippet/) via AJAX and get the results if there are any. I hope I didn't mess anything - you had better check it again, but you get the idea at least :) BTW, check this article on modx.com that teaches how to write a good snippet.
Also another minor issue: as it has been pointed out here, the use of window.location is preferable to document.location.
Here is another solution I did. I used pdoResources. Hope that you will understand my code and customize it for yourselves.
Create snippet ajaxCookieList
Paste JS-code in your custom.js file
Simple markup for resources. Insert it in the chunk:
Add to wish list
Remove from wish list
Thas all:)
I am using Jquery-option-tree plugin on a standalone website not based on Wordpress as in example 7 on the demo page, except that I am not passing a .txt file but a PHP page is generating the array of < options > to be passed to the plugin.
http://kotowicz.net/jquery-option-tree/demo/demo.html
This perfectly works: so let's say that the user wants to select a category for a new product, the plugin suits the purpose generating a nice: " Food -> fruit -> apples " upon user clicks. (see demo page ex. 7)
What instead if a product already exists with its categories assigned? I want to show it to the user when he edit that product, preloading the tree.
I have the ids path coming from database, so it would just be a matter of having the plugin to run without the user interact, using the value I pass. I saw this question: jQuery simulate click event on select option
and tried to simulate user' click with this (and other) methods with no luck.
$('#select')
.val(value)
.trigger('click');
Here the call to the function:
$(function() {
var options = {
empty_value: '',
set_value_on: 'each',
indexed: true, // the data in tree is indexed by values (ids), not by labels
on_each_change: '/js/jquery-option-tree/get-subtree.php', // this file will be called with 'id' parameter, JSON data must be returned
choose: function(level) {
return 'Choose level ' + level;
},
loading_image: '/js/jquery-option-tree/ajax-load.gif',
show_multiple: 10, // if true - will set the size to show all options
choose: ''
};
$.getJSON('/js/jquery-option-tree/get-subtree.php', function(tree) { // initialize the tree by loading the file first
$('input[name=parent_category_id]').optionTree(tree, options);
});
});
Here you can see the plugin:
https://code.google.com/p/jquery-option-tree/
I don't know that plugin, but looking at the examples there seems to be one that fits your need; Example 6 - AJAX lazy loading & setting value on each level change.
This would, in theory, just require some config options:
preselect: {'demo6': ['220','226']}, // array of default values - if on any level option value will be in this list, it will be selected
preselect_only_once: true, // prevent auto selecting whole branch when user maniputales one of branch levels
get_parent_value_if_empty: true,
attr: "id" // we'll use input id instead of name
If this doesn't fit you need though, you could initiate it from an event, like change, keyup, etc.
$(document).on('change', '#select', function() {
$('#nextSelect').val($(this).val());
})
$(document).on('change', '#nextSelect', function() {
$('#finalInput').val($(this).val());
})
Yes, you are right Mackan ! I saw that "preselect" option but I was initially unable to use it transferring the path from database to javascript, I ended up with my "newbie" solution to match the syntax:
preselect: {'parent_category_id': [0,'2','22']},
PHP
$category_path comes from DB query and is like "0,2,76,140,"
$path = explode(',', $category_path);
$preselect="";
foreach ($path as $value) {
$int = (int)$value;
if ($int != 0) $preselect.= "'". $int ."',";
else $preselect.= $int.","; // have to do this as ZERO in my case has to be without apostrophes ''
}
$preselect = "{'parent_category_id':[".$preselect."]}"
JS
var presel= <?php echo($preselect); ?>;
var options = {
preselect: (presel),
}
Any suggestion for a better code ?
Thanks a lot !!
I am using CakePhp 2.2.1 and I am having some problems to implement what I just asked in the title, I found several tutorials but most of them are for cakephp 1.3 and the others are not what I want to do. I have a "events" table which contains a "player_id" thus a Player has many Events and an Event belongs to a Player.
In my Event add form I proceed as the cookbook says and I get a dropdown list of players to choose from, however what I want is to just write the names of the players and select the one I want from the autocomplete results. Also these players must be from the team that I select before that. Any ideas?
Thanks in advance.
Special thanks to Andrew for pointing out this api.jqueryui.com/autocomplete. However there is not a real guide to use this one. So i found this post, which explains what Abhishek's second link says but I could understand it better. So here is my solution if anyone is interested:
1 - Download from the autocomplete page the .js you need. Save it in app/webroot/js
2 - Either in your app/View/Layouts/default.ctp or in the view you want to use the autocomplete add:
echo $this->Html->script('jquery-1.9.1.js');
echo $this->Html->script('jquery-ui-1.10.3.custom.js');
echo $this->fetch('script');
3 - In your view add (mine was add_goal.ctp):
<script>
$(document).ready(function(){
var myselect = document.getElementById("EventTeam"); //I needed to know which team I was looking players from.
var team = myselect.options[myselect.selectedIndex].value; //"EventTeam" was a dropdown list so I had to get the selected value this way.
$("#EventPlayer").autocomplete({
source: "/events/autoComplete/" + team,
minLength: 2, //This is the min ammount of chars before autocomplete kicks in
autoFocus: true
});
$("input:submit").button();
$("#EventPlayerId").autocomplete({
select: function(event, ui) {
selected_id = ui.item.id;
$('#EventAddGoalForm').append('<input id="EventPlayerId" type="hidden" name="data[Event][player_id]" value="' + selected_id + '" />');
}
});
$("#EventPlayerId").autocomplete({
open: function(event, ui) {
$('#EventPlayerId').remove();
}
});
});
</script>
4 - In your Controller (mina was EventController.php):
public function autoComplete($team = null){
Configure::write('debug', 0);
$this->autoRender=false;
$this->layout = 'ajax';
$query = $_GET['term'];
$players = $this->Event->Player->find('all', array(
'conditions' => array('Player.team_id' => $team, 'Player.name LIKE' => '%' . $query . '%'),
'fields' => array('name', 'id')));
$i=0;
foreach($players as $player){
$response[$i]['id']=$player['Player']['id'];
$response[$i]['label']=$player['Player']['name'];
$response[$i]['value']=$player['Player']['name'];
$i++;
}
echo json_encode($response);
}
visit below link ,this might help you as the ajax helper is no more in cake2.X versions core all related functionality moved to JS helper class.(here third one link for AJAX helper for contributed by user may help you)
http://bakery.cakephp.org/articles/matt_1/2011/08/07/yet_another_jquery_autocomplete_helper_2
or
http://nuts-and-bolts-of-cakephp.com/2013/08/27/cakephp-and-jquery-auto-complete-revisited/
or
http://bakery.cakephp.org/articles/jozek000/2011/11/23/ajax_helper_with_jquery_for_cakephp_2_x
You need to use ajax because your autocomplete-results depends on the team you have selected.
Something like this in jquery:
var team = $('#teamdropdown').find(":selected").text();
$.ajax({
type: "POST",
url: 'http://domain.com/playersdata',
data: {'team':team},
success: function(data){
console.log(data);
//put data in for example in li list for autocomplete or in an array for the autocomplete plugin
},
});
And in cake on playersdata page (Controller or model) something like this.
if( $this->request->is('ajax') ) {
$arr_players = $this->Players->find('all', array('conditions'=>array('team'=>$this->request->data('team')))); //pr($this->request->data) to get all the ajax response
echo json_encode($arr_players);
}
Also set headers to a json respons and $this->layout = null; to remove the layout tpl.
Another solution would be to use json_encode in your php and pass it to js-code like
<script>var players = <?php echo json_encode($array_players_with_teams); ?>; </script>
This solution is only interesting for a small amount of data, if you have a big database with teams and players I wouldn't recommend this, because why load all this data if you only need just a bit of it...
I didn't test the code but it should help you to go on...
Good luck!
I am working on an in-browser image layout GUI. The user uploads a series of images to the page, arranges them on the page using jQuery UI Draggable and Resizable, and then saves the position/size of the images using a submit button.
I am getting the final image data like so:
$('div.ui-wrapper').each( function(id) {
var _width = $(this).css("width");
var _height = $(this).css("height");
var _left = $(this).css("left");
var _top = $(this).css("top");
var _src = $('img').eq(id).attr("src");
var imgs = {
'imageID' : id,
'width' : _width,
'height' : _height,
'left' : _left,
'top' : _top,
'src' : _src
};
finalimgarray.push(imgs);
});
I would like the user to be able to submit this array via a form POST to a PHP function which would iterate over each value and store it to a SQL table. What is the best way to do this? I have considered converting to JSON or using a multidimensional array in the post but am not sure how to process an array of data.