Trying to transfer mysql database data to javascript array - javascript

I have tried few things bet they don't seem to work, my code works fine if I populate the array myself without database therefore the problem is with retrieving data from database.
var countries = <?php
require('connection.php');
$query = 'SELECT product_name FROM products';
$result = mysqli_query($conn, $query);
while($products = mysqli_fetch_array($result, MYSQLI_NUM)){
echo json_encode($products);
//OR
//$products = mysqli_fetch_all($result, MYSQLI_NUM);
//echo json_encode($products);
}
?>;
This is the code I have tried but it is not working
I am sending countries to a function
autocomplete(document.getElementById("myInput"), countries);
In this function I am parsing through the array in such a way
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
/*here arr is the array 'countries' send to the function autocomplete*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {//code snippet
}}

You are echoing a JSON string at each iteration of the while() loop. So, it will writes a non-valid JSON string. You could create an array, populate it, and finally, write it as JSON:
<?php
require('connection.php');
$query = 'SELECT product_name FROM products';
$result = mysqli_query($conn, $query);
$products = []; // new array
while($product = mysqli_fetch_array($result, MYSQLI_NUM)) {
$products[] = $product ; // push into array
}
// finally, write JSON:
?>
var countries = <?php echo json_encode($products) ?>;

Related

i have code like this for auto complete feature but am not able fetch the data from the data base.kindly help me out

My aim is to fetch location from the database once user start entering in the input tetc field
i have done all the coding properly but the also am not able to fetch the data from the database.
<!--My java script code-->
$(function() {
$( "#LocationName" ).autocomplete({
source: 'search.php'
});
});
<!--My Search.php code-->
<?php
include('dbConnect.php');
$searchTerm = $_GET['term'];
$sql = mysql_query ("SELECT LocationName,From arealistmain WHERE LocationName LIKE ?");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'value' => $row['LocationName'].'',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
?>
First of all don't use mysql_* functions as they were deprecated in PHP 5.5 and removed in PHP 7 instead use mysqli_* functions.
Second thing you should always sanitize user input don't just do $searchTerm = $_GET['term']; read more about this
Then your SQL query should read
$query = "SELECT LocationName From arealistmain WHERE LocationName LIKE '%$searchTerm%';";
The comma before FROM removed and the $searchTerm is enclosed in two percentage signs to match all
Update your query to below code
$sql = mysql_query ("SELECT LocationName From arealistmain WHERE LocationName LIKE '%".$searchTerm."%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = $row['LocationName'];
}

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 take individual values from MYSQL and save it to a JavaScript variable?

I want to select the last row of my table, and save all the values to separate JavaScript variables. I used the query in PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
to select the last row of the table. I don't know how to proceed.
PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
echo json_encode($row);
}
jQuery:
// sample variables
var username = "";
var password = "";
var phpUrl = 'http://sampleurl.com/mypage.php';
$.getJSON(phpUrl, function (result) {
$.each(result, function (data) {
// if data sent back is eg data:[{username:'sample', password:'sample'}]
// then you fetch and save as
username = data.username;
password = data.password;
});
});
cookies way is definitely the way to go. If you are doing all of this on one page and just need a quick fix you could do
<?php
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
$json_string = json_encode($row);
}
?>
<script> var sql_row = <?php echo $json_string; ?>; </script>
This is the lazy way and will get messy quickly, but it could be useful for understanding how PHP and JS work together

How to send rows using json_encode method in php?

I have number of rows in investment table. I need to retrieve all of them and send them back using json_encode.
Here is my code
$project_code = $_GET['id'];
$sql = "select * from investment where project_code = '$project_code'";
$result = mysql_query($sql);
while($x1 = mysql_fetch_array($result))
{ $detail = $x1['detail'];
$sector = $x1['sector'];
}
echo json_encode(array(
'a' => $detail,
'b' => $sector
));
In javascript I wrote following script:
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('display_acc.php',{id:value},function(data)
{
data = JSON.parse(data);
$( '#a' ).html(data.a);
$( '#b' ).html(data.b);
});
});
Here my problem is that it returns only data of last rows. I want to receive data of all rows.
I have to display id a and b here
I use table to display it.
Thank in advance
This should do the trick:
--EDIT after OP explanation--
PHP
$project_code = (int)$_GET['id']; //better put (int) before to avoid SQL Injection
$sql = "select detail, sector from investment where project_code = '$project_code'"; //better to maintain if you set only the fields you will use
$result = mysql_query($sql);
$return = array('detail'=> array(), 'sector' => array()); //here you can put empty return array or set detail and sector key. Your choice will have impact in your front-end
$return['my_extra_var' ] = $my_extra_var;
$i = 0;
while($x1 = mysql_fetch_array($result))
{
$return['table'][$i]['detail'] = $x1['detail'];
$return['table'][$i]['sector'] = $x1['sector'];
$i++;
}
echo json_encode($return);
Javascript
... your ajax request ...
data = JSON.parse(data);
var tableData = data.table;
$.each(tableData, function(index, value) {
$('#tableData').append('<tr><td>'+value.detail+'</td><td>'+value.sector+'</td></tr>'); //append row to tbody
});
HTML
<table>
<thead>
<th>Details</th>
<th>Sector of Investment</th>
</thead>
<tbody id="tableData">
</tbody>
</table>
You need arrays in your loop
$project_code = $_GET['id'];
$sql = "select * from investment where project_code = '$project_code'";
$result = mysql_query($sql);
$cnt=0;
while($x1 = mysql_fetch_array($result))
{ $detail[$cnt] = $x1['detail'];
$sector[$cnt] = $x1['sector'];
$cnt++;
}
echo json_encode(array(
'a' => $detail,
'b' => $sector
));
and in javascript loop over the result
It looks like you are not accumulating the two elements. Try something like this:
array_push(your_array_name, $detail, $sector);
Then encode your array when all done.

how to use the values from mysql database from php in javascript function

In php, i have used an sql query to fetch the data like :-
$sql="Select * from xyz";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
}
Now i want to use all the values attained using $row["id"] in javascipt function and use it in a variable (var j , lets say). How to do this?
Try something like this:
<?php
$sql="Select * from xyz";
$errorsData = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$errorData[]=$row["id"]
}
$errorJson = json_encode($errorsData);
?>
<script>
var errorJson = <?= $errorJson ?> ;
console.log(errorJson);
<script>
Good luck!!
in jquery I would have done like this,
php
$sql="Select * from xyz";
$arr_json = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$arr_json[] = $row['id'];
}
echo json_encode($arr_json);
jquery
$.get(
<THAT CALLED URL>,
function(ret_data){
console.log(ret_data);
/* you can use the ret_data as ret_data.<INDEX> */
}
);

Categories