Populate JSON array - javascript

I want to encode an array in php as JSON. How do I make a proper JSON array?
i want to pass two variables.
$var = 33;
$last = 44;
and db results:
foreach($query->result() as $r)
{
$data[]= $r; //popunjava niz rezultatima
}
i am trying to make JSON like this:
$data='';
$data[] =$last;
$data[] =$pn;
foreach($query->result() as $r)
{
$data[]= $r; //popunjava niz rezultatima
}
echo json_encode($data); // json enkoduje niz i pomocu echo prosledjuje do ajaxa

Use array_push to append rows onto the array.
$data = array();
foreach($query->result() as $r)
{
array_push($data, $r);
}
echo json_encode($data);

You should set a key in the array for the variables that you add.
$data= array();
$data['last'] = $last;
$data['pn'] = $pn;
foreach($query->result() as $r)
{
$data['results'][] = $r;
}
echo json_encode($data);

Related

convert string into array for highcharts js

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);

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>

How to remove multiple rows from mysql table, using an array of IDs in PHP

I'm having trouble using an array to make an sql query delete multiple rows of data at once. Please ignore that I'm using sql injection for now.
EDIT: A somewhat better explanation - my php does not work at all. I have edited it somewhat, after checking the link Sebastian provided in the comments
NOTE: I'm using AngularJS to post
This is my $data structure, from my controller.js function. devicesToDelete is just a simple array, e.g. ["1", "2", "3"]:
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
This is the updated php code im having trouble with. On clicking my deleteMultiple button, only the confirm alert fires, the selected items aren't deleted and the console is clear of errors:
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ( implode(",", $data) )";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
EDIT 2: I managed to solve the issue on my own. Here is the solution:
I used .join() on my array on the javascript side to have all of the IDs for deletion be separated by commas (e.g. 1, 2, 3):
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
Then I just added what I completely glanced over in my php code which is the name of the array i was passing into it - devicesToDeleteArray
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
here is php code:
<?php
$ids = $_POST['devicesToDeleteArray'];
if(!is_array($data)) {
$ids = json_decode($data, true);
}
if(!empty($ids)) {
include 'config.php';
$sql = "DELETE FROM devices WHERE devID in (implode(",", $ids))";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_object()) {
$data[] = $row;
}
} else {
$data[] = null;
}
$conn->close();
echo json_encode($data);

Passing an Array from PHP to Javascript

I'm trying to pass on a PHP array to then use the array in JavaScript.
The PHP code I'm using is as follows:
<?php
$link = mysqli_connect("localhost", "root", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM Employees";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
print_r($row);
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($data);
?>
JavaScript:
<script>
var array = <?php echo $data; ?>;
console.log(array);
</script>
The data array in PHP doesn't seem to get passed on to the Javascript var array. When looking at the console on firebug the following error messages are displayed:
Notice - Array to string conversion.
I'd really appreciate any help as to why this error is occurring.
Maybe because you are echo'ing the array instead of the json encoded string.
Use this
<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>
I believe it should be:
<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>
You're using json_encode in $data but you're not using that variable in your code. Could that be it?

Why is this jQuery autocomplete not working?

I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Categories