MYSQL data + PHP to FLOTgraphing - php

im quite new to mysql and flot graphing, but i get the general idea.
This is my scenario:
I receive data from a device, in which i put into mysql database.
am i wrong in saying that the new data will replace the existing data in the database?
i then need to plot that on a graph, how do i get(store) the old values so i can put in the data in this line?
$(function () {
var d4 = [[36,37],[50,51],null,[23,24],[18,17]];
$.plot($("#placeholder"), [d4]);
});
if not, i'll only be getting the current data... and that doesnt give me a line.. it'll give me datapoints haha
Thanks for your help!

First, you'll want to set the stage for a graph that you can recreate dynamically. To do so, grab your container then fire off an ajax call to the script that wraps up your data. Within the ajax success call, catch the script's results within a function and send it off to a method such as resetGraph that will reset the graph according to the new information found within the database.
var dataview = $("#placeholder");
$.ajax({
url: "index.php",
data: "stuff&junk&things",
method: 'GET',
dataType: 'json',
success: function(msg){
resetGraph(msg);
}
});
function resetGraph( data ){
plot = $.plot(dataview, data.data, {
points: { show: true, radius: 5 },
xaxis: { ticks: data.ticks, tickSize: 7 },
yaxis: {labelHeight: 2}
});
}
Your script should be populating arrays with the necessary information then json_encoding it before sending it back to Jquery. For example,
echo json_encode(
array(
"data" => array(
array("data" => array(1,2,3))
),
"ticks" => array(2, "two")
)
);

Related

PHP Clickable Row that display data of details?

How can I do clickable tab that display data?
I want to fetch the data from mysql row to the row in the table dynamically and when i open her i will see the details of all the the row in my database. Like in this picture.
https://ibb.co/m0Zmk7
If I didn't get your question wrong, you want to display some data from database when user will click on a row.
You need to call a function on every row just like this:
<tr onclick="somefunction(id)"></tr> OR <div onclick="somefunction(id)"></div>
Also you have to create a div where your data will be populated.
<div id="display_data"></div>
And then JS function would be just like:
<script>
function somefunction(id){
$('#display_data').remove(); //it will remove all the data before loading new record.
$.ajax({
url: "pathOfYourFile/function/",
type: "post",
data: {
id: id
},
success: function (data) {
if(data.status==1){
alert("success");
$('#display_data').show();
$('#display_data').append(data.message);
}else{
alert(record error);
}
},
error: function (data) {
console.log(data);
}
});
}
<script>
And in the end you have to write a function in php that will get your data from database. Just make sure that you will return data just like this:
$data['json_data'] = array('status' => 1,
'message' => $record
);
I Hope this will work in your case. Please do not hesitate to ask a question if there is any confusion.

jQuery full calendar $.ajax call issue ( using static events on page open )

So I am using Yii and full calendar as a widget which is called in a view of CalendarController. Uppon call for a widget, the widget retrives existing events from the DB and puts them inside the full calendar to display. Now I have also made a simple filter for filtering out events by category they are in ( dropdown with a submit ), so I want to send request to a calendarController method called actionEvents() which then takes what is passed to it ( the category of events for which we want to retrieve events ), gets them back to the jQuery which then calls the calendar again passing it a json_encode(d) array of needed properties to correctly render events under the selected category in the dropdown. The problem I have is that it seems fullcalendar is doing my wanted call ( POST ) as well as one another GET call along with it for some reason so it does return properly formatted json to the jQuery from the method of controller, but just shows an empty calendar without events in it on return. This is how the console looks like after the returned data.
This is the code that calls ajax call
$(document).ready(function() {
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$('form.eventFilter').submit(function() {
var selectedOption = $('form.eventFilter select').val(),
eventContainer = $('.fc-event-container');
var objectToSend = { "categories" : [selectedOption],"datefrom" : "september2013"/*month + "" + year*/ , "dateto" : "september2013"/*month + "" + year*/};
$.ajax({
url: '<?php echo Yii::app()->createUrl('calendar/events'); ?>',
type: "POST",
async:false,
data: {data : JSON.stringify(objectToSend)},
success: function(data) {
$('#fc_calendar').html('');
$('#fc_calendar').fullCalendar({
events: data
});
console.log(data);
},
error: function() {
console.log(data);
}
});
return false;
})
})
The code that renders initial calendar events on first page load ( open ) is this
<div id="fc_calendar"></div>
<script class="fc_calendar_script">
// gets calendar and its events working and shown
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#fc_calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: [
<?php foreach ($eventItems as $event): ?>
{
title: '<?php echo htmlentities($event['eventItems']['title']); ?>',
start: new Date(y,m,d + <?php echo $event['eventItems']['startdate_day_difference']; ?>),
end: new Date(y,m,d + <?php echo $event['eventItems']['enddate_day_difference']; ?>),
url: '<?php echo $event['eventItems']['url']; ?>',
className: [
<?php foreach($event['eventCategories'] as $category) { echo ''.json_encode($category['slug']).','; }?> // and categories slugs as classnames, same purpose
]
},
<?php endforeach; ?>
]
});
</script>
The code in controller is not that important since you can see what it returns in the screenshot :) If someone has an idea of how to get around this I would really be grateful :) Tried everything I know
Ok so bounty goes to whoever answers this question :)
I am having problems with full calendar month rendering when ajax data is returned and events populated. Since I have checkboxes for each category ( events have MANY_MANY relation with categories ) and each time a checkbox is checked or unchecked, JSON array of chosen categories of events is passed on to PHP method which queries DB for all events that go under chose categories and returns all events in a jquery encoded array to the view which then takes that events array and rerenders the calendar like shown in the upper code.
Problem is that when a checkbox is checked or unchecked and ajax returned the calendar always renders on the current month ( so right now it would always rerender itself to show events for september, untill the end of the month, then always for Ocbober and so on ), but what if a user was on lets say November 2013 when he checked event category for which he wanted to filter the events? The calendar would rerender on September still. How could I make it rerender on the month the user was on when he checked / unchecked a checkbox ?
The code that I have which keeps track ( or at least it should ) of the current month when prev or next month buttons are clicked is this
$('.fc-button-next span').click(function(){
start = $('#fc_calendar').fullCalendar('getView').visEnd;
console.log(start);
});
$('.fc-button-prev span').click(function(){
start = $('#fc_calendar').fullCalendar('getView').visStart;
console.log(start);
});
However this code is not tracking properly, sometimes it skips a month, sometimes it stays on the month without change and sometimes it returns propper month, which is bugging me so I cant call this function of the calendar properly which should set calendar to propper month on rerender.
$('#fc_calendar').fullCalendar('gotoDate', start);
I think what you might be looking for is something like
jQuery(function($){
$('form.eventFilter').submit(function() {
$('#fc_calendar').fullCalendar( 'refetchEvents' );
return false;
});
$('#fc_calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: function(start, end, callback) {
var selectedOption = $('form.eventFilter select').val(),
eventContainer = $('.fc-event-container');
//create the data to be sent
var objectToSend = {
"categories": [selectedOption],
"datefrom": start.getDate() + '-' + start.getMonth() + '-' + start.getYear(),
"dateto": end.getDate() + '-' + end.getMonth() + '-' + end.getYear()
};
//use jsonp based jQuery request
$.ajax({
url: 'events.json',
data: objectToSend,
cache: false
}).done(function(data){
//on success call `callback` with the data
callback(data)
})
}
});
});
Demo: Plunker
Note: The date param formatting and jsonp is not used here, you will have to change it to match your requirements
I see that you use JSON.stringify(data); this is what i tought your error was
maybe you need a jsonp, and below you have my example
$.ajax({
'url': 'http://domain.com/index.php/api/news?callback=?',
'data': {'data': JSON.stringify(data), callback: 'jsonPCallback'},
'success': function(data) {
// console.log(data);
},
jsonpCallback: jsonPCallback,
dataType: 'jsonp'
});
function jsonPCallback(cbdata){
console.log('callback2')
// console.log(cbdata);
return false;
}
now, do you also use something like
echo $_GET['callback'].'('.CJSON::encode(array('status_live' => 1, 'data' => $data_decoded)).')';
in the controller to return the results ?
also, createUrl might be wrong, because you need a absolute path
Actualy the problem solution is as weird as the problem itself and it is the following. You must use designated way of doing an ajax call to fetch json that is in the plugin documentation, any other way you send your own call ( GET or POST ) and the calendar after that makes yet another call ( hence the another GET call ) if you are using just a "regular" $.ajax, $.post or $.get call using jQueries native functionality
This should really be posted somewhere on the website in some section so that people do not get confused why their calendar is not making ajax calls and I wonder how noone else had similar problem before . So this is the "correct" documentation way of calling it with full calendar which you can find HERE
$('#fc_calendar').html('');
$('#fc_calendar').fullCalendar({
eventSources: [
// your event source
{
url: '?r=calendar/events',
type: 'POST',
data: { data : JSON.stringify(objectToSend)},
error: function(data) {
alert(data);
},
}
// any other sources...
]
});
So it will automaticly fetch any returned ( properly formatted data ) and use it to rerender new calendar with those events. It is very weird way of doing it, but the only way that will work.
I can't comment so, you have an assignment to variable:"nothing" in your last query parameter
double check if you have looked for ajax request in your controller(important!),
and also if this is this a 404 by the apache, you have url rewriting problems,
and it looks like index.php is missing from url?!

jQuery JSON and PHP Associative arrays arrays issues

Hi there I was wondering if somebody could help me?
I have the following code. It retrieves JSON data from a php file. The Json is the following format :
{"Title":"rose","Price":1.25,"Number":15},{"Title":"daisy","Price":0.75,"Number":25},{"Title":"orchid","Price":1.15,"Number":7}
This JSON is created using the following php code:
$shop = array();
$shop = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25,
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
echo json_encode($shop);
Whenever i try and access the data using obj.Title I get an undefined message.
$.ajax({
type: "GET",
url: "data.php",
success: jsonDo
});
//JSON DATA = {"Title":"rose","Price":1.25,"Number":15},{"Title":"daisy","Price":0.75,"Number":25},{"Title":"orchid","Price":1.15,"Number":7}
function jsonDo(data) {
var obj = jQuery.parseJSON(data);
alert(obj.Title)
}
I was wondering how I can access the keys in the JSON and display the data?
Thanks a million.
var obj = jQuery.parseJSON('{"Title":"rose","Price":"1.25","Number":"15"}');
alert(obj.Title);
This work. Check difference in your code.
OK this is more correct:
var obj = [
{"Title":"rose","Price":"1.25","Number":"15"},
{"Title":"daisy","Price":"0.75","Number":"25"},
{"Title":"orchid","Price":"1.15","Number":"7"}
];
alert(obj[1].Title);
You have to specify that you are expecting a JSON object by informing the dataType: "JSON" parameter to the ajax() function, so you will not have to parse the data.
There seems to be some PHP errors in your code. This could cause php to raise a notice / warning which might break the Json output and cause javascript to raise errors when trying to parse it.
The correct jSon output should have been
[{"Title":"rose","Price":1.25,"Number":15},{"Title":"daisy","Price":0.75,"Number":25},{"Title":"orchid","Price":1.15,"Number":7}]
Since it is in an array, the JS should be:
$.ajax({
type: "GET",
url: "data.php",
success: jsonDo
});
function jsonDo(data) {
var obj = jQuery.parseJSON(data);
alert(obj[0].Title)
}
You should just use jQuery's $.getJSON method:
$.getJSON('data.php',function(data) {
alert(obj.Title);
});
try obj[0]["Title"] or obj[0].Title
dont forget that you have nested a lot of arrays and that yoyu need to access them that way again.

Sending an array to a function in codeigniter

I have the following codes which sends an array to the function /chat in codeigniter
$(document).ready(function () {
$('#submit').live('click', function (eve) {
eve.preventDefault();
$.ajax({
url: "http://localhost/fq/index.php/splash/chat/",
type: 'JSON',
data: a,
success: function (html) {
alert(html);
}
});
});
Let us assume that array a contains names of people only. ( John, James, Smith)
I want to be able to retrieve the all the values from the array in the function chat.
How can it be done?
Edit:
I need to retrieve the values from the JSON encoded array in this function (codeigniter)
public function chat()
{
//code to retrieve values
$this->load->view('chat');
}
data: a,
should
data: $('form').serialize(), // 'form' may need to replace by your form selector
But if you want to send only an array like ['John', 'James', 'Smith']... then yours is just fine.
And use dataType: 'json' as configuration if you're expecting Object as response or dataType: 'html' for Html response.
Setting dataType will release you from extra parsing effort.
You should do it via JSON, by changing
type: POST
into
type: JSON
Take a look at: http://api.jquery.com/jQuery.getJSON/
Also I agree with thecodeparadox above, it's simply better practice

jQuery Connected Sortable Lists, Save Order to MySQL

Hoping that using something like this demo it is possible to drag items within and between two columns, and update their order either live or with a "save" button to MySQL. Point being that you can make changes and return to the page later to view or update your ordering.
http://pilotmade.com/examples/draggable/
Doing it for just one column is fine, but when I try to pass the order of both columns, the issue seems to be passing multiple serialized arrays with jQuery to a PHP/MySQL update script.
Any insight would be much appreciated.
If you look below, I want to pass say...
sortable1entry_1 => 0entry_5 => 1
sortable2entry_3 => 0entry_2 => 1entry_4 => 2
EDIT: This ended up doing the trick
HTML
<ol id="sortable1"><li id="entry_####">blah</li></ol>
jQuery
<script type="text/javascript">
$(function()
{
$("#sortable1, #sortable2").sortable(
{
connectWith: '.connectedSortable',
update : function ()
{
$.ajax(
{
type: "POST",
url: "phpscript",
data:
{
sort1:$("#sortable1").sortable('serialize'),
sort2:$("#sortable2").sortable('serialize')
},
success: function(html)
{
$('.success').fadeIn(500);
$('.success').fadeOut(500);
}
});
}
}).disableSelection();
});
This is the PHP query
parse_str($_REQUEST['sort1'], $sort1);
foreach($sort1['entry'] as $key=>$value)
{
do stuff
}
what I would do is split them up
data :
{
sort1:$('#sortable1').sortable('serialize'),
sort2:$('#sortable2').sortable('serialize')
}
then when you post you can get the request and set them as needed, I hope that makes sense
so what I do is this
parse_str($_REQUEST['sort1'],$sort1);
foreach($sort1 as $key=>$value){
//do sutff;
}

Categories