passing array to javascript - php

I'm working on a project with a classmate, neither of us have previous experience with php and javascript. Our goal is to query a db and store the results in an array then pass that array to a javascript function. My partner wrote this bit of code which works but I was unable to successfully pass the array to our function in our javascript.
First, I tried using a local array which worked out fine when I tested it. Then I tried with the array generated in the above php segment, I've seen this question asked a few times but when I tried implementing some of the suggestions to encode the array as a JSON object that didn't work. Is there something wrong with the way we store the results from the database? I appreciate any help.
<?php
$query = "SELECT * FROM predictions ORDER BY course_no DESC";
$result = $db->query($query);
if ($result and $result->num_rows != 0) {
#$result->data_seek(0);
while($classesArray = #$result->fetch_assoc()) {
extract($classesArray);
echo $course_no . "<br>";
}
#$result->free(); // Release memory for resultset
#$db->close();
echo " <script>var a = json_encode($classesArray);</script>";
}
?>
<script>
$(document).ready(function(){
//var a = ["class1", "class2", "class3"];
//loadClasses(a);'
loadClasses(a);
});
function loadClasses(classesArray) {
// #classesfield is the id of the classes dropdown
for (var i = 0; i < classesArray.length; i++) {
$("#classesdropdown").append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
$label = $('<label class="w3-validate"></label>'); // crete element to inject
$label[0].innerHTML= (classesArray[i]); // give it a class label
$("#classesdropdown").append($label); // add it to our dropdown
$("#classesdropdown").append('<br>'); // add new line to the dropdown
}
}
</script>

The proper way to do this is to have a simple HTML page which requests the JSON via an AJAX call to a PHP page which in-turn fetches the Database data, processes it, and returns JSON data.
SQL Data
I made up the following data as an example, but the PHP does not care about the fields. You will just return all the data in the table as a JSON object array.
CREATE TABLE IF NOT EXISTS `course` (
`course_no` int(11) NOT NULL,
`course_name` varchar(64) NOT NULL,
`course_desc` varchar(255) DEFAULT NULL,
`course_credits` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `course` ADD PRIMARY KEY (`course_no`);
INSERT INTO `course` (`course_no`, `course_name`, `course_desc`, `course_credits`) VALUES
(1, 'Algebra', 'Learn how to perform basic arithmetic.', 4),
(2, 'Biology', 'Learn how to classify organisms.', 4),
(3, 'Literature', 'Read a lot of books.', 4),
(4, 'Physical Education', 'Get active!', 2);
retrieveClasses.php
Connect, query, and return the class information from the database as a JSON array.
<?php
$mysqli = new mysqli('localhost', 'admin', '', 'test');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM `course`")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
?>
index.html
Populate the dropdown with the JSON data returned from the AJAX call.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax Populate Using PHP DB</title>
<meta name="description" content="PHP Database Ajax Populate">
<meta name="author" content="Self">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('./retrieveClasses.php', function(records) {
loadClasses(records.map(function(record) {
return record['course_no'] + '] ' + record['course_name'];
}));
});
});
function loadClasses(classesArray) {
// #classesfield is the id of the classes dropdown
for (var i = 0; i < classesArray.length; i++) {
$('#classesdropdown').append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
$label = $('<label class="w3-validate"></label>'); // crete element to inject
$label.text(classesArray[i]); // give it a class label
$('#classesdropdown').append($label); // add it to our dropdown
$('#classesdropdown').append('<br>'); // add new line to the dropdown
}
}
</script>
</head>
<body>
<div id="classesdropdown"></div>
</body>
</html>

Related

update data in the div

I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point

get sql query displayed rather than query result using AJAX

Hello I have been trying to figure out why my code aimed at listing a query result in a table does not work. I took code found on the web and tired to adapt it. My data is stored in pgsql. The html page has a drop down menu that allows selecting an institution name. When I click the submit button to know who belongs to this institution in my database, the php page is loaded and displays the SQL query I want to send to pgsql. I should get the result of the query displayed in a table displayed on the html page instead. The drop down menu works correctly so I do not provide the php code for this one (listinstitutions.php)
A person told me I should use ajaxsubmit() but I do not know where to put this function.
There may be an error in the php file also since the query is displayed rather than being sent to pgsql. Is the json correctly sent?
Your guidance would be very much appreciated.
Thank you.
The html side:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
//////////////////////////////////////
// Displays insitution names in Drop Down Menu
//Getting the selector and running the code when clicked
$('#selinstit').click(function(e){
//Getting the JSON object, after it arrives the code inside
//function(dataI) is run, dataI is the recieved object
$.getJSON('http://localhost/listinstitutions.php',function(dataI){
//loop row by row in the json, key is an index and val the row
var items = []; //array
$.each(dataI, function(key, val) {
//add institution name to <option>
items.push('<option>' + val['Iname'] + '</option>');
});//end each
//concatenate all html
htmlStr=items.join('');
console.log(htmlStr);
//append code
$('option#in').after(htmlStr);
});//end getJSON
});//end cluck
///////////////////////////////
// Displays persons form an institution in a table
$( "$subinst" ).button().click(function( event ) {
console.log($(this)); // for Firebug
$.getJSON('http://localhost/SelectPersonsBasedOnInstitution.php',function(data){ // I make an AJAX call here
console.log($(this)[0].url); // for Firebug check what url I get here
//loop row by row in the json, key is an index and val the row
var items = []; //array
$.each(data, function(key, val) {
//add table rows
items.push('<tr border=1><td>' + val['Pfirstname'] + '</td><td>' + val['Plastname'] + '</td><td><a mailto:=" ' + val['Pemail'] + ' " >' + val['Pemail'] + '</a></td></tr>');
});//end each
//concatenate all html
htmlStr=items.join('');
//append code
$('#instito').after(htmlStr);
});//end getJSON
event.preventDefault();
});
}); //end ready
</script>
</head>
<body>
<form id="myForm" action="SelectPersonsBasedOnInstitution.php" method="post">
Select persons from an institution:
<br>
<tr>
<td>
<select id="selinstit" name="instit">
<option id="in">Select</option>
</select>
</td>
<td>
<input type="submit" id="subinst" value="Submit" />
</td>
</tr>
</form>
<table frame="border" id="instito">
</table>
</body>
</html>
Here is the php code for SelectPersonsBasedOnInstitution.php
<?php
//////////
// part 1: get information from the html form
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
foreach ($_REQUEST as $key => $value){
$$key=$value;
}
// part2: prepare SQL query from input
$sqlquery= sprintf('SELECT "Pfirstname", "Plastname", "Pemail" FROM "PERSON"
LEFT JOIN "INSTITUTION" ON
"PERSON"."Pinstitution"="INSTITUTION"."Iinstitution"
WHERE "Iname" = \'%s\'',$instit);
echo $sqlquery;
/////////
// part3: send query
$dbh = pg_connect("host=localhost dbname=mydb user=**** password=*****");
$sql= $sqlquery;
$result = pg_query($dbh,$sql);
$myarray = pg_fetch_all($result);
$jsontext = json_encode($myarray);
echo($jsontext);
?>
The following line is likely to be the problem (it shouldn't be there):
echo $sqlquery;
Rewrite your code without that line and it should work.
$sqlquery= sprintf('SELECT "Pfirstname", "Plastname", "Pemail" FROM "PERSON" LEFT JOIN "INSTITUTION" ON "PERSON"."Pinstitution"="INSTITUTION"."Iinstitution" WHERE "Iname" = \'%s\'', $instit);
$dbh = pg_connect("host=localhost dbname=mydb user=**** password=*****");
$result = pg_query($dbh, $sqlquery);
$myarray = pg_fetch_all($result);
$jsontext = json_encode($myarray);
echo($jsontext);

How to plot real time graph using php and AJAX?

I am a newbie in web development. I have just started programming in php. I want to develop a dynamic page that is connected to MySQL database (from a server) and display the result in a plot (could be scatter, histogram) in real time. So far I managed to get my data from my database and display the graph. However, I couldn't manage to do it in real time.
I have been searching around. What I found was using AJAX to do the real time plot. Fine, I did some tutorial on it and was able to run the examples. My challenge is to plot the graph.
If it helps, this is exactly what I want to do
http://jsxgraph.uni-bayreuth.de/wiki/index.php/Real-time_graphing
I have tried to run this code but I was not able to.
Could anyone give me how to start from simple? I will elaborate if my question is not clear enough.
Thank you in advance!
#Tim, here is what I tried to do.
My php is
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
//echo "Database Connected!";
mysql_select_db("DB", $con);
$sql=mysql_query("SELECT Def_ID, Def_BH FROM BBB WHERE Ln_Def < 1200");
$Def_ID= array();
$Def_BH = array();
while($rs = mysql_fetch_array($sql))
{
$Def_ID[] = $rs['Def_ID'];
$Def_BH [] = $rs['Def_BH '];
}
mysql_close($con);
$json = array(
'Def_ID' => $Def_ID,
'Def_BH' => $Def_BH
);
echo json_encode($json);
?>
The output is
{"Df_ID":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41"],"Df_BH":["1","1","1","5","5","2","1","1","1","1","2","1","1","1","1","1","1","1","1","1","1","1","2","1","1","2","1","3","10","1","2","1","1","1","2","2","2","1","1","1","1","1"]}
Then my script follows
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Example: Real-time updates</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language = "javascript" type="text/javascript" src="Include/excanvas.js"></script>
</head>
<body>
<div id="placeholder" style="width:600px;height:300px"></div>
</body>
<script type="text/javascript">
function doRequest(e) {
var url = 'fakesensor.php'; // the PHP file
$.getJSON(url,data,requestCallback); // send request
}
function requestCallback(data, textStatus, xhr) {
// // you can do stuff with "value" here
$.each(data, function(index, value) {
console.log(value.Df_ID);
console.log(value.Df_BH);
});
}
</script>
</html>
I would like to plot Def_Id versus Def_BH. Do you see what have gone wrong?
Look at High Charts Dynamic Update ;-)
First, you need to get the output right. In my opinion, JSON is the best format to transfer data between server and client using async requests. It's a data format that can be parsed easily by a lot of programming languages.
Next, you need to figure out what you are going to transfer. Are you going to transfer a bulk of data at once and animate it using javascript, or are you planning to send a request per new bit?
My advice: make the amount of requests as little as possible. Requests are slow.
How do you know what to send? Are you going a timestamp? An ID? Anything is possible. Because ID's auto-increment, you might as well use that.
So first, I'm going to set up my PHP:
// get user input
$lastID = intval($_GET['lastid']);
// --------------------------------
// FETCH RECORDS FROM DATABASE HERE
// --------------------------------
// $sql = "SELECT * FROM `graph` WHERE `id` > " . $lastID;
// CREATE DUMMY CONTENT
$data = array();
for($i = $lastID; $i < $lastID + 50; $i++) {
array_push($data, array(
'id' => $i,
'position' => array(
'x' => $i,
'y' => mt_rand(0, 10) // random value between 0 and 10
)
));
}
// END CREATING DUMMY CONTENT
// create response
$json = array(
'lastID' => $data[count($data) - 1]['id'],
'data' => $data
);
// display response
echo json_encode($json);
As you can see, I'm getting a bulk of data using lastid as input. That input is important.
Now, we are going to set up our javascript to get the request. I'm using the jQuery library for my AJAX requests because I'm a jQuery fanboy!
var interval = setInterval(doRequest, 4000); // run "doRequest" every 4000ms
var lastID = 0; // set 0 as default to ensure we get the data from the start
function doRequest(e) {
var url = 'my-file.php'; // the PHP file
var data = {'lastid': lastID}; // input for the PHP file
$.getJSON(url, data, requestCallback); // send request
}
// this function is run when $.getJSON() is completed
function requestCallback(data, textStatus, xhr) {
lastID = data.lastID; // save lastID
// loop through data
$.each(data, function(index, value) {
// you can do stuff with "value" here
console.log(value.id); // display ID
console.log(value.position.x); // display X
console.log(value.position.y); // display Y
});
}
All that remains is outputting the results to a graph!
When you look at your PHP response you'll see that there's one object with two properties containing an array.
{
"Df_ID": [1, 2, 3, ...],
"Df_BH": [1, 2, 3, ...]
}
You can access these properties by... calling those properties data.Df_ID, data.Df_BH
function requestCallback(data, textStatus, xhr) {
console.log(data.Df_ID, data.Df_BH);
}
These are what i found in google -
http://www.makeuseof.com/tag/add-graphs-php-web-app-pchart/
http://www.ebrueggeman.com/phpgraphlib
You could create dynamic graphs and call using AJAX infinitely.

Autocomplete form populated by a database?

I am currently working on a project in which I need to have an autocomplete form call its information from a db file. I have seen many tutorials on jquery autocomplete forms, but I do not know how to call a db file to populate the list.
I am working in PHP. Currently the code represents a simple drop down box that is calling on the db file for population.
<?php
global $wpdb;
$depts = $wpdb->get_results( "SELECT * FROM departments ORDER BY department_name ASC" );
echo '<select>';
foreach($depts as $row) {
echo '<option name="select_dept" value="'.$row->department_id.'">'.$row->department_name.'</option>';
}
echo '</select>';
?>
Any help would be awesome!
I recently have used this library for autocompletion - http://www.devbridge.com/projects/autocomplete/jquery/
So here is brief script based on yours:
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
if ($query) {
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM departments WHERE department_name LIKE '".$query."%' ORDER BY department_name ASC" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->department_name;
$data[] = $row->department_id;
}
$response = array(
'query' => $query,
'suggestions' => $suggestions,
'data' => $data,
);
echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#box').autocomplete({
serviceUrl:'/',
// callback function:
onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
});
});
</script>
</body>
<html>
<?}?>
Please follow this very well written tutorial
http://www.nodstrum.com/2007/09/19/autocompleter/
JQuery UI includes an autocomplete, although you still need to write a PHP script to return the information to be added to the control as its done via AJAX. If you know in PHP how to connect to a database, query it, and return a list of the results - then you will have no problems with this. JQuery makes AJAX extremely simple.
Depending on how complicated your field/data set is - and assuming its not millions upon millions of unindexed records, I would be content to autocomplete from a:
SELECT thing WHERE thing LIKE '".$query."%'
So if you were searching for, say, food... the query "CA" would pull out CArrot and CAbbage and CAuliflower. If you added a % to the beginning of the LIKE, you could get results that contained your query, as opposed to just beginning with it.
The page your user hits would contain the JQuery part which both sends the request and creates the autocomplete effect from the results, and a very simple, separate PHP script which the AJAX request hits would return the potential 'matches'.
Take a look at the Autocomplete demos on JQuery UI

Load Javascript array with MYSQL database data

suppose i have an javascript array "userName".I want to load it from a database table named "user".
Can anyone help with idea or sample code?
Thanks
You'll have to use the mysql_connect(), mysql_select_db() functions in PHP to connect to your db. After that use mysql_query() to SELECT the fields in your user table (if your user table has the fields name and id, SELECT name, id FROM user). Then you can fetch all infos from the db with mysql_fetch_assoc() or any other mysql fetch function. Now you need to echo your data into the javascript on your website, formatted as an array. This is complicated to get right, but you can get help from json_encode.
To fill your array with the user names, you'd do something like this.
<html>
<head>
<script type="text/javascript">
var userName = <?php
// Connect to MySQL
//mysql_connect();
//mysql_select_db();
$d = mysql_query( "SELECT name, id FROM user" ) or die( mysql_error() );
$usernames = array();
while( $r = mysql_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
// Do something with the userName array here
</script>
</head>
Use ajax and php as an intermediate :
Define an empty JS array :
var myarray = new Array();
use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):
new Ajax.Request('myfile.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
Write your PHP code to grab data and print JS code (it must be valid javscript !) :
$i=0; $q=mysql_query('select ..');
while($row=mysql_fetch_array($q)){
echo "myarray[".$i."]='".$row['data']."';";
$i++;
}
You can check that your Js array contains data :
alert(myarray.length);
hope this helps.
This creates a global user variable in your page.
<?php
$user = /* get information from database the way you usually do */;
// $user == array('id' => 1, 'name' => 'foo', ...);
?>
<script type="text/javascript" charset="utf-8">
var user = <?php echo json_encode($user); ?>;
</script>
If you're looking for a dynamic AJAXy solution, follow some tutorials about AJAX.
The best way to do that simply is to get your data in your php code, and then "write" the javascript code to generate the array in php.
A short example would be :
echo "a = new Array();";
foreach($row in $results)
{
echo "a[$row[0]] = $row[1];";
}
My code could be quite incorrect, it's juste to give you a quick example.
You could also do that in a more elegant way, using json.

Categories