Unable to validate the JS variable in PHP file - javascript

i have three files index.html , getData.php and data.json
index.html ->
<script type="text/javascript">
function load() {
var jsonData = $.ajax({
url: "getData.php",
type: "GET",
data: {variable: "loadavg"},
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height: 400});
}
</script>
<ul class="list">
<p>Load average <input id="loadAvg" type="button" value="Enter" onclick="load();" /> </p>
</ul>
getData.php ->
<?php
// It reads a json formatted text file and outputs it.
if(isset($_GET["variable"]) == "loadavg"){
$string = file_get_contents("data.json");
echo $string;
// if this works you should see in console 'graph on cosole'
}
?>
data.json ->
{
"cols": [
{"id":"","label":"HostName","type":"string"},
{"id":"","label":"CPU","type":"number"},
{"id":"","label":"Free Avg memory","type":"number"}
],
"rows": [
{"c":[{"v":"lp10b2vapp01,w10"},{"v":21}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":15}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":73}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":60}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":48}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":40}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":36}]}
]
}
when i click on button i was unable to see the output (Graph) ,Kindly look help me
Thanks in advance

Don't use async: false. It's terribly bad practice as it locks the UI thread making the browser look to the user like it has crashed until the request completes. Instead use the async callbacks which $.ajax provides you to update the UI of the page once the request has finished. Try this:
function load() {
$.ajax({
url: "getData.php",
type: "GET",
data: {
variable: "loadavg"
},
dataType: "json",
success: function(jsonData) {
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.ColumnChart($('#chart_div')[0]);
chart.draw(data, {
width: 800,
height: 400
});
}
});
}
Also note that you need to get the value of the parameter in the PHP code as well as checking it exists:
if (isset($_GET["variable"]) && $_GET["variable"] == "loadavg")
{
// code here...
}

Related

Passing SQL results from controller to chart.js

Situation
I would like to pass the count of X from my SQL database from my controller to my view where a chart picks up this data and renders it.
What I have done so far
So far I have the controller code. which gets the count from the table and I am trying to pass this figure back to the chart.
public ActionResult currentPopulation()
{
var dests = db.personal_info.Count();
// return Json(dests, JsonRequestBehavior.AllowGet);
return Content(JsonConvert.SerializeObject(dests), "application/json");
}
I also have the chart (code below) from the view
<script>
var barChartData = {
url: '/Home/currentPopulation',//Local
type: "GET",
dataType: "JSON",
labels: ["A", "B", "C"],
datasets: [
{
// url: '/Home/currentPopulation',//Local
// type: "GET",
// dataType: "JSON",
fillColor: "#26B99A", //rgba(220,220,220,0.5)
strokeColor: "#26B99A", //rgba(220,220,220,0.8)
highlightFill: "#36CAAB", //rgba(220,220,220,0.75)
highlightStroke: "#36CAAB", //rgba(220,220,220,1)
data: [51, 30, 40], //this is the hard coded values which the chart loads
//
},
],
}
$(document).ready(function () {
// new Chart($("#canvas_bar").get(0).getContext("2d")).Bar()
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
</script>
Problem
The problem I have is that, I cannot replace the [51,30,40] for the A,B,C values
which is supposed to come from my controller. I am a bit confused as my action "currentPopulation" is not getting called, and i cannot move the link cause according to the code, the data is picked up from barChartData and assign when the new chart is called.
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
Any help would be appreciated.
If you want your controller to be hit you need to make an ajax request. This ajax call should be done on the action which you want the controller to be called. Button click or so on. Start using console.logs to debug your javascript.
If you want this code to be execute on page open, wrap the ajax call in document.ready function.
$.ajax({
type: "POST",
url: "Home/currentPopulation",
//data: jsonData, if you need to post some data to the controller.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var aData = response.d;
console.log(aData);
//build here your **data** as object wanted by Bar. Colors which you want and so on, options could be empty object {}. I think is possible to call bar without options, you need to read the documentation.
var ctx = $("#myChart").get(0).getContext("2d");
var myBarChart = new Chart(ctx).Bar(data, options);
}
function OnErrorCall(response)
{
alert('error');
}
Here I show you little example how to do it. You can just google chart.js with mvc there is a lot of examples. Check if the url is correctly written I think you should remove the / in the begging.
This is just suggestion.
Also if you had the money and this is serious chart project use highcharts.js ! This is the best library which can work totally offline and gives you really good flexibility.
Usefull links:
ChartJS documentation

How to trigger ajax from a javascript graph

Javascript noob. I have a forced directed graph from spring.js and I want to trigger ajax from it when the user selects a node but I keep getting an error
Uncaught SyntaxError: Unexpected token . this focusses on the line
function GetSpringyNode(node.data.label){
. I have managed to get it to trigger an alert but firing the ajax is tricky. Can anyone tell me how? I think the crux of the matter is how I pass the node.data.label to the ajax. Here is the jsfiddle and below is the code I am trying:
var graphJSON = <%=raw #users.to_json %>;
var graph = new Springy.Graph();
graph.loadJSON(graphJSON);
var springy = jQuery('#springydemo').springy({graph: graph});
jQuery('#springydemo').springy({ graph: graph, nodeSelected: function(GetSpringyNode) {
alert(node.data.label);
} });
function GetSpringyNode(node.data.label){
$.ajax({
url: "/users/show",
type: "GET",
dataType: 'html',
data: {name: d.name},
success: function(result) {
//$('#NodeProfile').html(result);
//$('.bchart-content').html(result);
//Need to parse into html here before included in .bchart-content
addGraph(result);
}
});
}
Change your code to this:
jQuery('#springydemo').springy({ graph: graph, nodeSelected: function() {
GetSpringyNode(node.data.label);
} });
and the GetSpringyNode function to this:
function GetSpringyNode(label){
$.ajax({
url: "/users/show",
type: "GET",
dataType: 'html',
data: {name: label},
success: function(result) {
//$('#NodeProfile').html(result);
//$('.bchart-content').html(result);
//Need to parse into html here before included in .bchart-content
addGraph(result);
}
});
}

CodeIgniter and JSON objects: how to push my data to database?

I have a JS file that manages my data (push the data in my JSON objects, etc), and the classic MVC structure of files from CodeIgniter.
My JS contains my JSON objects that I would like to push in my database. How could I do for it? How can I reach the controller and the model from my JS file? I just can't figure out what is the right process to achieve my goal! And I find nothing similar to my question.
EDIT
The data to push into the database is a part of the entire JSON object.The data to push is, for example: { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 }
In my JS file, I have tried this code:
$("#hexa-btn").on("click", function () {
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: JSONshapes.shapes[0].nodes[0],
cache: false,
success:
function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
And my controller has this function:
function returndata(){
$index = $this->input->post('index');
$x = $this->input->post('x');
$y = $this->input->post('y');
$weight = $this->input->post('weight');
$px = $this->input->post('px');
$py = $this->input->post('py');
$fixed = $this->input->post('fixed'); ;
echo json_encode(array('node'=>$node));
}
I am not sure at all about this function. It seems this is the role of the model to do this job, isn'it?
2nd EDIT So, I tried the solution of #Harish Lalwani, but this time with my array of nodes (not only one). I have the following function in the JavaScript file:
function sendNode(){
var node_url = "/prototype/insert_node";
var data_node = JSON.stringify(JSONshapes.shapes[0].nodes);
$.post(node_url, {'node_data': data_node}, function(data){
console.log(data.index);
});
}
and the following one in the controller (thank to this post):
function insert_node(){
$node_data = $this->input->post('node_data');
$node_data = json_decode($node_data,true);
echo 'Your Data: ' . $node_data[0]['index'];
},
But, when printing the data, I get undefined. The variable data_node is the following (so, is an array):
[{"index":0,"x":50,"y":80,"weight":2,"px":50,"py":80,"fixed":0},{"index":1,"x":189,"y":107,"weight":2,"px":189,"py":107},{"index":2,"x":95,"y":145,"weight":2,"px":95,"py":145}]
Now, I don't know anymore what to do! I find really too few examples. Can anyone put me out of my misery? Thank you very much in advance!!
Trigger this from your Js file. (include jQuery Library)
provide url, post key and value you will receive post parameters at specified URL.
jQuery.post("<URL>", {dataname: datavalue}, function( r ) {
console.log(r);
});
I am also using ajax.
From your Original Post, I see that you have a JSON object. If it is already in object form, there's no need for you to convert it at all. Just assign that JSON to a variable and pass that variable to your ajax data parameter like so:
$("#hexa-btn").on("click", function () {
var json = { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 };
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: json,
success: function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
Using ajax can solve your problem!
$.ajax({
type: "POST",
url: "test.php",
data: yourData,
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have m

Display data from json array using ajax

I have the following code on index page the script contains part of the code that will call the data from test page
<div class="leftbox" id="proddisplay">
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
From test.php i am getting json array that looks like this
[1,2,"text","text2"]
I want to display the json array data in a tabular form and display it inside the div. the view of table should be something like this (it will have some css of its own)
static text: 1
static text: 2
static text: text
static text: text2
static text will be given by me and remains the same throughout however the values of array would change. can anyone tell how i can do so
individually i can display the data from json, but here i also need to put json data in a table and then put that table within a div
First of all you need to encode the array in php before sending to frontend, use json_encode() and then decode it in the success function using JSON.parse() . After just run a loop throught the array.
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
var returneddata = JSON.parse(returndata);
var htmlData= '';
for(var i=0; i<returneddata.length; i++){
htmlData+= 'static text: '+returneddata[i]+' <br>';
}
$('#proddisplay').html(htmlData);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});

pass a php variable from one page to another page with ajax code

I dunno whether my heading is correct or not ??
While loading the shop.php page i have a variable named $curr set with values from GET like "GBP".
$curr = $_GET['cur'];
<script type="text/javascript" src="js/cart.js"></script>
While loading the page the cart.js code calls another page like as follows:
GET http://myshop.com/cart/config-loader.php?ajax=true
The javascript code which loads the config-loader page is as follows:
var config = (function() {
var config = null;
$.ajax({
url: path + '/config-loader.php',
data: {
"ajax": "true"
},
dataType: 'json',
async: false,
success: function(response) {
config = response;
},
error: function() {
alert('Ajax error: Edit the path in cart.js to fix.');
}
});
return config;
}());
I need to get the url passed as:
http://myshop.com/cart/config-loader.php?ajax=true&curr=GBP
so that i can get the $_GET['curr'] value in config-loader.php page.
My aim is to change the value USD to any other value like GBP in config-loader.phpge:
if (!$config['currencyCode']) $config['currencyCode'] = 'USD';
How can i do this in above code ?? Help requested from experts.
Use:
data: {
"ajax": "true",
"curr": <?php echo json_encode($curr) ?>
},

Categories