I've seen some questions about this already but I still couldn't clear the fog around this...
I have this sql statement to get data:
<script type="text/javascript">
<?php
$query = "SELECT rel_id, SUM(suma) FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]'";
$result = mysql_query ($query);
while($row = mysql_fetch_array($result)){
echo 'var some_data = ' . json_encode( $viso );
}
?>
Next is the js part:
$(function () {
$.plot($("#placeholder"), [some_data],
{
series: {
pie: {
show: true
}
},
legend: {
show: false
}
});
});
</script>
I was thinking I could reach the data in some_data and use it to display it in the pie chart, unfortunately this is not the way to go.
Any help and suggestions are greatly appriciated ! :)
The most likely problem is that your numeric data is being interpreted as a string.
From the API.txt:
Note that to simplify the internal
logic in Flot both the x and y values
must be numbers (even if specifying
time series, see below for how to do
this). This is a common problem
because you might retrieve data from
the database and serialize them
directly to JSON without noticing the
wrong type. If you're getting
mysterious errors, double check that
you're inputting numbers and not
strings.
So either force your data to numeric types on the PHP side, or do it in javascript, perhaps with .Number(some_data)
Related
I try to learn JS together with jQuery and Ajax, and until now it was more or less painless, but now I faced myself with some obstacles about getting result from called PHP script, initiated by Ajax. What is my problem here? I have a MySQL table and I wanted to pull some data from JS by Ajax call. I tested my query to check is it correct and make result and with same query I built PHP script. Here is my JS file:
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<script>
callphp(12,14);
//
function callphp(par1, par2) {
$.ajax({
type: "POST",
url: "_ajax2php2.php",
cache: false,
dataType: "json",
data: { "po1": par1, "po2":par2 },
success: function(data, status, jqXHR){
jss=JSON.stringify(data);
alert(jss);
//
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " +data[key] + "\n"); }
}
alert(strBuilder.join(""));
},
error: function(data) {
alert( "params error" );
}
});
// end of JS
and here is my PHP script:
<?php
$eol="<br/>";
$uuu= isset($_POST['po1']) ? $_POST['po1'] : '';
$zzz= isset($_POST['po2']) ? $_POST['po2'] : '';
$con=mysqli_connect("localhost","root","some_password","mydbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Fail to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mydbase");
$query4 = "SELECT * from mytable WHERE uc_id='$uuu' AND pr_id='$zzz' ";
$result4 = mysqli_query($con, $query4);
$row4= mysqli_fetch_assoc($result4);
if(mysqli_num_rows($result4) > 1) {
while($row4[]=mysqli_fetch_assoc($result4)) {
$data = $row4; }
}
else
{$data=$row4;}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
/* free result set */
mysqli_free_result($result4);
mysqli_close($con);
//end of php
?>
and it seems that it works good when PHP query return just one record, if there are 2 or more then I'm unable to "dismantle" JSON object by this JS code, because for example if my query return 3 records, in alert it appears like
Key is 0, value is [object Object]
Key is 1, value is [object Object]
Key is name_of_field1, value is 1
Key is name_of_field2, value is 12
Key is name_of_field3, value is 2
Key is name_of_field4, value is 1
Key is name_of_field5, value is 14
Key is name_of_field6, value is 2015-09-10
and I need to be able to get each particular record fields of each record in order to fill with it some HTML table. How to write this part of code that resolve JSON response consist of two or more records made by PHP? I tried examples I found here but no one met my needs. Thanks.
In your while loop after the DB query, you are just overwriting the value for $data with every iteration. I would suggest not having different logic for cases with one row in result set vs. more than one row, as this does nothing but add complexity to your code. Just return an array every time and you will be better off. Your code around the query might look like this:
$data = array();
$result4 = mysqli_query($con, $query4);
if($result4) {
while($row = mysqli_fetch_assoc($result4) {
$data[] = $row;
}
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
This simplifies this section of code and will also simplify the client-side code since now you can write it to simply expect to work with an array of objects in all cases.
This means that in javascript your code might look like (ajax success handler code shown):
success: function(data, status, jqXHR){
// data is an array, with each array entry holding
// an object representing one record from DB result set
var recordCount = data.length;
console.log(recordCount+' records returned in response.');
// you can iterate through each row like this
for(i=0;i<recordCount;i++) {
// do something with each record
var record = data[i];
// in this example, I am just logging each to console
console.log(record);
// accessing individual properties could be done like
console.log(record.name_of_field1);
console.log(record.name_of_field2);
// and so on...
}
}
You should get in the habit of using console.log() rather than alert() or similar for debugging your javascript, as alert() actually interrupts your javascript code execution and could introduce problems in debugging more complex javascript (particularly when there are asynchronous activities going on). Using the javascript console functionalty built into your browser should be fundamental practice for any javascript developer.
I have googled and looked at SO for a while now and can't seem to figure this out. The only requirement Im trying to meet is to return a properly formatted javascript array that contains the results of the sql statement.
I.E.
Given a query:
SELECT NUMBERS FROM TABLE
And results:
NUMBERS
1
2
3
I would like to eventually get back an array like so
["1","2","3"]
Please help me understand where I am going wrong
Here is my php code
<?php
$mysqli = new mysqli("local.host.com", "user", "pass", "db");
$sql = "SELECT DISTINCT NAME FROM table";
$result = $mysqli->query($sql);
while($row = $result->fetch_array())
{
$rows[] = $row['NAME'];
}
echo(json_encode($rows));
$result->close();
/* close connection */
$mysqli->close();
?>
Here is my javascript:
function GetCards()
{
var cardarray = new Array();
//alert('test');
$.getJSON('getcardlist.php', function(data)
{
for(var i=0;i<data.length;i++)
{
cardarray.push(data[i]);
}
//return cardarray;
});
return cardarray;
}
EDIT:
Little more information, Im trying to setup an autocomplete list for jquery ui, this is my setup for the autocomplete widget.
var list = GetCards();
$( "#name" ).autocomplete({
source: list,
minLength: 2
And this is the error Im getting from chrome console
Uncaught TypeError: Cannot read property 'label' of null
GetCards is returning an empty array -- which is what you're passing on to the Autocomplete widget -- and causing the widget to throw up the TypeError exception. To pass on the populated array, move the code that instantiates Autocomplete into your getJSON success callback (I'm not sure you even need to loop through data -- unless you need to actually transform its contents in some way):
$.getJSON( 'getcardlist.php', function( data ) {
$( "#name" ).autocomplete( {
source: data,
minLength: 2
} );
} );
Alternatively, consider using Autocomplete's shorthand for loading directly from the data feed (see passing source as a string). However, this approach may require some additional work on the server-side to filter down the list as the user types -- if you want that behavior.
you have to use $.each to get the data
$.getJSON('getcardlist.php', function(data)
{
$.each(data, function(key, val) {
cardarray.push(val);
});
//return cardarray;
});
I'm building a search function to retrieve XML data for a google map.
In addition to that, I want to display how many results were actually found.
I thought about doing an echo inside the actual document, however that might mess with my marker data. How would I take a PHP variable and retrieve it in Jquery after a success call?
If my PHP looked like this:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
And Jquery like this:
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});
Might find it easier to create array in php and send JSON. At client is easy to loop over response object/array
$output=array('status'=>'', 'results'=>array());
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if( $num_rows){
$output['status']='ok';
/* push row data to $output['results'][]; in while loop*/
}else{
$output['status']= 'No results';
}
echo json_encode( $output);
Then in jQuery:
success:function( data){
if (data.status != 'No results' ){
/* count array length*/
var count= data.results.length;
/* loop over data.results array*/
}
}
/* change dataType to "json"*/
I forgot about count and added it in jQuery...can also add a count property to the $output php array and use $num_rows to populate
Just trying out a JSON example for you, this has echo but you can do complex things with it?
Not sure if that is what your after? I get that you don't want to do echo on each variable, and you wont if using JSON.
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
You see, what AJAX gets on success is an html code. If you AJAX a complete html page you will get it back, starting with <html> and ending with </html>. You can just make a special markap on your return html data, like [sepcial_info : 'INFO'] or somthing and then just to filter it.
Okay, I needed a bit to decipher your question, probably I'm still wrong, let's try:
What you try to do is not technically possible with what you have in mind. In short: If you do one Ajax request, you return one response. The moment the success function is called, your PHP script is already gone. So you can only pass one return value.
However what you can do is, that you make that return value a nested one, e.g. containing two parts:
The XML document you already returned
The count
That is probably your solution. If you ask how, I would add the count as a namespaced value to the XML and then process it with javascript.
As you have not shown any code here, I can not give a quick example (and I leave that as a pointer for your future questions) for your case. Add a namespace element, like an attribute is pretty simple with DOMDocument in PHP.
I've got an array with 6000 plus user names that I've pulled from MySQL like this:
$pop = mysql_query("SELECT * FROM import_student");
while ($r = mysql_fetch_assoc($pop)) {
$student_array[] = $r['studentfirstname']." ".$r['studentlastname'];
}
$big_array = json_encode($student_array);
I then pass this array to JS and initialize my auto complete function like this.
<script>
$(document).ready(function() {
var availableTags = <?php echo $big_array; ?>;
console.log(availableTags);
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
This works great when I limit the SQL results to 0,10, but when I don't limit and I get the 6000 or so usernames into the array, the autocomplete doesn't work. I get this error in firebug:
value is null
return matcher.test( value.label || value.value || value );
Anyone know what I'm doing wrong here? Like I said, this works when I limit the results. Something about having a large array? IDK.
I tested before (some 2k items for 1-2 letters) and it has to do with the parsing as well as rendering your large result set to the DOM.
You should reduce results by limiting the possibilities. You can do this by raising your minimum characters to at least 3-4.
Also, you should do a little caching on your result set instead of having jQuery re-parse it every entry. For example, I searched for ad. I should store in an object the results under the key ad.
var cache = {
'ad' : [...results...],
'adder' : [...results...],
...and so on...
}
When the autocomplete queries for ad again, it should search for the key in the cache first and return the results if it exists. You should have a caching logic to avoid stale data. Afaik, jQuery has simple caching demo in autocomplete.
i retrieve your same problem... you could use autocomplete using instead all array, a part creted by another script.. something like:
$('#tags').autocomplete({
source : "aScript.php",
};
and aScript.php:
$autocompleteValue = $_GET["term"];
$pop = mysql_query("SELECT * FROM import_student WHERE 'studentfirstname' LIKE '$autocompleteValue%'");
while ($r = mysql_fetch_assoc($pop)) {
$student_array[] = $r['studentfirstname']." ".$r['studentlastname'];
}
return json_encode($student_array);
I'm creating a contest sign-up page for our annual math competition at my school. It requires some AJAX like behavior when you click and select an item in a dropdown list.
I've gotten an event to fire when I select something in the dropdown (I'm currently showing an alert box):
<script type="text/javascript">
$(function() {
$("#student").change(onStudentChange);
});
function onStudentChange()
{
alert("Dropdown changed");
}
</script>
What this needs to do, is do an asynchronous call to the server to get a list of contests that student is currently registered for.
I know I need to do a jquery ajax call. So I think my onStudentChange() function would look like this:
$.ajax({
type : 'POST',
url : 'get_registered_events.php',
dataType : 'json',
data: {
studentid : $('#student').val()
},
success : function(data){
// Do something once we get the data
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// Display error
}
});
return false;
});
So I went ahead and created the get_registered_events.php, which I want to return the events the student is registered for.
My problem is, I'm not experienced with PHP and I'm having difficulty figuring out how I would return the data the database gave me to this ajax call in the JSON format. Another snag I have is our school is using a very old version of PHP so I have to use this PEAR JSON library.
Here is that PHP file I'm having trouble with:
<?php
if (!empty($_POST['studentid')) {
include_once('JSON.php');
$json = new Services_JSON();
$dbconn = pg_connect("host=somehost dbname=somedb user=someuser password=somepassword") or die('Could not connect: ' . pg_last_error());
$query = 'SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id';
$contests = pg_query($query) or die('Query failed: ' . pg_last_error());
// Here I need to convert the rows of $contests (contest.id, contest.title), into JSON and return it to that ajax call.
}
?>
So my question is, how do I convert $contests (its rows), into JSON (contest.id, contest.title), and return that back to the ajax call that will make it above.
If anyone could point me in the right direction I would really appreciate it.
$myarray = array();
while ($row = pg_fetch_row($contests)) {
$myarray[] = $row;
}
echo json_encode($myarray);
I think this has to work.
You can also do
$resultArray = pg_fetch_all($result);
echo json_encode($resultArray);
This will encode each row as a JSON Object with the column name as the key and put all the rows in a JSON Array
Only do this if you know for sure that your query will return a small set of data. If you are worried about the size of data, use #atif089's but use pg_fetch_assoc() instead of pg_fetch_row()
From postgresql 9.3 you can get result directly as a json array with json_agg:
With p as (
SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id
)
select json_agg(p) as json from p;
http://www.postgresql.org/docs/9.3/static/functions-aggregate.html