php array not showing up in javascript - javascript

I created an array of values from data in MySQL. I then try to print it in Javascript but unfortunately it is not showing up.
Database has two cols: gurtej and singh
<?php
require_once('config.php');
function readAttribute($connect){
$resultArray=array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
echo mysqli_num_rows($res);
if(mysqli_num_rows($res)==0){
return 0;
}
else{
while($result=mysqli_fetch_array($res)){
array_push($resultArray,$result[0]);
}
return $resultArray;
}
}
?>
<html>
<body>
<script>
var jArray= <?php
$resultArray=readAttribute($connect);
if($resultArray==0){
$resultArray=[];
}
echo json_encode($resultArray);?>;
var counter=<?php echo count($resultArray);?>;
document.write(jArray[0]);
</script>
<?php
print_r($resultArray);
?>
</body>
</html>
And when i try to print it in php using print_r this is the result.
Array ( [0] => gurtej [1] => singh )

The resulting JavaScript statement includes more than just the var and array as JSON:
var jArray = 2["gurtej","singh"];
The extra 2 comes from the echo within readAttribute() showing the number of rows:
function readAttribute($connect){
$resultArray=array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
echo mysqli_num_rows($res);
// ^^^^
By following the number, the "array" changes meaning and is interpreted as a bracket property accessor with a comma operator. The statement behaves the same as:
var jArray = (2).singh;
And, the number 2 doesn't (normally) have a property named singh. So, you get undefined, which can't have properties.
console.log(typeof jArray); // 'undefined'
console.log(jArray[0]); // TypeError
To remove the 2, you'll want to remove or comment out the additional echo:
function readAttribute($connect){
$resultArray=array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
// echo mysqli_num_rows($res);
// ...
}
var jArray = ["gurtej","singh"];
console.log(typeof jArray); // "object"
console.log(jArray[0]); // "gurtej"

Let's clean up that function a bit and we'll fix the problem too
function readAttribute($connect){
$resultArray = array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
//echo mysqli_num_rows($res);
while($result = mysqli_fetch_assoc($res)){
$resultArray[] = $result;
}
return $resultArray;
}
Your problem is that you were using $result[0], but that just pushes the first column. And if you're going to json_encode this, I would avoid using fetch_array() (without an argument) because it returns both a numeric AND associative key value for each column (which will inflate your data set of rows)

Lets clean up the code:
<html>
<body>
<!-- container to hold data -->
<div id='container'></div>
<script>
<?php
//--- get the results from the database
$resultArray=readAttribute($connect);
//--- convert if necessary
if($resultArray==0){
$resultArray=[];
}
?>;
//--- place results into JavaScript array
var jArray= <?php echo json_encode($resultArray);?>;
//--- show the raw array
document.getElementById('container').innerHTML = jArray[0];
</script>
<?php
print_r($resultArray);
?>
</body>
</html>

Related

How can I prevent `[` and `]` to be parsed as array in JavaScript from PHP?

I have array in my PHP like this:
$arr['itemDetail[0][itemDescription]'] = Sample Product;
$arr['itemDetail[0][itemPrice]'] = 50000;
$arr['itemDetail[0][itemQty]'] = 2;
$arr['itemDetail[1][itemName]'] = Sample Product Again;
$arr['itemDetail[1][itemDescription]'] = Sample Product Again;
$arr['itemDetail[1][itemPrice]'] = 150000;
$arr['itemDetail[1][itemQty]'] = 1;
That array will be parsed into URI with:
$uri = '/process?'.http_build_query($arr);
Then I retrieve the parameter in JavaScript with:
<?php foreach ($params as $_key => $_val): ?>
<script>console.log("<?php echo $_key; ?> <?php echo $_val; ?>");</script>
<?php endforeach ?>
Why does in my JavaScript console the value in $_key and $_val returned itemDetail Array?
What I expect for the console.log(); is to return:
itemDetail[0][itemDescription] Sample Product
itemDetail[0][itemPrice] 50000
itemDetail[0][itemQty] 2
itemDetail[1][itemName] Sample Product Again
itemDetail[1][itemDescription] Sample Product Again
itemDetail[1][itemPrice] 150000
itemDetail[1][itemQty] 1
And not
itemDetail array
What is the problem?
PHP array is read by 'echo' as word 'array'. You need to encode array to js-string by PHP and then parse it with JS:
<?php foreach ($params as $_key => $_val): ?>
<script>console.log("<?php echo $_key; ?> JSON.parse('<?php echo json_encode($_val); ?>')");</script>
<?php endforeach ?>

How to insert a PHP 'while loop' into JavaScript code?

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>

Unable to show php variable in javascript?

I am unable to show php variable in javascript;
this is my code here:
<script type="text/javascript">
$(document).ready(function (){
var n=<?php echo json_encode($count)?>;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('wrapper').appendChild(div);
<?php
$query="select * from shop_product where shop_uniqueid='$unq'";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$product=$row["in_product"];
?>
var product=<?php echo $product?>;
$('#'+div.id).html(product);
<?php
}
?>
}//for loop ends
});//ready ends
</script>
here i am trying to pass var product in html() of which value is coming from php like: var product=<?php echo $product?>;
but when doing so php value is not coming in Javascript's var product.
when I pass $('#'+div.id).html("abcd"); abcd value is showing in divs.
please help me.
Compare the first place you take data from PHP and put it in JavaScript:
var n=<?php echo json_encode($count)?>;
with your attempt to assign the product value:
var product=<?php echo $product?>;
You haven't converted the data from plain text to JavaScript in the second line. Use json_encode there too.

JSON Encode converts to null - so weird

This is the weirdest thing i've seen. I have an array that I created with php - then I used JSON_Encode to use it with a FLOT Graph. I echoed out the encoded array once - and it's perfect.
Then randomly, another alert box appears with "null".
Subsequently, the script also has a "null" when i echo it into the javascript.
the var d1 is null when I inspect it...
At first I get an alert box with [[0,50],[1,3],[2,488],[3,25],[4,90],[5,50],[6,90],[7,50],[8,5]] -- then I get a second alert box WHICH I DID NOT CODE with "null".
code:
<?php
$num = 0;
while($row = $sql->fetch(PDO::FETCH_OBJ)){
$line[] = array($num,intval($row->percent));
$num ++;
}
$TEST = json_encode($line);
echo "<script>alert('".$TEST."');</script>";
?>
<script>
var d1 = <?php echo $TEST;?>;
$(document).ready(function () {
$.plot($("#chart"), [d1]);
});
</script>
Output from Inspector:
var d1 = []; //Notice the empty array
$(document).ready(function () {
$.plot($("#chart"), [d1]);
});
Use $line = array(); for empty data from while loop
$line = array();
while(....
You can check empty
if(count($line)!=0) {
$TEST = json_encode($line);
echo "<script>alert('".$TEST."');</script>";
}
UPDATE:
$TEST = json_encode($line);
echo "<script>$.plot($('#chart'), \"<?php echo $TEST; ?>\");</script>";

how to get the value of array sent from AJAX POST in php?

i am having a probelem with ajax multiple delete. I've sucessfully set the values of the checkbox slected in a variable.
the problem i have to solve is how to get the value of the sent array in php.
here is the ajax post code
<script>
$("#delete-btn").click(function(e){
e.preventDefault();
var id = new Array();
$(".check:checked").each(function() {
id.push($(this).attr('value'));
});
$.post("../ajax/multiDelete.php",{id:id},function(data){
alert(data);
});
});
</script>
now, the php page
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
echo $value;
}
}
?>
when the data is alerted, i only get "array";
i do not know about JSON, so if there is anything i can do without it then your help is most appreciated! thanks : D
Since id is an array and in your code you are wrapping it inside an array again. Instead of that,do this :
<?php
if(isset($_POST['id'])){
// Don't use array($_POST['id']) as id is already an array
$id = $_POST['id'];
foreach($id as $value){
echo $value;
// Here you'll get the array values
}
}
?>
If you want retun array from php - user json_encode()
echo json_encode(array($_POST['id']));
P.S. JS function alert() can`t print arrays or object. Use console.log(data) and you will see result in developer console of your browser.
This is not related to your question, but I just wanted to show you a better way of getting the id values, without creating a new array variable and then pushing items into the array, by using the jQuery .map() method:-
$("#delete-btn").click(function (e) {
e.preventDefault();
// Get all the values in the array 'id' variable
var id = $(".check:checked").map(function () {
return this.value || 0;
}).get();
$.post("../ajax/multiDelete.php", { id: id }, function (data) {
alert(data);
});
});
Hope this helps!
Don't pass array variable in AJAX. Convert id array to JSON using JSON.stringify(id).
In PHP backend,use
<?php $val = json_decode($_REQUEST['id']);
foreach($val as $ids){
echo $ids;
}
use $val array to proceed further in php.
You have to access your checked value by-
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
foreach($value as $value1){
echo $value1;
}
}
}
?>
Because this is an array inside array.

Categories

Resources