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.
Related
I have an SQL database (I know for sure it includes remote access, if that's necessary to access a database through php). It definitely has at least one record in it, and I need to get each record and create a corresponding button that links to a php file, taking the first field for that record as a/n argument, variable, parameter, or whatever you call the whatever.php?variable=value.
For some reason, this code just gives me a blank page. Why?
<?php
$connection=mysqli_connect("myhost","myusername","mypassword","mydatabase");
$result=mysqli_query($connection, "SELECT * FROM myTable");
$resultArray=array();
while ($row = mysqli_fetch_array($result)) {
array_push($resultArray, $row['ID']);
}
$resultArrayImplode = implode(",", $resultArray);
?>
<script>
var resultArray = <?php echo $resultArrayImplode; ?>
arrayEntries = new Array();
arrayEntries = resultArray.split(",");
function CreateButtons(element, index, array) {
var button = document.createElement("input");
button.type = "button";
button.value = element;
button.onclick = function() {
document.location.href = "ButtonClicked.php?id=" + element;
}
document.body.appendChild(button);
}
arrayEntries.forEach(CreateButtons);
</script>
Thanks!
Your javascript assignment to resultArray is probably not syntactically correct due to quote characters, etc. Luckily, PHP's JSON functions automagically create good javascript for you.
Try this for the javascript output:
var arrayEntries = <?php echo json_encode($resultArray)?>;
Your problem is $resultArrayImplode; is a string, so
var resultArray = <?php echo $resultArrayImplode; ?>
renders as:
var resultArray = 1,2,3,4,5
Which is a syntax error.
What you can do is use JSON. JSON syntax is JavaScript syntax, so all you need to do is:
var arrayEntries = <?php echo json_encode($resultArray); ?>;
This should render as something like:
var arrayEntries = [1,2,3,4,5];
Which is perfect JavaScript syntax. Then the rest of your code should work.
I just don't see why do you need to use javascript for this, cant you just do the following :
<?PHP
foreach($resultArray as $result)
{
?>
Im a button click me</div>
<?PHP
}
?>
in my opinion, i see no real need for you to use javascript for this.
I have an app that sends latitude, longitude values to my postgresql database. And i want to plot the updated points accordingly on my OpenLayers map using jquery,ajax. But here is where i am stuck at: When I click the button, the php file with database connection and saving the last entry of the table in an array is happening.
But when i try using the outputs in markers, nothing is happening.
How to use the output values of the php in my function?
Here is the code that i am trying to use.
php file:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
My page code is :
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
and the alert i am getting when clicking update button is
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
Is the way i am trying to access the values of query output correct? Please help.
Sorry if this is a dumb question. I am new to jquery.
When your php script sends a string like:
'var javascript_lat1 = ["output of the query"];'
back to your code, that does not mean that your code has a variable called javascript_lat1 in it.
Your php script is sending strings back to your javascript code from which you must extract the information that you want to use in your code. It is up to your javascript code to know what format the strings are in. But since you wrote the php script you can send the strings back in any format you want. Then your javascript code can dissect the strings with regexes, split(), etc. to extract the parts of the strings that you want to use in your code. A very simple format that your php code could use is:
"output of query 1, output of query 2"
Then you can split() on the comma to separate the two pieces of data e.g.:
var pieces = data.split(', ');
Then you can use pieces[0] and pieces[1] in your javascript code.
Another option is to send a request to your php script using the $.getJSON() function. If you do that, your php script should send back a json formatted string, e.g.:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
Then the $.getJSON() function will automatically convert the string into a javascript object and pass the js object to your callback function. Inside the callback function you can access the data using:
some_func(data.lat1, data.long1);
I am working on an e-commerce website. There is an array "products" in javascript defined by the following code
<script type="text/javascript">
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
/*some other javascript code*/
</script>
I want this array to be updated dynamically according to the number of rows returned by querying the database.
For example, suppose I query the database and 5 rows are returned. I want this array to be updated with those 5 rows. Please help me getting this done. I am using PHP, MySQL, Apache on Windows machine.
You want the push function: http://www.w3schools.com/jsref/jsref_push.asp
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
// Let's add a new phone:
products.push({"id":"3","title":"HTC Evo"});
/*
products now equals:
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"},
{"id":"3","title":"HTC Evo"}
];
*/
To account for the possibility you may have an existing array and you'd like to update it via ajax, you can do this dynamically with PHP:
<script type="text/javascript">
<?php foreach($phones as $phone): ?>
products.push({"id":"<?=$phone['id']?>","title":"<?=$phone['name']?>"});
<?php endforeach; ?>
</script>
The top answer to the question JSON encode MySQL results could achive this for you:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
In your case, replacing the last line with
?>
var products = <?php echo json_encode($rows); ?>;
<?php
would initialize the JavaScript object with your query results. This would need to be done before the page is loaded, because the PHP runs on the server producing the JavaScript for the client. If you need to get the results after the client page is loaded you would need a more complicated solution, probably using AJAX.
I would make a server side script that makes the connection to the database, get's the products, and constructs the JSON for you, so that way all you have to do is make an AJAX request to the script from the client side and it will return everything for you for use on your webpage.
You can use PHP to output json directly into the page.
Assuming that $data is an array that contains the products you want to output.
In the template you would do something like this:
<script type="text/javascript">
var products = <?php echo json_encode($data) ?>;
</script>
products[products.length] = {..some data..};
products.push({..some data..});
Or you need something else?
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
I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...