i have php var same this in index.php file :
<?php
$aoData = '
{ "name": "count", "value": "5" } ,
{ "name": "tbl", "value": "member" } ,
{ "name": "0", "value": "id" } ,
{ "name": "1", "value": "fname" } ,
{ "name": "2", "value": "lname" } ,
{ "name": "3", "value": "username" } ,
{ "name": "4", "value": "mail" }
';
include("main.php");
?>
i need send this php var as js function parameters in main.php and i use json like this:
<input type="button" onClick="run(<?php echo htmlentities(json_encode($aoData)); ?>)"
and i need use this var in load.js as a parameters. my load.js is like this :
function run(data1){
var oTable =$('#example').dataTable( {
aoData.push(**data1**)},
"onblur" : "disable",
"select" : true })}
but this way doesn't work.
It looks like your data is already json_encode()ed in your main PHP file. You should just be able to echo is using htmlentities() to make sure it is attribute-safe.
So run( <?php echo htmlentities( $aoData ); ?> )
Just as a note, what you're doing with json_encode() would work if $aoData looked like:
$aoData = array(
array( 'name' => '', 'value' => '' ),
array( 'name' => '', 'value' => '' ),
array( 'name' => '', 'value' => '' ),
);
json_encode() takes an array/object and turns it into JSON, which is a string that is formatted similarly to how your $aoData is currently.
You shouldn't be hand-coding json in PHP. There are too many potential encoding issues that can develop from this. Make a PHP array and then encode that.
$aoData = array();
$aoData[] = array('name' => 'count', 'value => 5);
...
echo json_encode($aoData);
The data table function needs two parameters. But you are pass one variable to that function.
Look through the documentation of datatable and their input types.
You can use php variable directly on your javascript function its on a same page.
Try to alert the javascript params for check yourself
Your json.encode not handled correctly. Already you have a json string. Then why you need encode
I actually agree with Tyler Carter
you should encode your JSON from a PHP array.
The following example is completely independent and you can see the result in your console
<?php
$aoData = json_encode(array(
array("name" => "count", "value" => "5"),
array("tbl" => "count", "value" => "member"),
array("0" => "count", "value" => "id"),
array("1" => "count", "value" => "fname"),
array("2" => "count", "value" => "lname"),
array("3" => "count", "value" => "username"),
array("4" => "count", "value" => "mail"),
));
?>
<html>
<body>
<input type="button" onclick="console.log(<?=htmlentities($aoData);?>)" value="run"/>;
</body>
</html>
Related
I have a Javascript file with a function I'm trying to test. All the function does is make a jQuery post request to a PHP ajax file (see code)
function loadTeams(clubID){
var data = {
action: 'loadClubTeams',
clubID: clubID
};
return jQuery.post('/ajax/calendar_ajax.php', data);
}
I have a mock set up in my /__mocks__/ dir as such:
<?php
$teams = array(
array(
"Name" => "Team 1",
"ClubID" => 34
),
array(
"Name" => "Team 2",
"ClubID" => 34
),
array(
"Name" => "Team 3",
"ClubID" => 35
)
);
$response = array();
if($_REQUEST['action'] == "loadClubTeams"){
foreach($teams as $team){
if($team['ClubID'] == $_REQUEST['ClubID']){
array_push($response, $team);
}
}
}
return json_encode($response);
Here is my test file:
const assoc_cal = require('../../secure-htdocs/js/templates/association_calendar');
jest.mock('../../secure-htdocs/ajax/calendar_ajax.php');
test("loadTeams returns Teams 1 and 2 when passed clubID 34", () =>{
data = {action: "loadTeams", ClubID: 34};
const expected = [
{
name: "Team 1",
clubID: 34
},
{
name: "Team 2",
clubID: 34
}
];
expect(assoc_cal(data)).toEqual(expect.arrayContaining(expected));
});
But when I run my test, it still tries to call the real calendar_ajax.php file. I'm apparently setting up the mock incorrectly. Can anyone else out with this?
im using php to send a push but my json object isent getting the way i want...
i need my json to be like this :
{
"to": ["xxx"],
"data": {
"title": "dw",
"body": "dw",
"actions": [
{ "icon": "emailGuests", "title": "Candidatar-me", "callback": "app.emailGuests", "foreground": true},
]
}
}
but im getting this instead :
{
"to": "xxx",
"data": {
"title": "dw",
"body": "dw",
"actions": {
"icon": "send.ico",
"title": "EMAIL GUESTS",
"callback": "app.callbackName",
"foreground": true
}
}
}
i am building my json like this :
$fields = array ( 'to' => $row1['fcm_registered_id'] ,
'priority' => "high",
'data' => array("title" =>$titlepost,
"body"=> $msg,
"actions" => array('icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
),
);
Remember that json_encodeconverts non-numeric indexed arrays to objects. There is why you gets objects instead of array of objects. It's enough to wrap this array by another array. Here is fixed code:
$fields = array (
'to' => array( $row1['fcm_registered_id'] ),
'data' => array(
"title" =>$titlepost,
"body"=> $msg,
"actions" => array(
array(
'icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
)
)
);
And here is working example: http://phpio.net/s/1n0e
Little note: try to use new array syntax: [] than old array()
Instead of "value": "11413425.62", how can I change the code to get the data from database phpMyAdmin?
Here's my full code..
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'angulargauge',
renderAt: 'Profit10%',
width: '350',
height: '250',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Total Profit",
"subcaption": "After add value",
"lowerLimit": "0",
"upperLimit": "10000000",
"showValue": "1",
"valueBelowPivot": "1",
"theme": "fint"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "50000",
"code": "#e44a00"
}, {
"minValue": "50000",
"maxValue": "75000",
"code": "#f8bd19"
}, {
"minValue": "75000",
"maxValue": "100000",
"code": "#6baa01"
}]
},
"dials": {
"dial": [{
"value": "11413425.62"
}]
}
}
}
);
fusioncharts.render();
});
</script>
and the data had been extracted using this file "dataCountryGrossMargin.php" with this code.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
//connect to the server
$connect= mysql_connect("127.0.0.1","root","");
//$conn = new mysqli($servername, $username, $password);
if(!$connect)
{
die('Could not connect: '.mysql_error($connect));
}
//connect to the database
mysql_select_db("fyp",$connect);
$result = mysql_query("SELECT Country, COGS FROM `table 3`");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($connect);
?>
Thank you !
You can use a similar approach to the example offered on the Fusioncharts website:
<?php
/* Include the `fusioncharts.php` file that contains functions to embed the charts. */
include("includes/fusioncharts.php");
/* The following 4 code lines contain the database connection information. Alternatively, you can move these code lines to a separate file and include the file here. You can also modify this code based on your database connection. */
$hostdb = "localhost"; // MySQl host
$userdb = "root"; // MySQL username
$passdb = ""; // MySQL password
$namedb = "fusioncharts_phpsample"; // MySQL database name
// Establish a connection to the database
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Name, Population FROM Country ORDER BY Population DESC LIMIT 10";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Countries",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Name"],
"value" => $row["Population"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
I want to retrieve data from mysql in the form of graph with the following code. But, nothing is shown. Can anybody help me?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "graphdata.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?php
echo("<div id='chart_div'></div>");
?>
Here is my getdata.php:
$sql = "SELECT count(`booth_number`),`sold_by` FROM `registration1` where week(`Date`) = week(curdate()) GROUP BY `sold_by`";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'string')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);
As mentioned, I think you need to move your code inside the success callback:
function drawChart() {
$.ajax({
url: "graphdata.php",
type: "GET",
dataType:"json",
success: function(jsonData, textStatus, jqXHR) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
});
}
[edit] A working example (with some mocked data) can be found on jsBin.
[edit2] Update the example on jsBin with the output provided in the duplicate question:
{
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"string"
}
],
"rows": [
{
"c":[
{"v":"3"},
{"v":"jaspreet singh "}
]
},{
"c":[
{"v":"3"},
{"v":"joseph swanson"}
]
}
]
}
The JSON returned by the server is wrong, the object should look like this:
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"number"
}
],
"rows": [
{
"c":[
{"v":"jaspreet singh "},
{"v":"3"}
]
},{
"c":[
{"v":"joseph swanson"},
{"v":"3"}
]
}
]
};
The changes needed should now be obvious. Hope this helps.
[edit3] getdata.php should contain the following snippet imho:
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'number')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array(
'c' => array(
array('v' => $row[1]),
array('v' => $row[0])
)
);
}
Ok so I have a json output that looks like this:
{"Result" : [
{
"Id" : "5214",
"ParentReasonId" : "0",
"Description" : "Billing & Payment",
"SysName" : "Billing & Payment",
"SysCategory" : "Billing & Payment",
"ClientId" : "924",
"DispositionCount" : "6",
"IsActive" : true,
"ChildReasonCount" : "8",
"Attributes" : [],
"SortOrder" : "0",
"CreatedBy" : null
}
]
}
And I would like to pull the data for id and description out of this.
jQuery("#chained_child").cascade("#chained", {
ajax: { url: 'Customhandler.ashx?List=MyList' },
template: commonTemplate,
match: commonMatch
});
function commonTemplate(item) {
return "<option Value='" + item.Result.Id + "'>"
+ item.Result.Description + "</option>";
};
But for the life of me I can't get it to return the value I am looking for. I know this is something noobish but I am hitting a wall. Can anyone help?
If you examine your JSON string, your Result object is actually an array of size 1 containing an object, not just an object. You should remove the extra brackets or refer to your variable using:
item.Result[0].Id
In order to reference your variable using item.Result.Id you would need the following JSON string:
{
"Result" :
{
"Id" : "5214",
"ParentReasonId" : "0",
"Description" : "Billing & Payment",
"SysName" : "Billing & Payment",
"SysCategory" : "Billing & Payment",
"ClientId" : "924",
"DispositionCount" : "6",
"IsActive" : true,
"ChildReasonCount" : "8",
"Attributes" : [],
"SortOrder" : "0",
"CreatedBy" : null
}
}
One thing that has helped me immensely with JSON funkyness has been setting breakpoints in Firebug, which let's you step through the resulting object, and view its structure.
item.Result[0].Id works as Sebastian mentioned - however it only works if "item" is actually assigned a value. My guess is it's not.
In your commonTemplate function try doing console.log(item) and seeing what the result is.
As far as I see it on the plugin page, the argument send to the template callback is an
item from the JSON response, which is an Array. Your JSON response is an Object. I guess you're not sending the correct JSON response. But take that with a grain of salt, as I've never used this plugin.
Anyway, if I'm right, you're response should be:
[
{
"Result" :
{
"Id" : "5214",
"ParentReasonId" : "0",
"Description" : "Billing & Payment",
"SysName" : "Billing & Payment",
"SysCategory" : "Billing & Payment",
"ClientId" : "924",
"DispositionCount" : "6",
"IsActive" : true,
"ChildReasonCount" : "8",
"Attributes" : [],
"SortOrder" : "0",
"CreatedBy" : null
}
}
]
Ionut G. Stan's answer is correct. Your json output is not the correct format for the cascade plugin.
If you don't want to change your json, you can use the dataFilter option in the ajax settings to augment the data.
I've set up a working demo here: http://jsbin.com/ebohe (editable via http://jsbin.com/ebohe/edit )
Here's the pertinent javascript:
$(function(){
$('#chained_child').cascade(
'#chained',
{
ajax: {
url: 'Customhandler.ashx?List=MyList',
dataFilter: extractResult
},
template: customTemplate,
match: customMatch
}
);
function extractResult(data) {
return eval('(' + data + ')').Result;
}
function customTemplate(item) {
return $('<option />')
.val(item.Id)
.text(item.Description);
}
function customMatch(selectedValue) {
return this.ParentReasonId == selectedValue;
}
});
You might want to take a look at this JSON tutorial from IBM:
Mastering Ajax, Part 10: Using JSON for data transfer