Show a JSON array into a JQPLOT (Beginner) - php

I'm just a beginner and I want to show data from my database (MySQL) and display it in a line chart using JQPLOT. I have a PHP file that takes the data from the database and converts it into a JSON array which, as I understand, is what JQPLOT needs to display it properly.
The problem I'm having is that I've never used AJAX before.
The JQPLOT website gives me this code:
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:"json",
success: function(data) {
ret = data;
}
});
return ret;
};
// The url for our json data
var jsonurl = "./jsondata.txt";
var plot2 = $.jqplot('chart2', jsonurl,{
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I don't understand the second half of this code, but I want to know how I can incorporate my PHP file (that contains the json array) into this code and display a line chart. Or maybe if anyone has a simpler code where I can implement the PHP file and still able to show the line chart? Im just very new at this, please help.

The first part loads the data and the second part displays the data.
Now to explain further if you have downloaded jQPlot you will see there is one file called as jSonData.txt which contains an array, in the second part you use that array to display the chart.
You can do it differently, say in your PHP code you load the data from your database(MYSQL) and send it back as JSON, just pass this JSON retrieved to the jQPlot
the above code in that case will look like this:
var plot2 = $.jqplot('chart2', myJsonDataRetrievedFromDB,{

Related

Json result into PHP variable

I have a script that calls dat from my table and returns it in JSON format. How do I echo out the var nps and data as php variable.
My script:
$.ajax({
type: "POST",
url: "../charts/1-2-4-reports_nps.php?TAG=<?php echo $_SESSION['SectionVar'];?>&From=<?php echo $_SESSION['StartDate'];?>&To=<?php echo $_SESSION['EndDate'];?>",
cache: false,
success: function(data){
var nps = data[0].name;
console.log(nps);
var data = data['data'];
console.log(data);
$("#div1").append($("<div/>", { id: "div2", text: nps }));
}
});
My Json returns:
[{"name":"nps","data":[35]}]
Something like $nps = data['nps'] and echo the result of $nps.
I think initially you were confused about the contexts your code is running in. var nps = data['nps']; is JavaScript. It runs in the browser, and it runs after the page is loaded.
$nps by contrast is a PHP variable, and PHP runs on the server, and it runs before the page is loaded. In fact it is the PHP which creates the HTML, CSS, Script etc which is then downloaded to the browser. After that is downloaded, the JavaScript executes separately.
There is no direct connection between the two languages, other than you can use PHP to generate JavaScript (just like you use it to generate HTML).
Once you understand that, then you realise that to display your nps variable further down the page, you need to use JavaScript to manipulate the web page and insert the data.
The first issue to resolve with that is that the data being returned from the server is coming back as a string that looks like JSON, but not an actual JSON object. You can add
dataType: "json"
to your ajax options, and that tells jQuery to treat the returned data as an object instead of a string.
The next problem is that data is an array, containing a single object, and you were trying to read it like it was just a plain object.
So you get data out of it, and, as you requested, display each value in a new div which gets inserted into an existing div, you can do the following :
function success(data)
{
var nps = data[0].name;
var dt = data[0].data[0];
$("#div1").append($("<div/>", { id: "div2", text: nps }));
$("#div3").append($("<div/>", { id: "div4", text: dt }));
}
You can see a working example (with simulation of the ajax call, but using the correct data structure) here: https://jsfiddle.net/yukot05x/5/

Extracted json url from example.com/myjsonsql.php to jquery mobile fail to return value

i am a new php developers i was trying to create a simple system where i use php to extract database from mysql and use json in jquery mobile.
So here is the situation,
I've created a custom .php json (to extract data from mysql) on my website and i've successfully upload it onto my website eg: www.example.com/mysqljson.php
This is my code extracting mysql data `
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
Which in returns gives me the following json # http://i.imgur.com/d4HIxAA.png?1
Everything seems fine, but when i try to use the json url for extraction on jquery mobile it doesn't return any value.
i extract the json by using the following code;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
The json.id # #current_temp and json.id.username # #current_sum dint return any result on my jquery mobile page.
I suspected i didn't extracted the json url correctly, but im not sure, could anyone help me identify the problem?
Thank you.
jsonp expects a callback function to be defined in the json being retrieved - for ecample see here.
Your data print screen is actually plain old fashioned json, not jsonp.
So I see 2 options:
change the php data to render jsonp (this assumes you have control over data source).
change your jquery request to expect plain old fastioned json (this assumes client and server are on same domain, otherwise CORS error happen), e.g,,
$.get(forecastURL)
.then(function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
})
.fail(function(e) {
console.log(e.message);
});
First of all, you don't have to use jsonp to retrieve JSON. You could just do a simple Ajax Call. jQuery convert automatically your json string to a json object if your HTTP response contains the good Content-Type. And you did this good in your PHP call.
I think your problem comes from your json data analysis in your javascript success callback. The json generated is an array containing some user objects. In your code you don't work on one item of the array but you directly call .id or .username on the array. So javascript give you undefined values.
Here is an example displaying the data for the first item (index 0) of your json array. You have after that to choose for your own purpose how to treat your array objects but it's an example:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}

Echoing PHP within ajax success call

Basically I have two sliders on my page, whenever their value is adjusted they reference a script which returns a JSON array holding values about products which meet the new criteria.
In my success callback I want to call my PHP class which renders my view to the screen ( I am aware that I could probably achieve this effect in Javascript, but I already have a PHP class built which handles all of the required logic, so it would be simpler if there was a shortcut.
My AJAX method looks like this:
function update_results(values)
{
var json = JSON.stringify(values);
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?cache=" + (new Date().getTime()),
data: { query : json },
cache: false,
success: function(data) {
// Remove the old data from the document
$('tr').remove();
// Build the new table rows using the returned data array
$('table').append("<?php Table t = new Table(data); ?>");
}
});
}
Calling my Table constructor builds everything I need just by passing the JSON array I recieve back from my AJAX call, however nothing is being rendered to the screen at the moment - is there any way of doing this?
PHP runs on the server...JavaScript on the client... "<?php Table t = new Table(data); ?>"
does not magically work with the Ajax call. The server should be returning the table when you make the Ajax call.

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

What is correct way to pass data through .ajax() to a PHP script?

I'm attempting to send a piece of data through jQuery .ajax() to a PHP script which will then be loaded into a div container. The PHP script will then run with this piece of data and its contents will be returned into the aforementioned div container.
Initially, I wrote this piece of code (shown below) which successfully added the correct elements upon a click but wasn't able to name them correctly because it didn't doesn't pass the count_bucket variable to the PHP.
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP));
return false;
});
I then altered the code to this (shown below) in attempt to pass the count_bucket variable to the PHP script.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.ajax ({
type: "GET",
url: "create_new_bucket.php",
data: var count_bucket,
dataType: "json",
async: false,
}).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
The PHP file create_new_bucket.php looks like this:
<?php
include_once "test_functions.php"; // include functions page
$i = $_GET["count_bucket"];
drawBunchNew($i);
?>
I'm unclear which aspect of the .ajax() is incorrect. I suspect I'm not collecting the variable correctly in the PHP or I'm using the incorrect syntax to pass it to the PHP file. If anyone could help me identify the error, I would greatly appreciate it.
*UPDATE******
Thanks Tejs & Tandu. I'm clear on how to structure the data now but I still am having trouble getting the whole bit of jQuery to work. I took Tandu's suggestion to use .load() instead and have changed my PHP to use POST to pull the data but it's still not working correctly.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.load ("create_new_bucket.php", {count_bucket: count_bucket}, }).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
And the PHP is:
<?php
include_once "test_functions.php"; // include functions page
$i = $_POST["count_bucket"];
drawBunchNew($i);
?>
Final working jquery I used (final PHP is same as above):
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP, {count_bucket: count_bucket}));
return false;
});
The data property of the ajax request is going to be an object; think of it like JSON:
{ data: var response }
Is not valid JSON. However, you can do something like this:
data: { myKey: 'myValue', myKey2: 'myValue2' }
Or in your situation:
data: { count_bucket: 4 }
And it will send the data contained in the data property to your server as part of that name value set.
Data for ajax in jQuery needs to be passed as a query-string formatted string ('key[]=value&key[]=value&key[]=value') or as a json object ({key: [value, value, value]}). I believe that the var you have there will be a syntax error. You also need to specify the key, so either data: {count_bucket: count_bucket} or data: 'count_bucket=' + count_bucket should do.
Note that it is not necessary to use .ajax(). It's usually a bit nicer to use .load(), .post(), and .get(). In your case, .load() should work fine. Pass the data as the second argument.
Why do you not want the request to be asynchronous? Note that dataType is the data type of the return value, not of what you are sending. Are you receiving json? jQuery can also usually guess this correctly, and if you set the header on the php side, it helps a lot. The GET type is also the default.
Final note: when using .load(), if you pass the data as a string it will use GET, but if you pass it as an object it uses POST.

Categories