convert string into array for highcharts js - javascript

My code PHP generate a string variable
<?php
foreach($rows as $row){
$result .= "['" .$row["Name"]."'," .$row['Value']. "] , ";
}
$result = rtrim($result, ' , ');
//echo $result returns: ['FirstName1 LastName1',10] , ['FirstName2 LastName2',12] , ['FirstName3 LastName3 ',40]
?>
In js how can I convert the 'name' variable into a functional variable for 'data:' ?
<script>
var name = "<?php echo $result; ?>";
Highcharts.chart('container', {
...
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2]
];
...
});
</script>
Thank you!

You need to wrap $result in an array:
$result = "[$result]";
But you really should use json_encode like this:
$resultArr = [];
foreach ($rows as $row) {
$resultArr[] = [$row['Name'], $row['Value']];
}
$result = json_encode($resultArr);

Related

How do get php array in javascript variable

I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>

Storing PHP variable into JavaScript variable in a For loop

I know how to pass a PHP variable into JavaScript variable one by one, but now I wish to pass a bunch of variable in a For loop and I just stuck.
<?php
$m = new MongoClient();
$db = $m->data_from_tweeter;
$collection = $db->output;
$cursor = $collection->find();
foreach($cursor as $document){
echo $document['place'] ;
echo $document['fir'];
echo $document['sec'];
}
?>
I want to store 'place' as a String variable, 'fir' and 'sec' as two Num variables, and make them look like:
var num_1 {
some_place : some_fir,
some_place : some_fir,
some_place : some_fir,
....
}
and
var num_2 {
some_place : some_sec,
some_place : some_sec,
some_place : some_sec,
....
}
How can I make it? Thanks in advance!
if $document['fir'] and $document['sec'] are array .You can do like this
<?php
$m = new MongoClient();
$db = $m->data_from_tweeter;
$collection = $db->output;
$cursor = $collection->find();
$num1=array();
$num2=array();
foreach($cursor as $document){
echo $document['place'] ;
$num1 = json_encode ($document['fir']);
$num2 = json_encode ($document['sec']);
}
?>
You can use a JSON string as a object for javascript
var num_1 = <?php echo $num1;?>
var num_2 = <?php echo $num2;?>
The following code snippet might help get you started:
$num_1 = "var num_1 = {\n";
$num_2 = "var num_2 = {\n";
foreach ($cursor as $document) {
$num_1 .= " {$document['place']} : {$document['fir']},\n";
$num_2 .= " {$document['place']} : {$document['sec']},\n";
}
$num_1 .= "};\n";
$num_2 .= "};\n";
echo $num_1;
echo $num_2;

Pass PHP array from Javascript

I would like to pass a PHP array from JavaScript.
PHP Data Table
---------------------------
| adminID | adminEmail |
===========================
| 1 | abc#gmail.com |
| 2 | xyz#ymail.com |
===========================
Javascript
<script>
function checkuser_callback_function($el, value, callback) {
var $array = new Array("xyz#gmail.com","abc#ymail.com");
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>
I want to pass that adminEmail here var $array = new Array("..","..");
I have tried alot in php but I didn't get any result.
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
$array = $row;
$str = "'" . implode ( "', '" ,$array ) . "'";
$parts = split("'", $str);
print_r($str);
}
?>
You can use php to create javascript array. Then use the same in the script later. Please note that , just to differentiate, I have called javascript array jArray instead of $array. Rest is explained along in the script only. Hope this helps..
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
//start script tag
echo "<script>\n";
// javascript array decalaration beginning
echo "var jArray = new Array(";
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
echo $arrStr;
// end javascript array
echo ");\n";
echo "</script>\n";
?>
<?php
include 'ePHP/config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
?>
<script>
function checkuser_callback_function($el, value, callback) {
var $array = Array(<?php echo $arrStr; ?>);
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>

How to store MySQL date in Javascript array?

I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.
Let say,
My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.
How can I store in Javascript after I converted them into json by
<?php
$sql = "SELECT public_holiday.holiday_date
FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
$json_array = json_encode($result_array);
echo $json_array;
?>
?
I have tried to store them into a javascript date array like
var holidays = [<?php //sample array for example
$loop_one = true;
foreach ($result_array as $date)
{
if ($loop_one)
{
echo "'new Date(\'$date\')'";
$loop_one=false;
}
else
{
echo ", 'new Date(\'$date\')'";
}
}
?>];
but all of these are invalid.
I need your help, much appreciated.
To get a javaScript date object array you need to change your script code only no need to change the PHP code.
You can use JSON.parse and forEach loop.
Try like this
<script>
var holidays = '<?php echo $json_array;?>';
holidays=JSON.parse(holidays);
var holidayArray=[];
holidays.forEach(function (key) {
holidayArray.push(new Date(key));
});
console.log(holidays);
console.log(holidayArray);
</script>
It will produce an out put as
I thing it will help you.
So in your sample, the $result_array variable will be a PHP array like:
$result_array = ['2017-06-25', '2017-06-26', '2017-06-27'];
You do not really need to convert this to JSON before passing it to your Javascript. Instead, you could print those string values directly into your Javascript to instantiate the date object, i.e.
<?php
$sql = "SELECT holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['holiday_date']; # Return the actual date value and not an array
}
?>
Javascript Part:
var holidays = [<?php
$firstLoop = true;
foreach ($result_array as $date_result) {
# Here you could format your $date_result variable as a specific datetime format if needed to make it compatible with Javascripts Date class.
if ($firstLoop) {
$firstLoop = false;
echo "new Date('$date_result')";
} else {
echo ", new Date('$date_result')";
}
}
?>];
In this example, I'm constructing a javascript array of new Date($phpDateTime) objects.
Your while loop should be like this and push the date into new array
<?php
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
//$result_array contains date like this $result_array = ['2017-06-26', '2017-06-27'];
?>
Javascript example
<script>
var holidays = [<?php $result_array = ['2017-06-26', '2017-06-27']; //sample array for example
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>
Update 1: Finally your code should be like this
<?php
$sql = "SELECT public_holiday.holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
?>
<script>
var holidays = [<?php
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>

load JSON data attributes from external php page

Hi I try to load a JSON data from a php link in a js file whith this
$.getJSON('link to rempl.php', function(data) {
cn =data.nom;
});
this is the code of rempl.php
<?php
header('Content-Type: text/plain; charset=utf-8');
require_once ('connectDB.php');
if ($_POST['nom']== 0){
header("Location: http://localhost/geopp/editer.php");
}else{
$id = $_POST['nom'];
}
$sql = "SELECT id , id_archi , nom , archithect , adresse , date_construction , dateconst , resume FROM patri where id=".$id.";";
$req = mysqli_query ($link,$sql);
$feature = array();
//echo "lon\tlat\ttitle\tdescription\ticon";
while ($row = mysqli_fetch_assoc($req)) {
$res['id_archi'] = $row['id_archi'];
$res['id'] = $row['id'];
$res['date'] = $row['dateconst'];
$res['nom'] = $row['nom'];
$res['archithect'] = $row['archithect'];
$res['adresse'] = $row['adresse'];
$res['date_construction'] = $row['date_construction'];
$res['resume'] = $row['resume'];
$feature[] = json_encode($res);
}
echo implode(', ',$feature);
header("Location: http://localhost/geopp/empl.php");
?>
but when I alert the variable cn it show me undefined and thanks for helping me.

Categories