Morris.js setData doesn't work, unless I do this - json

I'm graphing data based on database results and getting the data via ajax. The graph is supposed to redraw based on the query using jquery setData. I've asked other programmers at work and still can't figure it out.
php code
if(isset($_POST['data'])){
$data = $_POST['data'];
$data = json_decode($data);
$query = "SELECT * FROM bad_errors WHERE rel = '$data' LIMIT 20";
$result = $db->query($query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$month = date("M", strtotime($row['date_time']));
$chart_data .= "{ month:'".$month."', website:".$row["rel"].", code:".$row["code"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
$data = json_encode($chart_data);
echo $data;
}
jquery code
let barChart = Morris.Bar({
element : 'chart',
data:[],
xkey:'month',
ykeys:['website', 'code'],
labels:['website', 'code'],
hideHover:'auto',
stacked:true
});
let json = JSON.stringify(rel);
$.ajax({
url: "ajax-php/morris-data.php",
type: "POST",
data: {data: json},
dataType:"json",
success: function (data) {
//data variable only redraws the graph if data looks like this -
data = [
{ month:'Mar', website:38, code:547}, {
month:'Mar', website:38, code:584}, { month:'Mar', website:38,
code:500}, { month:'Mar', website:38, code:564}, { month:'Mar',
website:38, code:500},
]
barChart.setData(data); // but not here via ajax success
},
});

I was processing the data wrong in php
while($row = mysqli_fetch_array($result))
{
$month = date("M", strtotime($row['date_time']));
$data[] = array(
'month' => $month,
'website' => $row['rel'],
'code' => $row['code']
);
}
$data = json_encode($data);
echo $data;

Related

WordPress API JSON output not valid with quotes

I have a custom function that outputs a Json
However the Json Output has always quotes added and is thus unvalid.
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
return print_r($result, true);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
The result I get is: "[{\"bus_id\":\"BC025\",\"traject_id\":\"D\",\"traject_show\":[[\"06:00-08:16\"]]}]"
I just replaced the $result with a teststring. It is exactly same format that comes through the function.
How to get rid of those outer quotes?
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
$result = json_decode($result);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
For you better understanding about json_decode please visit here

Auto display results using json

Currently i'm using json to auto display my reuslt, but i got error say json_encode(): type is unsupported, encoded as null, and i think my problem is view, when i choose in name in dropdown i gives an error json_encode(): type is unsupported, encoded
Model
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
foreach($result->result_array() as $row){
echo $row['address'];
}
}
return $result;
}
Controller
function address() {
$name=$this->input->post('name');
$this->load->model('default/M_profile');
$data['address'] = $this->M_vendor->get_address($name);
$this->output->set_output(json_encode($data));
//echo $data;
return;
}
in view i use dropdown.
$(document).ready(function () {
$('#profile select').change(function () {
var add = $(this).text();
$.ajax({
url: "<?php echo base_url();?>admin/profile/address",
method: "POST",
data: {profile: add},
success: function(add) {
$('#address').val(add);
}
})
});
});
<select name="test">....</select>
You have a lots of errors:
1.In ajax it should be type:'POST'.Not method:'POST'.
2.In controller it should be $this->input->post('profile')
3.In model just return your data using result_array().
MODEL:
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
return $result->result_array();
}
}
}
Controller:
function address() {
$name=$this->input->post('profile');
$this->load->model('default/M_profile');
$data = $this->M_vendor->get_address($name);
echo json_encode($data);
}
View:(Ajax):
<script type="text/javascript">
$(document).ready(function () {
$('#profile select').change(function () {
var add = $(this).text();
$.ajax({
url: "<?php echo base_url('admin/profile/address');?>",
type: "POST",
data: {profile: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
alert(data[0].address);
}
})
});
});
</script>
<select name="test">....</select>
I hope it helps you a lot.
you are echoing the result instead of returning
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
foreach($result->result_array() as $row){
$result[] = $row['address'];
}
}
return $result;
}

Yii2 Post to controller and get back data

This is my code in view.
<?= $form->field($model, 'projectTitle')->dropDownList($fullprojectlist, [
'prompt'=>'-Choose a Course-',
'id' => 'projectList',
'type'=> 'POST',
'onchange'=>' var value = $("#projectList :selected").val();
//$("#draftproposalform-supervisor").val(value);'
$.post("'.Yii::$app->urlManager->createUrl(["/draftproposalform.php", "id" => value).'", function(data) {
//set value for text box
}
]);?>
<?= $form->field($model, 'supervisor')->textInput(['readonly'=> 'true']); ?>
I am trying to pass the selected value to the controller so that I can query the database to look for the relevant information. Then send back that information to the view to settext.
I know how to get data from the database. I just don't know how I can pass the selected value to controller and get back a value to settext while maintaining the selected value in view.
public function actionDraftproposalform() {
$model = new DraftProposalForm();
if($model->load(Yii::$app->request->post()) && $model->validate())
{
return $this->refresh();
}
else {
$query = new Query;
$query->select(['User.name', 'Project.title', 'Project.project_ID'])
->from('Project')
->innerJoin('Supervisor', '`Project`.`supervisor_ID` = `Supervisor`.`supervisor_ID`')
->innerJoin('User', '`Supervisor`.`user_ID` = `User`.`user_ID`')
->where(['Project.project_type_ID'=>1, 'Project.approval_ID'=>2]);
$projectlist = $query->all();
$fullprojectlist = ArrayHelper::map($projectlist, 'name', 'title', 'project_ID');
return $this->render('draftproposalform', [
'model'=>$model,
'fullprojectlist' => $fullprojectlist]);
}
}
Sorry if it's messy. Truthfully, I don't even know if passing the data back to here is the correct choice.
Edited Codes
View
<?php
$this->registerJs(' $("#projectList").change(function() {
var value = $("#projectList option:selected").val();
alert(value);
$.post(
"'.Yii::$app->urlManager->createUrl(["/draftproposalform.php"]).'",
{id:value},
function(data) {
alert("Test");
$("input[name=\'supervisor\']").val(data);
}); });');
?>
<?= $form->field($model, 'projectTitle')->dropDownList($projectlist, [
'prompt'=>'-Choose a Course-',
'id' => 'projectList',
'type'=> 'POST'
]);
?>
<?= $form->field($model, 'supervisor')->textInput(['readonly'=> 'true']); ?>
Controller
public function actionDraftproposalform() {
$model = new DraftProposalForm();
if(Yii::$app->request->isPost)
{
$id = Yii::$app->request->post("id");
$super = DbProject::findOne(["project_ID"=>$id]);
$supervisor = DbSupervisor::findOne(["supervisor_ID"=>$super->supervisor_ID]);
$user = DbUser::findOne(["user_ID"=>$supervisor->user_ID]);
//$super = DbSupervisor::findOne(["supervisor_ID"=>$id]);
echo $user->name;
exit;
}
else {
$projectlist = ArrayHelper::map(DbProject::find()->where(['project_type_ID' => 1, 'approval_ID' => 2])->asArray()->all(), 'project_ID', 'title');
return $this->render('draftproposalform', [
'model'=>$model,
'projectlist' => $projectlist]);
}
}
Can you test this.
//Controller
<?
public function actionDraftproposalform() {
$model = new DraftProposalForm();
if(Yii::$app->request->isPost)
{
$id=Yii::$app->request->post("id");
$super=Supervisor::findOne(["supervisor_ID"=>$id]);
if($super) echo $super->name;else echo "Not found";exit;
}
else {
$query = new Query;
$query->select(['User.name', 'Project.title', 'Project.project_ID'])
->from('Project')
->innerJoin('Supervisor', '`Project`.`supervisor_ID` = `Supervisor`.`supervisor_ID`')
->innerJoin('User', '`Supervisor`.`user_ID` = `User`.`user_ID`')
->where(['Project.project_type_ID'=>1, 'Project.approval_ID'=>2]);
$projectlist = $query->all();
$fullprojectlist = ArrayHelper::map($projectlist, 'name', 'title', 'project_ID');
return $this->render('draftproposalform', [
'model'=>$model,
'fullprojectlist' => $fullprojectlist]);
}
}
//view register js: put this in your view
<?
$this->registerJs(' $("#projectList").change(function(){
var value = $("#projectList option:selected").val();
$.post(
"'.Yii::$app->urlManager->createUrl(["/draftproposalform"]).'",
{ id:value },
function(data) {
$( "#draftproposalform-supervisor").val(data);
}); });');
?>

Ajax mysql duplicate entry

before i post this i already looked up for my problem. so here it is
I'm using ajax to get a value using post. but it appears that when i insert it to my database it produces duplicate entry. here's my ajax code
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'Test App',
},
function (receiverUserIds) {
$.each(receiverUserIds.to, function (i, v) {
// console.log(receiverUserIds.request + " " + v);
$.ajax({
url: '<?php echo $config["base_url"]; ?>/main/saverequestinfo/?signed_request=<?php echo $_REQUEST["signed_request"]; ?>',
data: {
request_id: receiverUserIds.request,
receiver_id: v
},
type: 'POST',
success: function (d) {
console.log(receiverUserIds.request + " " + v);
}
});
});
}
//http://developers.facebook.com/docs/reference/dialogs/requests/
);
this is the code called by ajax
function saverequestinfo() {
$data = array(
'inv_user_id' => 1,
'inv_request_id' => $_POST['request_id'],
'inv_user_fbid' => $this->fb->getUser(),
'inv_receiver_fbid' => $_POST['receiver_id'],
'inv_liked' => fb_isLiked($this->fb)
);
$this->main->insertrequest('invitedfriends', $data);
}
and this is my model:
function insertrequest($tbl_name, $data) {
$date = date('Y-m-d H:i:s');
$qry = "INSERT INTO `".$tbl_name."` (";
$c = count($data);
$cc = 0;
$f = "";
$fv = "";
foreach($data as $i=>$v) {
$f .= $i;
$fv .= "'".$v."'";
if($cc<$c-1) {
$f .= ",";
$fv .= ",";
}
$cc++;
}
$qry .= $f.") VALUES(".$fv.")";
if ($this->conn->query($qry) !== TRUE) {
echo $this->conn->error;
die();
}
$this->conn->query($qry);
}

Kohana 3.2 select issue

I have table with 'servers' name in my db. So when I want to add there some data with that code it's just ok:
public function action_add()
{
$serverGameId = (int)Arr::get($_POST, 'serverGameId', '');
$newServerName = Arr::get($_POST, 'newServerName', '');
try
{
$server = new Model_Server();
$server->Name = $newServerName;
$server->GameId = $serverGameId;
$server->save();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "serverId" => $server->Id));
return true;
}
Here is a model:
class Model_Server extends ORM {
protected $_table_name = 'servers';
public function rules()
{
return array(
'Name' => array(
array('not_empty'),
)
);
}
}
But I have problem when I try to select it from the table:
public function action_servers()
{
$gameId = (int)Arr::get($_POST, 'gameId', '');
if($gameId == -1) return false;
try
{
$servers = ORM::factory('server')
->where('GameId', '=', $gameId)
->find_all();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "servers" => $servers, "gameId" => $gameId));
return true;
}
I already try to solve problem with change code inside of try block on:
$servers = DB::select('servers')->where('GameId', '=', $gameId);
Even when I try just get all my servers from db without '->where' it's doesn't work.
Any ideas?
Try print_r($servers); inside try block to see what you get from model.
And $servers is some class with results - use foreach to get result (one by one)
$results = array();
foreach($servers as $row) {
//echo $row->Name;
$results[] = $row->Name;
}
Or
$results = array();
foreach($servers as $row) {
//echo $row->as_array();
$results[] = $row->as_array();
}