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?
Related
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've been trying to solve my question based off of this answer:
Populate select box from database using jQuery
I've attempted to implement what is said in the answers there but I am not having any luck here. As of now all that appears in the drop down menu is the default "Stone" item that starts in it.
Could anyone spare some time and give me a hand fixing my issue. My code should essentially read from a MySQL database which has over 150 ID's in order starting at 1 and use the corresponding name in the same ID's row to populate the drop down menu on load.
Example of what drop down menu would look like inside of it:
Stone
Grass
Diamond
What corresponding DB would look like:
ID item_name
1 Stone
2 Grass
3 Diamond
The code I'm using to try and do this is:
PHP (process_item_list.php):
$con = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$dbs = mysql_select_db($DB_NAME, $con);
$tableName = "itemlist";
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
jQuery/Javascript
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("process_item_lists.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#tradeItems").html(items);
});
});
</script>
HTML
<select id="tradeItems">
<option value="">Stone</option>
</select>
I'm open to different ways to do this as well, as long as it still fills the drop down menu on load!
Edit: With the help of wirey the PHP issue is fixed. Here is what the results look like from running the PHP file: http://fogest.net16.net/mctrade/php/process_item_list.php
When I run the actual page using the alert boxes which should give me the ID and the item name they both return undefined rather then the correct values.
The results at http://fogest.net16.net/mctrade/php/process_item_list.php doesn't look like what you're expecting, it looks like this:
[ ["1","Stone","images\/stone.png"],
["2","Grass Block","images\/grass_block.png"],
/* snip a lot of rows */
]
But what you are expecting is something like this:
[ { "id":"1", "name":"Stone", "image?":"images\/stone.png"},
{ "id":"2", "name":"Grass Block","image?":"images\/grass_block.png"},
/* and so on */
]
I think that you'll want to use mysql_fetch_assoc() instead of mysql_fetch_row(), that might give you proper output.
Bonus: you can give the response a proper content-type by adding a row before the echo:
header("Content-type: application/json");
echo json_encode($data);
Remark: when I inspected the source of http://fogest.net16.net/mctrade/php/process_item_list.php I found this at the end:
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
This should not be part of the response, it will probably make the JSON parser crash.
Im trying to learn php by doing a little project using apache server. I have a php page where I want to display a bar chart with jqplot using data i pull from a MySql query. I already have a query working giving me the data i want. The problem is i dont know how to implement this into a jqplot graph. Im guessing i need to make an ajax call but if i can avoid that i would like to. my php page code so far is here http://snipt.org/oknnl2.
the javascript for the bar chart is here http://snipt.org/oknoi3.
i want the chart to render in div id=chartdiv thats on line 177. I have to visualize like 6 charts. if i can get some help on doing this one, im sure i can use the same process to build the others.
PHP cannot create the javascript plot and send it downstream to the client, but you don't have to make an actual AJAX call after the page is loaded either. Simple javascript once the page loads will suffice. If you retrieve the data you need at the PHP level, you can then make it available to javascript in the HTML received by the client. The steps to make this happen:
First, use PHP to retrieve the data you need from the MySQL database.
Then, output the plot data you retrieved using PHP inside a javascript
code block as part of the HTML that PHP sends to the client.
Execute the javascript with the data seeded by PHP on page load.
So, a simplified example:
<?php
// Retrieve plot data from mysql
$q = '...';
$r = mysql_query($q);
$plot_row1 = array();
$plot_row2 = array();
$plot_row3 = array();
while ($row = mysql_fetch_array($r)) {
// append values to $plot_row1, $plot_row2 and $plot_row3 arrays
}
$my_page_title = 'My first PHP/JS Combo Foray';
?>
<html>
<head>
<script type="text/javascript" src="/scripts/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/scripts/my_plotter.js"></script>
</head>
<body>
<h1><?php echo $my_page_title; ?></h1>
<div id="chartdiv">
Hold on, javascript is loading the plot ...
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
// we're combining the php array elements into a comma separated list
// so that when the code is output javascript thinks it's an array.
// if the $plot_row1 = array(1, 2, 3) then we'd get this:
//
// row1 = [1, 2, 3];
//
// if you needed quotes around the imploded php array values (if they
// are strings where javascript is concerned) you could do this instead:
//
// row1 = ["<?php echo substr(implode('","', $plot_row1), 0, -2); ?>"];
row1 = [ <?php echo rtrim(implode(',', $plot_row1), ','); ?> ];
row2 = [ <?php echo rtrim(implode(',', $plot_row2), ','); ?> ];
row3 = [ <?php echo rtrim(implode(',', $plot_row3), ','); ?> ];
// call your js function that creates the plot
showBrittleness(row1,row2,row3);
// add whatever js code you need to append the plot to $('#chartdiv')
}
</script>
UPDATE
According to a cursory examination of the jqplot docs, if you edit line 12 of the javascript you link from this:
var plot1 = $.jqplot('chart1', [s1, s2], {
To this:
var plot1 = $.jqplot('chartdiv', [s1, s2], {
Your function should render the plot in the 'chartdiv' id element. It seems the first argument to the $.jqplot function is the element in which to create it ...
I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.
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.