Sending PHP array to JavaScript issue - javascript

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

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] . '");';
}

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>

Trouble passing associative array from javascript to php and insert it into mysql database through prepared statements

http://jsfiddle.net/kqd7m5nb/
Just click on the insert data button, notice an alert box. This is an associative array. These are the values I want to pass into my php file.
In The php file, I get a Post value containing all the data I passed from my ajax data. I decoded It using json_decode. The data is now extracted as a php array of type stdClass. And I am now using prepared statements to insert all of the php array through the for loop statement.
Using Xdebug, the arrow stops inside the for loop of the php file. And after that, nothing gets inserted into my database. I also noticed when evaluating the 'count($value)' on php on xdebug, it returns 1 instead of 3. And evaluating $value[0]->fname in XDEBUG also returns an error.
sample.js
$('#ajax').click(function() {
var values = $('#mytable tbody tr').map(function() {
return {
fname : $('td:eq(0)',this).text(),
lname : $('td:eq(1)',this).text(),
point : parseInt($('td:eq(2)',this).text())
}
});
var valuesDebug = "";
for (var i = 0; i < values.length; i++)
{
valuesDebug += " " + values[i]["fname"] + " " + values[i]["lname"] + " " + values[i]["point"] + "\n";
}
alert(valuesDebug);
var valueStringed = JSON.stringify(values);
$.ajax({
"type":"POST",
"url":"insertData.php",
"data":{value : valueStringed},
"success":function(data){
alert('Done inserting the current table values');
}
});
});
insertData.php
<?php
if (isset($_POST['value']))
{
$value = json_decode(stripslashes($_POST['value']));
}
$mysqli = new mysqli("localhost","root","password","test");
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$stmt = $mysqli->prepare("INSERT INTO team VALUES (NULL,?, ?, ?)"); //NULL is auto increment primary key id
$stmt->bind_param('ssi', $fname, $lname, $point);
if (count($value) > 0)
{
for( $i = 0 ;$i < count($value);$i++){
$fname = $value[$i]->fname;
$lname = $value[$i]->lname;
$point = $value[$i]->point;
$stmt->execute();
}
}
$stmt->close();
$mysqli->close();
?>
At a glance you need to be doing:
$stmt->bind_param('ssi', $fname, $lname, $point);
in your for loop as your defining them in the loop, if you do it above as you have - the variables are undefined.
So try:
$stmt = $mysqli->prepare("INSERT INTO team VALUES (NULL,?, ?, ?)");
if (count($value) > 0)
{
for( $i = 0 ;$i < count($value);$i++){
$fname = $value[$i]->fname;
$lname = $value[$i]->lname;
$point = $value[$i]->point;
$stmt->bind_param('ssi', $fname, $lname, $point);
$stmt->execute();
}
}
This code now works.
Please see my original javascript code.
It seems on this part I added an array valuesDebug and copied the contents from the values array through the push method. I don't know how exactly why this works. Is there a way to make this shorter?
BTW The first line is the row cell contents of my table being converted into the values array.
var values = $('#mytable tbody tr').map(function() {
return {
fname : $('td:eq(0)',this).text(),
lname : $('td:eq(1)',this).text(),
point : parseInt($('td:eq(2)',this).text())
}
});
var valuesDebug = [];
for (var i = 0; i < values.length; i++)
{
valuesDebug.push({fname: values[i]["fname"],lname: values[i]["lname"],point: values[i]["point"]});
}
var valueStringed = JSON.stringify(valuesDebug);
// passes valueStringed into ajax ...

What is the best way to Parse a PHP Array into 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 );
});

jQuery - Load info from database, into different variables?

Basically I can do so it prints out for example one field from the table, but I want to have all of them to different tables or whatever, how would I achieve this? I got this as my save/load code:
// Save/Load data.
$('').ready(function() {
if($.cookie('code')) {
$.ajax({
type: "POST",
url: "ajax/loadData.php",
data: "code=" + $.cookie('code'),
dataType: "json"
success: function() {
var json = $.parseJSON();
var coins = json.coins;
var lvl = json.lvl;
$('#test').html('lvl: ' + lvl + ' coins: ' + coins);
}
});
console.log('Loaded data from the database with the code ' + $.cookie('code'));
} else {
// Generate save&load-code
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 64;
var randomCode = '';
for(var i = 0; i < string_length; i++) {
var num = Math.floor(Math.random() * chars.length);
randomCode += chars.substring(num, num+1);
}
// Save code in cookies & database
$.cookie('code', randomCode);
console.log('Generated and saved code ' + $.cookie('code'));
}
});
Note that I do know that I do not have a save-function/ajax yet, but I'm working on the load feature right now.
This is my loadData.php file:
<?php
include '../inc/_db.php';
$code = $_GET['code'];
$query = mysqli_query($db, "SELECT * FROM data WHERE code='$code'");
while($row = mysqli_fetch_array($query)) {
echo $row['coins'];
}
?>
Simple enough, yeah. This prints out the amount of coins that belongs to the specific user. Here's the table structure:
How would I go about to load both coins AND the lvl field, into different variables or alike, so I can use them properly.
Looks like Joroen helped you out with the ajax side and hopefully you added the comma he was talking about. The php/mysqli part can be written like this:
<?php
include '../inc/_db.php';
$code = $_GET['code'];
$query = mysqli_query($db, "SELECT * FROM data WHERE code='$code'");
$row = mysqli_fetch_array($query));
print json_encode($row);
?>
In reality this code is scary because you're not cleaning any of the incoming data and using it directly in a SQL statement. Since you already know it's only allowing A-Za-z0-9 characters you should check the value of $_GET['code'] to make sure it's safe to use. I also highly recommend using mysqli prepared statements to avoid some of the funny stuff that can happen with tainted input.
this is probably a bad programming practice but that is how i would do it.
while($row = mysqli_fetch_array($query)) {
$return = $row['coins'].",".$row['id'; //separate the send the values as a comma-separated string
echo $return;
}
the js would look like this
$('#coins').load('ajax/loadData.php?code=' + $.cookie('code')); //collect the values here
var values = $(#coins).text(); //save the values in a srting
var array_of_values = values.split(","); //split the string at a delimiter and save the values in an array
mind you, this is not likely to work if the query returns multiple rows

Categories

Resources