I would like to create a flot bar graph based on a php output. I managed to output data from php, but I would also like to use labels and display them on the xaxis. For some reason the output of the code below is invalid. The labels show up, but the bars and xaxis labels do not.
PHP:
function getOverview() {
$arr[] = array(
'label' => "Label 1",
'data' => array(0, 1)
);
$arr[] = array(
'label' => "Label 2",
'data' => array(1, 2)
);
echo json_encode($arr);
}
Output:
[{"label":"Label 1","data":[0,1]},{"label":"Label 2","data":[1,2]}]
jQuery:
$(document).ready(function(){
$.ajax({
url: 'http://localhost/getOverview.php',
method: 'GET',
dataType:"json",
success: onOutboundReveived
});
function onOutboundReveived(series)
{
var options = {
series: {
bars: {
show: true,
barWidth: .1,
align: 'center'
}
},
xaxis: {
tickSize: 1
}
};
$.plot("#chart_filled_blue", series, options);
}
});
Can anyone help me?
You've got a couple problems:
1.) Series data needs to be an array of arrays. Not just a single array:
'data' => array(array(1, 2))
This is, of course, so a series could have more than one point (even though your's has a single point).
2.) To get xaxis labels, you have two options. One, use the categories plugin. Two, manually provide the tick labels:
ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]
In your situation I'd just use the category plugin. You'll need to modify the final data to:
{"label":"Label 1","data":[["Label 1",1]]}
or in the PHP:
$arr[] = array(
'label' => "Label 1",
'data' => array(array("Label 1", 1))
);
Here's a fiddle.
I think, your output has an incorrect format. Try this:
[
{
label: "Label 1",
data: [[0,1]]
},
{
label: "Label 2",
data: [[1,2]]
}
]
Related
My php file has code look like this
<?php
$connect = mysqli_connect("localhost","root","","surveytest");
$query = '';
$table_data = '';
$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);
foreach($array2 as $row) //Extract the Array Values by using Foreach Loop
{
$query .= "INSERT INTO survey(name, gender, designation)
VALUES
('".$row["name"]."',
'".$row["gender"]."',
'".$row["designation"]."'); "; // Make Multiple Insert Query
$table_data .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
</tr>
'; //Data for display on Web page
}
if(mysqli_multi_query($connect, $query)) //Run Mutliple Insert Query
{
echo '<h3>Imported JSON Data</h3><br />';
echo '
<table class="table table-bordered">
<tr>
<th width="45%">Name</th>
<th width="10%">Gender</th>
<th width="45%">Designation</th>
</tr>
';
echo $table_data;
echo '</table>';
}
?>
My javascript file has code look like this
var json =
{
"items": [
{
"name": "Rusydi",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Hakim",
"gender": "Male",
"designation": "Conservation worker"
}
]
}
Hey! i am a beginner for javascript and JSON.
I try to add var json into mysql database.
Now i want to refer to this javascriptfile(var json) but it's don't work.
My purpose is try to stored this variable in mysql.
That's why i try to do like this.
var json = {
questions: [
{
name: "name",
type: "text",
title: "Please enter your name:",
placeHolder: "Jon Snow",
isRequired: true
}, {
name: "birthdate",
type: "text",
inputType: "date",
title: "Your birthdate:",
isRequired: true
}, {
name: "color",
type: "text",
inputType: "color",
title: "Your favorite color:"
}, {
name: "email",
type: "text",
inputType: "email",
title: "Your e-mail:",
placeHolder: "jon.snow#nightwatch.org",
isRequired: true,
validators: [
{
type: "email"
}
]
}
]
};
This is full code.
https://surveyjs.io/Examples/Library/?id=questiontype-text&platform=jQuery&theme=default
Survey
.StylesManager
.applyTheme("default");
var json = {
questions: [
{
name: "name",
type: "text",
title: "Please enter your name:",
placeHolder: "Jon Snow",
isRequired: true
}, {
name: "birthdate",
type: "text",
inputType: "date",
title: "Your birthdate:",
isRequired: true
}, {
name: "color",
type: "text",
inputType: "color",
title: "Your favorite color:"
}, {
name: "email",
type: "text",
inputType: "email",
title: "Your e-mail:",
placeHolder: "jon.snow#nightwatch.org",
isRequired: true,
validators: [
{
type: "email"
}
]
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (result) {
document
.querySelector('#surveyResult')
.innerHTML = "result: " + JSON.stringify(result.data);
});
$("#surveyElement").Survey({model: survey});
or what should i do?
Remove the "var json =" from your file and change the extension to ".json" instead of ".js".
Since your javascript file does not contain a valid JSON string it cannot be decoded by php.
employee_data.json
{
"items": [
{
"name": "Rusydi",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Hakim",
"gender": "Male",
"designation": "Conservation worker"
}
]
}
Ok the problem as I see it is this:
//employee_data.js
var json =
{
And then you import that
$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);
JSON is not JavaScript code (strictly speaking), it's way to format or encode JavaScript objects as strings. (JavaScript Object Notation). So your file should start with { and not a variable setting. So you just need to remove that var json = bit.
If you check var_dump($array2); it will probably say NULL and if you check echo json_last_error_msg() right after doing json_decode it will probably say something like Syntax error invalid JSON etc..
This can be reproduced like this:
var_dump(json_decode('var json={"foo":"bar"}', true));
echo json_last_error_msg();
Output:
NULL
Syntax error
Sandbox
If you remove the var json = from my overly simple example, you get this:
array(1) {
["foo"]=> string(3) "bar"
}
No error
Cheers!
First, isolate the json data which immediately follows var json = and ends with } which is followed immediately by ;.
Then repair the json string by wrapping all of the keys in double quotes.
Finally, convert the data to an array so that you can perform your query process with the questions subarrays.
*Note, I DO NOT recommend that you use mysqli_multi_query() because it is unstable/insecure. I recommend that you use a prepared statement to INSERT your data. I will refrain from explaining this task because there are many, many examples of how to do this on StackOverflow.
Code: (PHP Demo) (Regex 1 Demo) (Regex 2 Demo)
if (preg_match('~^var json = \K{.*?}(?=;)~ms', $js_file_contents, $match)) { // cut away extra
$json = preg_replace('~^\s*\K\w+~m', '"\0"', $match[0]); // quote-wrap the keys
var_export(json_decode($json, true)); // convert json string to array and display
}
Output:
array (
'questions' =>
array (
0 =>
array (
'name' => 'name',
'type' => 'text',
'title' => 'Please enter your name:',
'placeHolder' => 'Jon Snow',
'isRequired' => true,
),
1 =>
array (
'name' => 'birthdate',
'type' => 'text',
'inputType' => 'date',
'title' => 'Your birthdate:',
'isRequired' => true,
),
2 =>
array (
'name' => 'color',
'type' => 'text',
'inputType' => 'color',
'title' => 'Your favorite color:',
),
3 =>
array (
'name' => 'email',
'type' => 'text',
'inputType' => 'email',
'title' => 'Your e-mail:',
'placeHolder' => 'jon.snow#nightwatch.org',
'isRequired' => true,
'validators' =>
array (
0 =>
array (
'type' => 'email',
),
),
),
),
)
In laravel am using eloquent to get data from the database.
I have two tables 'questions' and 'options'
Am using the eloquent method to join 'options' to 'questions'
$questions = Question::join('options', 'options.question_id', 'questions.id');
return QuestionResource($questions);
This does return an expected collection of data, where the same question appear multiple times in the collection and each is joined with different options where the 'options.question_id' and 'question.id' are the same.
[
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "city",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "planet",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "continent",
answer: true
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 2,
value: "comedian",
answer: false
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 1,
value: "genius scientist",
answer: true
}
]
I want all options be nested under a key within the related question. Like
[
{
id: 1,
text: "Africa is a...?",
// joined options
options: [
{value: "city", answer: false},
{value: "planet", answer: false},
{value: "continent", answer: true}
]
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined options
options: [
{value: "comedian", answer: false},
{value: "genius scientist", answer: true}
]
}
]
Can I achieve this with laravel's eloquent or I'll have to apply an extra logic.
If you want to applie extra logic this code may help you
<?php
$combinedqst = array('id' => '','text'=> '','option'=> array('value' => array('value' => ,'' ), 'answer' => ''));
$ids = array('id' => , '');
//loop through questions array 1st loop for getting the question
foreach($questions as $question) {
$count = 0;
//check if question is already looped
if(!in_array($question["id"],$ids)){
//2end loop to get the opstions
foreach($questions as $question_check) {
if($question_check["id"] == $question["id"]){
if($count == 0){
$combinedqst["id"] = $question["id"];
$combinedqst["text"] = $question["text"];
}
$count = 1;
array_push($combinedqst["option"]['value'],$question_check['value']);
array_push($combinedqst["option"]['answer'],$question_check['answer']);
}
}
}
array_push($ids,$question["id"]);
}
vardump($combinedqst);
In mongoDB i have two collection users and posts following this structure:
Posts
{
_id: ObjectId(""),
subject: "some post",
content: "here is the content",
user_id: "4351"
}
Users
{
user_id: "4351",
name: "John Marks",
picURL: "http://...",
aboutme: "historian of the future"
}
needing to get the posts in array with name.
db.posts.find().map(function(newPost){
newPost.name = db.users.findOne({user_id: newPost.user_id}).name;
return (newPost);
})
I wrote this code and it's work in mongoshell well returning this result:
{
_id: ObjectId(""),
subject: "some post",
content: "here is the content",
user_id: "4351",
name: "John Marks"
}
but i could not apply in php. You can't just simple get the output of the map function. It requires reduce function and output collection for the returning value.
Edit:
$map = new MongoCode('
function(newPost) {
newPost.username = db.users.findOne({user_id: newPost.user_id}).name;
return newPost;
}
');
post = $app->mongo->command(array(
"mapreduce" => "posts",
"map" => $map,
"reduce" => '',
"out" => array("inline" => 1)
));
var_dump($post);
This code must be work but accessing another collection in map function via 'db' is forbidden after mongo 2.4 release. That's why i changed my approach. Instead of using map/reduce, handled with php. Added posts user_ids to array and get the users information with following code.
$userInf = $app->mongo->selectCollection("users")->find(
array('user_id' => array('$in' => $user_ids)),
array("_id" => 0, "user_id" => 1, "name" => 1, "picURL" => 1)
);
I am very much hoping you can help me with this as I've spent all too much time on this. First, my JSON formatting is unfortunately not very mutable and I have moved it to a number of different formats to support both some jquery and a php-based search. Each time I move it, the search will work and the rest of the site will break or vice-versa.
Is it possible to access a JSON array by both name and index number? Here is my JSON (stored in PHP file and being retrieved & converted successfully to valid JSON):
<?php
$contents = array(
'Song Name #1 by Artist Name #1 (maininfo)' => array(
'contentid' => '1',
'aname' => 'Artist Name',
'sname' => 'Song Name',
'main' => 'core content #1',
'maininfo' => 'url')
),
'Song Name #2 by Artist Name #2 (maininfo)' => array(
'contentid' => '2',
'aname' => 'Artist Name',
'sname' => 'Song Name',
'main' => 'core content #2',
'maininfo' => 'url')
);
?>
My search works when something in the array title is matched on, otherwise it returns no matches so I must leave the array title as-is.
Another part of my project uses jquery and has the following:
parse(jsonobj[0][1]['sname']) //successfully already returning 'Song Name'
The above will ONLY work when the array title is not provided (e.g. 'Song Name #1 by Artist Name #1 (maininfo)' => array( becomes simply array(.
For those curious, file is being converted to JSON using:
var jsonobj;
$.ajax({
url: 'getjson.php',
dataType: "json",
success: function (doc) {
jsonobj = doc;
}
});
On the PHP side, when getjson.php is called the JSON array (above) is loaded in and converted to valid JSON using:
$final = array($final_contents);
header('Content-type: application/json');
echo json_encode($final);
Note: $final_contents is just $contents with an additional header added. See Searching JSON array for values and accessing surrounding keys/values; output as JSON for the PHP I have running specifically.
Thank you in advance.
JavaScript does not support arrays with named indexes. You should encode it as a JSON object instead.
var $contents = {
"Song Name #1 by Artist Name #1 (maininfo)": {
"contentid": 1,
"aname": "Artist Name",
"sname": "Song Name",
"main": "core content #1",
"maininfo": "url"
},{
"Song Name #2 by Artist Name #2 (maininfo)": {
"contentid": 2,
"aname": "Artist Name",
"sname": "Song Name",
"main": "core content #2",
"maininfo": "url"
}
};
Although it would probably be better to arrange it this way (here's a fiddle to demonstrate:
var songs = [
{
"contentid": 1,
"artist": "Artist Name",
"title": "Song Title 1",
"main": "core content #1",
"maininfo": "url"
},
{
"contentid": 2,
"artist": "Artist Name",
"title": "Song Title 2",
"main": "core content #2",
"maininfo": "url"
}
];
Then you can search through your songs list by id, or iterate through to filter on specific field values. For instance to find all songs whose titles start with "Song Title":
var findAllSongs = function(prop, value){
var result = new Array();
for (var i = 0; i < songs.length; i++) {
var song = songs[i];
if (song[prop] && (song[prop] === value || song[prop].search(value) >= 0)){
result.push(song);
}
}
return result;
};
var song = findAllSongs("title","Song Title 2")[0];
alert(song.contentid);
// Outputs "2"
The php equivalent of my json above is:
$songs = array(
array(
"contentid" => 1,
"artist" => "Artist Name",
"title" => "Song Title 1",
"main" => "core content #1",
"maininfo" => "url",
),
array(
"contentid" => 2,
"artist" => "Artist Name",
"title" => "Song Title 2",
"main" => "core content #2",
"maininfo" => "url",
)
);
If you're using PHP 5.4 or higher, you can use the short syntax:
$songs = [
[
"contentid" => 1,
"artist" => "Artist Name",
"title" => "Song Title 1",
"main" => "core content #1",
"maininfo" => "url",
],[
"contentid" => 2,
"artist" => "Artist Name",
"title" => "Song Title 2",
"main" => "core content #2",
"maininfo" => "url",
]
];
Then you can turn it into JSON by using your current method:
json_encode($songs);
You are having array. convert it to json using following code (json_encode) and echo so that jquery can receive it:
$jsonVar = json_encode($contents);
echo $jsonVar;
Update:
Code to call json using ajax is:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Alternatively you can use shorthand for it:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Of course the file being sent should be in json format, that is:
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
for that you need to convert the array into json.
I've been trying to learn how to convert MySQL query results to JSON arrays in PHP and I haven't managed to make much progress.
Basically I'm trying to convert the results of this query into an array:
$sql = mysql_query("SELECT `status` FROM jobs");
while($row = mysql_fetch_array($sql)){
$job_status = $row['status'];
}
Into this:
$data = array(
array( 'label'=> "a", 'data'=> 1), // The data values are queried using PHP and SQL
array( 'label'=> "b", 'data'=> 2),
array( 'label'=> "c", 'data'=> 3)
);
echo json_encode($data);
The $data array will be used display the values in the float chart. The code is shown below:
if($("#piechart").length)
{
$.plot($("#piechart"), data,
{
series: {
pie: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
},
legend: {
show: false
},
colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
});
Below is the JS code that is converted into a PHP array and the encoded using JSON.
var data = [
{ label: "a", data: 1},
{ label: "b", data: 2},
{ label: "c", data: 3},
Any help would be greatly appreciated!
mysql_fetch_assoc might work better