What is the best way to Parse a PHP Array into Javascript? - javascript

I currently have a PHP file that accesses my MySQL database and pulls out the Names and Scores for each player and stores them in an array.
//This query grabs the top 10 scores, sorting by score and timestamp.
$query = "SELECT * FROM Score ORDER by score DESC, ts ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
//We find our number of rows
$result_length = mysql_num_rows($result);
//And now iterate through our results
for($i = 0; $i < $result_length; $i++)
{
$row = mysql_fetch_array($result);
echo $row['name'] . "\t" . $row['score'] . "\n"; // And output them
}
What is the best way for me to get both the name and the score from the PHP File and store them in a Javascript Array?

The best way to store them is store them in json. Use following function
json_encode(arrayname);
and in html use
$.parsejson(responsevariable);
to get original value.

I would suggest to give json_encoded array to javascript variable (json_encode()), and use javascript json decoding functionality, so you will get what you want :)

Create a result variable
$results = array();
Store your results in it in your loop
array_push($results, array("name" => $row["name"], "score" => $row["score"]));
At the end return it with
echo json_encode($results);
When you get the response on the front end, you can take the response data and JSON.parse() it to turn it into a variable that you can access
var results = JSON.parse(data);
results.forEach(function(result){
console.log( result.name +" - "+ result.score );
});

Related

HTML collection getting parsed to JavaScript through PHP when it should be a String

I have a database that I use to create a resource of string values for example
|Boxers|1|
|Shirts|2|
etc
I then use php to populate a array with this resource
eg
$myArr = arrary['Boxers', '1', 'Shirts', 2]
then I parse the array as a JavaScript array through an echo and .push() each element within a for loop
This JS array then becomes the argument of a JS function call.
As you can see below.
<?php
if(isset($_SESSION["username"])){
$cartArr = array();
$sql = "SELECT item, quantity FROM shop_cart WHERE user = 'Mike'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
array_push($cartArr,$row["item"],$row["quantity"]);
}
}
echo '<script> let paramArr = [];';
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push(' . "$cartArr[$x]" . ');';
}
echo 'cleanUpVue(paramArr);
</script>';
}
?>
The problem is that every element that is a String such as Boxers, Shirts keeps getting parsed as an HTML Collection and not just as a String. I'd like to know what I can do to avoid this behavior? As all I need is a JS array of String elements (4 as per the example) and nothing else
terrible what an obvious oversight on my part, I simply forgot to include quotation marks before concatenating the variable name, as such JS was trying to evaluate the original Strings as they also matched id's within the DOM
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push("' . $cartArr[$x] . '");';
}

Access current users username in javascript

I have an object that I get from a "SHOW tables" query. Unfortunately, I get an array inside an object has a name that changes based on what user is logged in (eg. data[1].Tables_in_kazura). How can I either access what user is logged in or even better rename the result from PHP, from Tables_in_xxx to whatever I want?
$.getJSON("php/loadCategories.php", function(data) {
for (let i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
This is my PHP
$sql = "SHOW tables";
$rows = $db->query($sql);
$length = $rows->num_rows;
$result = array();
for ($i = 0; $i < $length; $i++) {
$row = $rows->fetch_assoc();
array_push($result, $row);
}
echo json_encode($result);
The echo $result gives me:
Object { Tables_in_kazura: "drinks" }
Object { Tables_in_kazura: "food" }
and what ever else the user (user here is kazura) has in his tables.
Since it is based on username, Tables_in_USERNAME will vary and I don't know how I can access the data inside it.
The optimal solution would be that echo json_encode($result); returns Object { categoryname: "drinks" } and so on no matter what user is logged in
If the tables all have the same structure then you can just use raw SQL although this is really not advised as it leaves you open to attack. The problem seems to be that you're using a table per user rather than following a relational convention. But as a short answer, you cant do what you're looking for within a sanitized SQL query as dynamic table names aren't supported.
I figured out a way to get my wanted result in javascript. It's not pretty, but it works.
let propertyName = Object.keys(data[1]).toString();
//Rename the query from Tables_in_USERNAME to categoryname
data = data.map(function(obj) {
obj['categoryname'] = obj[propertyName];
delete obj[propertyName];
return obj;
});
I rename all the object keys to categoryname instead of changing the SQL query.

Inserting PHP DB result into Javascript array

How can i insert PHP db result query to a javascript array. I have set of values in my Database and I want to get those values and store it in a javascript array. This is my query
$query = $db->query("SELECT * FROM members");
while ($row = $query->fetch_assoc()) {
echo $row['names'];
}
And I want to store it in a javascript array like this
var names = ['John','Chris','Leo'];
This is my code but im getting an error.
var names = [
<?php while ($row = $query->fetch_assoc()) {
echo $row['skill'];
} ?>
];
Do this instead.
$names = [];
<?php while ($row = $query->fetch_assoc()) {
$names[] = $row['skill'];
}
$javaScriptArray = json_encode($names);
?>
JavaScript is run on the browser while PHP is run on the server. They don't really integrate with each other. To make the array available in javascript do something like this.
<script>
var arr = <?php echo $javaScriptArray; ?>;
</script>

Sending PHP array to JavaScript issue

I have an AJAX POST function that runs a PHP file that queries a MySQL database. It uses the "CONCAT" option in MySQL and then adds each row it receives into an array. I need to get that array from PHP to JavaScript, how would I go about doing this?
I've tried looking it up but nothing that I found either I didn't understand how to actually implement it, or it just flat out didn't work.
$sql_query = substr($sql, 0, -3);
$result = $connection->query($sql_query);
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$rowCount = mysqli_num_rows($result);
echo "Total Bans: " . $rowCount . "\r\n";
echo "\r\n";
$bans = [];
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
I included that part of my PHP code if you need it.
I tried this:
echo(json_encode($bans));
.
success: function(data) {
document.getElementById('outputtext').innerHTML = '';
var array = new Array();
array = data;
document.getElementById('outputtext').innerHTML = array;
}
That returns everything, but adds a lot of "," between them.
Example of an index in the array:
[05-18] Daedalus banned EXAMPLE_USERNAME(EXAMPLE_GUID / EXAMPLE_IP) for EXAMPLE_REASON
I want all the lines from the $bans array to be put into an array in JavaScript.
When you usage echo(json_encode($bans)); that convert php array to json array. To use json in javascript you should first Parse that array like this
success : function(data){
result = JSON.parse(data) ;
}
Now you check this data console.log(result);
Access particular data through key like this
name = result.name;
This place in your code is wrong:
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
Because you cycle trough records with while and inside once more with for. Use only while:
while ($row = $result->fetch_row()) {
array_push($bans, $row);
}
Will pull all rows and without nulls.
In your case when you have only single column in your return from database you should use:
while ($row = $result->fetch_row()) {
array_push($bans, $row[0]);
}

Why does body onload require htmlentities on nested json_encode'd array?

I read database records, and create one PHP array() for each database record, then store each of these arrays as an element of a top-level PHP array(). The top level array is thus an array of arrays, and the nested arrays each contain the fields of one database record. Nothing special here.
I need to pass the nested array of database record arrays to two different javascript functions and so I use json_encode in PHP before passing the nested array:
CASE #1: the first pass of the nested json_encoded-d is to a Javascript function doSomeStuff( theNestedJsonEncodedArray) -- I used a hidden iframe technique to pass the nested array into javascript code (see below)
CASE #2: the other pass of the nested array is to my web page's body onload=handleLoad( theNestedJsonEncodedArray )
With Case #1, I do not need to use htmlentities( theNestedJsonEncodedArray ) in order for this json encoded array to be successfully used in my doSomeStuff() function.
With Case #2, the body onload=handleLoad( ) function will NOT EVEN EXECUTE. Unless I add an extra step. The extra step is this: after json_encode'ing the nested array, I have to call htmlentities() -- then and only then will my body onload=handleLoad( ) behave correctly.
I 100% fail to understand this. I do not understand why, in the case of my "PHP/iframe/javascript" scenario, json_encode() is sufficient to pass the nested array -- but my "body onload=handleLoad()** case, I need to use htmlentities() on the nested array, or the onload javascript function will not even execute.
Note here: there is zero html in my database records.
CASE #1 CODE -- uses a hidden iframe to pass javascript code to my web page:
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theTopLevelArray= array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$recordNum = $theRow[0];
$lat = $theRow[1];
$lng = $theRow[2];
$city = $theRow[3];
$state = $theRow[4];
// EACH NESTED ARRAY IS A TOWN with City, State, Latitude, Longitude
$nestedArray = array( $lat, $lng, $i, $recordNum, $city, $state);
$theTopLevelArray[] = $nestedArray;
}
$jsonArray = json_encode($theTopLevelArray);
echo '<script type="text/javascript">' . "\n";
echo 'var parDoc = parent.document;' . "\n";
$sendToWebpageStr = "parent.doSomeStuff( $jsonArray );";
echo $sendToWebpageStr;
echo "\n".'</script>';
// And in my web page's javascript code......
function doSomeStuff( theNestedJsonArray )
{
// Traverse the array of Towns and show their latitude and longitude
for (var i = 0; i < theNestedJsonArray.length; i++)
{
var town = theNestedJsonArray[i];
var lat = town[1];
var long = town[2];
alert("The lat, long are: " + lat + ", " + long);
// ALL THIS WORKS FINE.
}
}
CASE #2 CODE -- REQUIRES AN EXTRA STEP, A CALL TO htmlentities( )
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theTopLevelArray= array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$recordNum = $theRow[0];
$lat = $theRow[1];
$lng = $theRow[2];
$city = $theRow[3];
$state = $theRow[4];
// EACH NESTED ARRAY IS A TOWN with City, State, Latitude, Longitude
$nestedArray = array( $lat, $lng, $i, $recordNum, $city, $state);
$theTopLevelArray[] = $nestedArray;
}
$jsonArray = json_encode($theTopLevelArray);
$readyNowArray = htmlentities( $jsonArray );
// AND HERE'S THE 'body' ON MY PAGE:
<body onload="handleLoad( <?php echo $readyNowArray ?> )">
// HERE IS handleLoad()
function handleLoad( theNestedArray )
{
var town = theNestedArray[0];
alert("bl.js, handleLoad(), town is: " + town);
alert("bl.js, handleLoad(), town[0] is: " + town[0]);
alert("bl.js, handleLoad(), town[1] is: " + town[1]);
}
If I do not call html entities for CASE #2 -- the handleLoad() function does not even execute.
Is there some nuance here when echo'ing a PHP array in the body onload tag that is requiring the extra step of calling htmlentities() on the json array, while passing the json array directly into javascript from PHP code by way of an iframe is bypassing that somehow?
Is there some nuance here when echo'ing a PHP array in the body onload
tag that is requiring the extra step of calling htmlentities() on the
json array
Yes. You're echoing into HTML, for which you of course need htmlentities. If you don't, any quotes from the JSON will end your HTML onload attribute value, and the resulting js is nothing but a syntax error.
while passing the json array directly into javascript from PHP code
is bypassing that somehow?
Inside a <script>, nothing but </script> does need to be escaped.

Categories

Resources