plotting Graph with flot - flot

I want to plot graph using flot and mysql but an exception occurs
getData.php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
echo "[";
while($result = mysql_fetch_array($sql))
{
//print_r($result);
echo "[".$result['msgCount'].",".$result['From_user']."]"."\n";
}
echo "]";
And for plotting
<div id="plotarea" style="width:600px;height:300px;">
<script type="text/javascript">
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.ajax({
url:"getData.php",
type:"post",
success:function(data)
{
alert(data);
$.plot($("#plotarea"),data,options);
//alert(data);
}
})
</script>
</div>
What is wrong with this code?
Next I want to plot graph with one of the axis is time.

$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
while($result = mysql_fetch_array($sql))
{
$user_data[] = array($result['msgCount'],$result['From_user']);
}
echo json_encode($user_data);
The above will eliminate issues with comma separation (which, from what I can tell, you never resolved).
Next, the javascript:
<script type="text/javascript">
$(function () {
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.get("getData.php", function(data){
$.plot($("#plotarea"),data,options);
},
json);
});
</script>
Notice that I changed $.ajax to $.get, since you weren't passing any data from the page to the script, a post is not necessary. And if you use $.get, all of the setting names are assumed.
Also notice that I pulled the script out of the html and put it within the jquery window.onload syntax : $(function () { . This would go in the head of your html.
From what I can tell, you aren't really in need of ajax, since you didn't define any sort of event that would trigger the $.ajax function. It looks like you are using ajax to call a script when you could just put the script into the same script that loads the page, like:
<?php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
while($result = mysql_fetch_array($sql))
{
$user_data[] = array($result['msgCount'],$result['From_user']);
}
?>
<script type="text/javascript">
$(function () {
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
var userposts = <?php echo json_encode($user_data); ?>;
$.plot($("#plotarea"),userposts,options);
</script>
<style type="text/css">
#plotarea {
width: 600px, height: 300px;
}
</style>
</head>
<body>
.....//Put whatever before the div
<div id="plotarea"></div>
.....//Finish up the page.

Firstly it looks like the JavaScript list you are creating with your PHP code isn't separating each data point list item with a comma separator.
According to the jQuery $.ajax documentation the first argument passed to the success function is the data returned from the server, formatted according to the 'dataType' parameter. You haven't provided a dataType parameter. The docs say it will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response if no dataType has been specified.
I'm guessing the data getting passed to the plot function is a plain old string instead of a JavaScript list object as expected by Flot. Adding a dataType: 'json' option to your $.ajax call should fix this up.

What you're trying to output is a json document in the php side, which will directly be parsed to a java script array (either manually or automatically by libraries like jquery)
So there is no need to print json in php instead you can easily feed data into a php array and use the json_encode function to easily convert it to a json string.
A small example could help
you were trying to output
echo "[".$result['msgCount'].",".$result['From_user']."]"."\n";
which in java script [] = array and you are creating [[]] = array inside array.
But when the array is big, it's cumbersome to echo in php.
What do we do.
An array structure is similar in php.
You will need to add data into php as an "array inside array"
eg: php array(array(1,2,3)) = [[1,2,3]].
How to map it to json?
easy==> echo json_encode(array(array(1,2,3));
Cheers

Related

Typed.js initialize with existing text and then loop it

I'm working with typed.js to get some words typed. I would like the first word to be showing when the page loads and start the loop from there. In order to get this result I've just placed "nice" in between the span tags, did this the trick.
But... When looking to the following codepen, you can see that the first loop is correct. When the second loop starts, the first word (nice) is not being typed but just appears and disappears quickly. I could really use some help to fix this. Any thoughts?
var typewriter = $('.typewriter');
if(typewriter.length) {
function initTypewriter() {
var typed = new Typed(".typewriter", {
strings: $(".typewriter").attr("data-typewriter").split("|").map(function(e) {
return e
}),
typeSpeed: 80,
backSpeed: 75,
startDelay: 1000,
backDelay: 2000,
loop: !0,
loopcount: false,
showCursor: false,
callback: function(e){ } // call function after typing is done
});
};
initTypewriter();
};
<h2>A <span title="nice, clean, good" class="typewriter" data-typewriter="nice|clean|good">nice</span> example</h2>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.6/typed.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
CodePen Link
Kind regards
I realise this question is over 2 years old now, but I came across this issue today and couldn't find a solution either so put together a workaround.
Essentially, create 2 instances of Typed JS.
The first removes the existing text and uses the onComplete method to remove itself, clear the text content from the DOM and then setup the second instance to do the actual loop.
My example has no dependencies outside of Typed JS, but you could adapt to jQuery selectors, etc, pretty easily.
Demo here: https://codepen.io/jneale/pen/pogyzXK
HTML
<h1>Hello <span class="typed-replaced">world</span></h1>
Javascript
function setupTypedReplace() {
// the text node to type in
var typed_class = 'typed-replaced';
// the original text content to replace, but also use
var replace_text = 'world';
var options = {
strings: ['there', 'buddy', replace_text], // existing text goes at the end
typeSpeed: 80,
backSpeed: 60,
backDelay: 1000,
loop: true,
smartBackspace: false,
cursorChar: '_',
attr: null
};
// clear out the existing text gracefully then setup the loop
new Typed('.' + typed_class, {
strings: [replace_text, ''],
backSpeed: options.backSpeed,
backDelay: options.backDelay,
cursorChar: options.cursorChar,
attr: options.attr,
startDelay: 700,
onComplete: function (t) {
// existing text has now been removed so let's actually clear everything out
// and setup the proper Typed loop we want. If we don't do this, the original
// text content breaks the flow of the loop.
t.destroy();
document.getElementsByClassName(typed_class)[0].textContent = '';
new Typed('.' + typed_class, options);
}
});
}
setupTypedReplace();

Load "on the fly" code with requirejs

I'm trying to create an online interactive js programming test-bed. I have a code window and a target iframe where the code gets loaded to execute. I wrap the code in html and load it into the iframe. The problem is that the code I want to be testing is normally loaded via requirejs using a data-main parameter. It appears that the code needs to be loaded from a separate file so that I can't include it in the html itself.
What works but doesn't help me is creating a file on the server to use as the target of the data-main parameter and sending html to the iframe that requires requirejs and then loads my code.
html:
<html>
....
<script type="text/javascript" src="lib/requirejs/require.js" data-main="src/requireConfigTest"></script>
....
</html>
contents of requireConfigTest.js:
/*globals require*/
require.config({
shim: {
},
paths: {
famous: 'lib/famous',
requirejs: 'lib/requirejs/require',
almond: 'lib/almond/almond',
'famous-polyfills': 'lib/famous-polyfills/index'
}
});
// this is the injection point where the dynamic code starts
define(function (require,exports,module) {
var Engine = require("famous/core/Engine");
var Surface = require("famous/core/Surface");
var mainContext = Engine.createContext();
var surface = new Surface({
size: [100, 100],
content: "Hello World",
classes: ["red-bg"],
properties: {
textAlign: "center",
lineHeight: "20px"
}
});
alert('hi');
mainContext.add(surface);
});
//this is the end of the dynamic code
This requires writing the dynamic code back to the server, not a reasonable solution. I'm trying to implement something like this...
html:
<html>
....
<script type="text/javascript" src="lib/requirejs/require.js"</script>
<script type="text/javascript">
/*globals require*/
require.config({
shim: {
},
paths: {
famous: 'lib/famous',
requirejs: 'lib/requirejs/require',
almond: 'lib/almond/almond',
'famous-polyfills': 'lib/famous-polyfills/index'
}
});
// this is the injection point where the dynamic code starts
define(function (require,exports,module) {
var Engine = require("famous/core/Engine");
var Surface = require("famous/core/Surface");
var mainContext = Engine.createContext();
var surface = new Surface({
size: [100, 100],
content: "Hello World",
classes: ["red-bg"],
properties: {
textAlign: "center",
lineHeight: "20px"
}
});
alert('hi');
mainContext.add(surface);
});
//this is the end of the dynamic code
</script>
This fails with the message:
Uncaught Error: Mismatched anonymous define() module: function
(require, exports, module) {...
My hope is to either find a way to reformat the code above in the second script tag or find a way to pass the actual contents of requireConfigTest.js via data-main instead of passing the name of the file to load.
Any help here would be greatly appreciated.
Since you are not actually defining a module with your define call, you could just use require:
require(["famous/core/Engine", "famous/core/Surface"], function (Engine, Surface) {
var mainContext = Engine.createContext();
// Etc...
You can think of define as being a require call which additionally defines a module. The way you are using define it is defining a module that does not have a name because you did not give it a name (which is generally the right thing to do) but it is not loaded from a .js file. When you don't give a name to a module as the first argument of define, RequireJS assigns a name from the .js file it loads the module from.
Another thing to keep in mind is that require schedules its callback for execution right away. (The callback is not executed right away but it scheduled for execution right away.) Whereas define does not schedule anything. It just records the callback and then when a require call (or something equivalent) requires it, the callback is executed.

Does Knockout.mapping make ALL nested objects observable?

I am trying to map all possible nested objects of a JSON object so that each and every one is becomes an observable. I was under the impression that the use of ko.mapping.fromJS would result in all objects and their objects becoming observable. However, I am not seeing that happen.
If you look at the JSFiddle and code below you will see that the span initially displays the value "Test". My intention is for the button click to update the viewModel with the contents of stuff2, which should change the span's value to "Test2". However, the button click does not update anything.
http://jsfiddle.net/Eves/L5sgW/38/
HTML:
<p> <span>Name:</span>
<span data-bind="text: IntroData.Name"></span>
<button id="update" data-bind="click: Update">Update!</button>
</p>
JS:
var ViewModel = function (data) {
var me = this;
ko.mapping.fromJS(data, {}, me);
me.Update = function () {
ko.mapping.fromJS(stuff2, {}, windows.viewModel);
};
return me;
};
var stuff = {
IntroData: {
Name: 'Test'
}
};
var stuff2 = {
IntroData: {
Name: 'Test2'
}
};
window.viewModel = ko.mapping.fromJS(new ViewModel(stuff));
ko.applyBindings(window.viewModel);
Is it just that I have to make use of mapping options to have the nested objects be made observable? If so, what if the JSON object is so vast and complex (this one obviously isn't)? Can some recursive functionality be used to loop through each object's nested objects to make them all observable?
Modifying the Update function as below will work.
me.Update = function () {
ko.mapping.fromJS(stuff2, {}, windows.viewModel);
};

Is it possible to get URL parameters in JavaFX?

I'm building a JavaFX application which will run in browser.
Is it possible to get the app URL, like localhost/Java/MyApp/dist/index.html?x=123, in JavaFX?
I need to receive that "x" parameter.
You can get url parameters from the page: Get escaped URL parameter
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
Once you have the parameters you can pass the parameters to the embedded JavaFX application using the JavaFX deployment toolkits DTJava.js functions. See section 7.3.3 Pass Parameters to a Web Application of the JavaFX deployment guide.
<!-- Example 7-7 Pass Parameters to an Embedded Application -->
<head>
<script type="text/javascript" src="http://java.com/js/dtjava.js"></script>
<script>
function deployIt() {
// deployment guide sample modified by me to show
// getting the zipcode parameter from the url instead of hardcoding it.
//var zipcode = 95054;
var zipcode = getURLParameter("zipcode");
dtjava.embed(
{ id: "myApp",
url: "Map.jnlp",
width: 300,
height: 200,
placeholder: "place",
params: {
mode: "streetview",
zip: zipcode
}
},
{ javafx: "2.1+" },
{}
);
}
dtjava.addOnloadCallback(deployIt);
</script>
</head>
<body>
<div id="place"></div>
</body>
http://docs.oracle.com/javafx/2/deployment/deployment_toolkit.htm#BABJHEJA
As the JavaFX deployment guide says, to access parameters in the application code, use the getParameters() method of the Application class. For example:
String zipcode = app.getParameters().getNamed("zip");

Passing an object to client in node/express + ejs?

I have a pretty large object that I need to pass to a function in a client script. I have tried using JSON.stringify, but have run into a few issues with this approach - mostly performance related. Is it possible to do something like this in ejs?
app.get('/load', function(req, res) {
var data = {
layout:'interview/load',
locals: {
interview: '',
data: someLargeObj
}
};
res.render('load', data);
});
And in my client script, I would pass this object to a function like so
<script type="text/javascript">
load(<%- data %>); // load is a function in a client script
</script>
When I try this I get either
<script type="text/javascript">
load();
</script>
or
<script type="text/javascript">
load([Object object]);
</script>
In Node.js:
res.render('mytemplate', {data: myobject});
In EJS:
<script type='text/javascript'>
var rows =<%-JSON.stringify(data)%>
</script>
SECURITY NOTE : Don't use this to render an object with user-supplied data. It would be possible for someone like Little Bobby Tables to include a substring that breaks the JSON string and starts an executable tag or somesuch. For instance, in Node.js this looks pretty innocent...
var data = {"color": client.favorite_color}
but could result in a client-provided script being executed in user's browsers if they enter a color such as:
"titanium </script><script>alert('pwnd!')</script> oxide"
If you need to include user-provided content, please see https://stackoverflow.com/a/37920555/645715 for a better answer using Base64 encoding
That is the expected behavior. Your template engine is trying to create a string from your object which leads to [Object object]. If you really want to pass data like that I think you did the correct thing by stringifying the object.
If you are using templating, then it would be much better to get the values in the template, for example whether user is signed in or not. You can get the send local data using
<script>
window.user = <%- JSON.stringify(user || null) %>
</script>
From the server side code, you are sending user data.
res.render('profile', {
user: user.loggedin,
title: "Title of page"
});
Think there's a much better way when passing an object to the ejs , you dont have to deal with JSON.stringfy and JSON.parse methods, those are a little bit tricky and confusing. Instead you can use the for in loop to travel the keys of your objects, for example:
if you have an object like such hierarchy
{
"index": {
"url": "/",
"path_to_layout": "views/index.ejs",
"path_to_data": [
"data/global.json",
{
"data/meta.json": "default"
}
]
},
"home": {
"url": "/home",
"path_to_layout": "views/home/index.ejs",
"path_to_data": [
"data/global.json",
{
"data/meta.json": "home"
}
]
},
"about": {
"url": "/about",
"path_to_layout": "views/default.ejs",
"path_to_data": [
"data/global.json",
{
"data/meta.json": "about"
}
]
}
}
On the EJS side you can loop yourObject like this;
<% if ( locals.yourObject) { %>
<% for(key in yourObject) { %>
<% if(yourObject.hasOwnProperty(key)) { %>
<div> <a class="pagelist" href="<%= yourObject[key]['subkey'] %>"><%= key %></a></div>
<% } %>
<% } %>
<% } %>
For this example [key] can take 'index','home' and 'about' values and subkey can be any of it's children such as 'url','path_to_layout','path_to_data'
What you have is a result like this
[{'re': 'tg'}]
You actually need to loop it. See javascript while loop https://www.w3schools.com/js/js_loop_while.asp
Then, render it in your front end with ejs... i can't help on that, i use hbs

Resources