Pass PHP array into Javascript array [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Referring to the title. I have an array which I coded like this:-
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result)) {
$dServer[] = $row['model'];
}
Now, how do I pass the $dServer array into a Javascript array?
For example, this array:
var a = new Array();

$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result)){
$dServer[] = $row['model'];
}
?>
<script type="text/javascript">
var a = <?php echo json_encode($dServer); ?>;
</script>

Encode it as a json object.
<?
$arr = array('entry' => 'content');
?>
<script>
var data = <?=json_encode($arr);?>;
alert(data['entry']);
</script>

Try to get use of ajax request and json_encode.
Second variant
<?php
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result))
{
$dServer[] = $row['model'];
}
?>
var a = <?php echo json_encode($dServer);?>;

In addition to the ajax / json methods mentioned, you can directly print out the values:
<?php
$query = "SELECT * FROM server";
$result = mysql_query($query);
?>
<script type="text/javascript">
var a = new Array();
<?php
while($row = mysql_fetch_assoc($result)){
echo "a['model'] = " . $row['model'] . ";";
echo "a['nextField'] = " . $row['nextField'] . ";";
}
?>
</script>

Related

[PHP]Same Array into different Bracket

In PHP, I have an array which I created and usueally the value of that array are like ['a','b','c'], but I dont know why, my array is in this form : [['a'],['b'],['c']]
Here is my code :
<?php
$res1 = array();
$result1 = mysqli_query($con,$dfcv) ;
while($row2 = mysqli_fetch_array($result1)){
array_push($res1, array(
$row2['username2'])
);
}
echo json_encode($res1);
?>
Because you add the result into additional an array (...array(
$row2['username2'])...).
<?php
$res1 = array();
$result1 = mysqli_query($con,$dfcv) ;
while($row2 = mysqli_fetch_array($result1))
array_push($res1, $row2['username2']);
echo json_encode($res1);
?>
Your code should look like this:
<?php
$res1 = array();
$result1 = mysqli_query($con,$dfcv) ;
while($row2 = mysqli_fetch_array($result1)) {
array_push($res1, $row2['username2']);
}
echo json_encode($res1);
?>
You've put an extra array on $row2 when you were doing the array_push()
array_push($res1, array($row2['username2']));

implode output does not gives proper output

This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);

Filling Javascript array with objects properties from database

Hi I'm trying to make an array " events" in javascript that is filled with objects of two properties {Title: , Date:}
But, the value of those two properties is brought from the database using PHP!
Here's my code but I don't know why it doesn't work..
var events = [
<?php
//Connect to mysql server
//Select database
$result=mysql_query("SELECT * FROM event");
$count = mysql_num_rows($result);
if($count>0){
for($i=0;$i<$count-1;$i++){
$row= mysql_fetch_row($result);
echo "{ Title: ".$row['title'].", Date: ".$row['date']." },";
}
$row= mysql_fetch_row($result);
echo "{ Title: ".$row['title'].", Date: ".$row['date']." }";
}
?>];
Let's first take the building of your results:
Use array_push to create your data from your SQL (this is called an associative arrays:
var events =
<?php
$json = array();
$result=mysql_query("SELECT * FROM event");
$count = mysql_num_rows($result);
for($i=0;$i<$count;$i++) {
$row= mysql_fetch_row($result);
$item = array();
$item['Title'] = $row['title'];
$item['Date'] = $row['date'];
$json[] = $item;
}
Now echo the results as JSON using json_encode:
echo json_encode($json);
?>;
Tested in PHP 5.3.2

remove last character

i noticed that there are a lot of topics like this in stackoverflow, but the ones that i read are with just 1 variable, and i have two and i'm a little confuse.
so this is my code,
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
while($row = mysql_fetch_array($query)){
echo "'".$row['provider_id']."':'".$row['company_name']."',";
}
I am using this to generate javascript code for Jeditable.
I need to take out the last comma, so I can wrap up with the rest of the code...
I like to use an array:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(",",$out);
It looks like you're trying to output some kind of JSON though, so perhaps you could use:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[$row['provider_id']] = $row['company_name'];
}
echo json_encode($out);
So i usually just stack things like this into an array and then implode:
$parts = array();
while($row = mysql_fetch_array($query)){
$parts[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(',', $parts);
That said it looks like youre outputting the body of a JSON string. If so you shouldnt manually build it you should use json_encode instead.
$data = array();
while($row = mysql_fetch_array($query)){
$data[$row['provider_id']] = $row['company_name'];
}
echo json_encode($data);
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = "";
while($row = mysql_fetch_array($query)){
$result .= "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = rtrim($result, ',');
OR
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = array;
while($row = mysql_fetch_array($query)){
$result[] = "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = implode(',' $result);
OR
get count of records (mysql_num_rows($query)) and when you hit last row just do what you want

getting specific php variable out of a loop to jquery function parameter

i have a auto suggest textbox witch generates li tags with a onclick event with a function but i have to pass a php variable to the function as parameter but i only want the variable value of the li the user clicked on and now i always get the last variable in the loop.
And i want the var test to be the value of $test = $row['t_product']; of the li the user clicks on
here is the code im using now:
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
$search_term = $_POST['search_term'];
$customerid = $_SESSION['userdata']['t_customer_id'];
$conn = connect();
$sql = "SELECT * FROM Licenses WHERE customer_id = '$customerid' AND t_name LIKE '$search_term%'";
$query = sqlsrv_query($conn, $sql);
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<script type="text/javascript">
var test = <?php echo json_encode($test); ?>;
</script>
<?php
echo '<li onclick="show(test)">', $row['t_name'], '</li>';
}
}
i hope i explained my problem well and hope that some wane can help me :)
Well, maybe you should do :
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<?php
echo '<li onclick="show("'.$test.'")">', $row['t_name'], '</li>';
}
or
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
$index = 0;
$search_term = $_POST['search_term'];
$customerid = $_SESSION['userdata']['t_customer_id'];
$conn = connect();
$sql = "SELECT * FROM Licenses WHERE customer_id = '$customerid' AND t_name LIKE '$search_term%'";
$query = sqlsrv_query($conn, $sql);
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<script type="text/javascript">
var test<?php echo $index++ ?> = "<?php echo $test; ?>";
</script>
<?php
echo '<li onclick="show(test'.$index++.')">', $row['t_name'], '</li>';
}
}
Edit: removed json_encode and replaced it with quotes
solved it by passing the $test value as id to each li and in the js get it with
$test = $row['t_product'];
echo '<li onclick="show(this)" id="'.$test.'">', $row['t_name'], '</li>'
function show(id){
alert($(id).attr("id"));}

Categories