How to access PHP array element using JavaScript variable as key? - javascript

So I am trying to make a simple academic system.
I made dynamic boxes which show course information.
Core code looks like this
function addcourses(){ //(numcourses)
var num_courses= <?php echo $_GET['num']?>; //=numcourses
var newdiv;
var divIdName;
var i=0;
for(i=1;i<=num_courses;i++){
var divtoadd = document.getElementById('courselist');
newarticle = document.createElement('article');
divIdName = 'course'+i;
newarticle.setAttribute('id',divIdName);
newarticle.innerHTML ='<div class="box"><h2><?php echo $course_num_arr[i]?></h2><div class="content"><p>Credit Hours: <?php echo $credit_arr[0]?> </p><p>Professor: <?php echo $prof_arr[0]?></p><p>Average GPA: <?php echo $avg_arr[0]?></p><p>GPA: <?php echo $gpa_arr[0]?></p></div></div>';
call_course();
divtoadd.appendChild(newarticle);
}
}
The problem is with <?php echo $course_num_arr[i]?> since i is the variable from javascript, I don't know how to deal with this.
I want to echo $course_num_arr[1] when i = 1 and $course_num_arr[2] when i = 2 and so on.

If you don't want to use ajax call and wants to place the code in the PHP file, your can use json_encode() function. Please refer below code.
<?php
$cources = array( "0" => array ("name" => "maths","credits" => 30),"1"
=> array ("name" => "physics","credits" => 30));
?>
<script>
data=<?php echo json_encode($cources); ?>;
for(i=0;i<data.length;i++){
alert(data[i].name)
var h = document.createElement("H1");
var t = document.createTextNode(data[i].name);
h.appendChild(t);
document.body.appendChild(h);
}
</script>

Related

How to create var javascript via php?

How to create var javascript via php ?
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words = $bad_words."".$resilt_row [word].",";
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?PHP echo $bad_words; ?>"];
alert(bad_words);
</script>
I want to get var javascript like this var bad_words = ["fuck", "ass"];
When alert it's get only blank result.
How can i do that ?
<?php
include("connect.php");
$query = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$badWords = [];
while($row = mysqli_fetch_array($query))
{
$badWords[] = $row['word'];
}
js
<script>
var bad_words = <?= json_encode($badWords); ?>;
alert(bad_words[0]);
console.log(bad_words);
</script>
I don't like gluing the strings if it's an array then pass it as an array with json_encode() function. Also in views it's better to use short syntax with <?= ?> tag
The string you're making is not the one you want.
You're not adding quotes.
Do this instead, using an array is better:
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$bad_words = array();
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = "'" . $resilt_row[word]. "'";
}
And then, down in your js:
var bad_words = ["<?php echo implode(",", $bad_words) ?>"];
or (for short)
var bad_words = ["<?= implode(",", $bad_words) ?>"];
If you want alert them as a string you can do it like this:
<script>
var bad_words = ["<?php echo implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
Otherwise, you can print them as an array:
<script>
var bad_words = <?php echo json_encode($bad_words) ?>;
console.log(bad_words);
</script>
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = $resilt_row['word'];
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?php print implode('","',$bad_words); ?>"];
alert(bad_words);
</script>

PHP file ouputs the javascript code itself and not running

I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>

for loop to set javascript variable = to a php variable

I am working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);

Assigning PHP variable to PHP array

I want to assign some php to a javascript variable like:
var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;
but ends up with: 1 (instead of 2000).
Here's my troubleshooting:
I have an array in a php class:
<?php
class ResourceArray {
public static $goldLevel = array(
0, 2000, 10000
),
I've tried to assign through a couple of variables to find the problem with no luck:
var goldLevel = <?php $user->getResource($data -> id, "goldLevel") ?>;
var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;
var goldPrice1 = <?php echo ResourceArray::$goldLevel[1]?>;
This writes:
var goldLevel = 1;
var goldPrice = 1;
var goldPrice1 = 2000;
Finally I tried to assign a php variable to put in:
PHP: $goldLevel1 = $user->getResource($data->id, "goldLevel");
$goldLevel2 = 1;
js: var goldPrice2 = <?php echo ResourceArray::$goldLevel[$goldLevel1]?>;
var goldPrice3 = <?php echo ResourceArray::$goldLevel[$goldLevel2]?>;
This ends up like:
var goldPrice2 = ;
var goldPrice3 = 2000;
When I echo $goldLevel1 and $goldLevel2, it shows 1 and 1.
Trying this works fine with me:
<html><body>
<?php
class ResourceArray {
public static $goldLevel = array(
0, 2000, 10000
);
}
// set gold price to second entry of goldLevel array
$goldPrice = ResourceArray::$goldLevel[1];
// check to make sure we have a valid number
if (!is_numeric($goldPrice) || $goldPrice < 1)
$goldPrice = 0;
// this outputs 2000
echo $goldPrice;
?>
<script>
var goldPrice = <?php echo $goldPrice; ?>;
alert(goldPrice);
</script>
</body></html>
Try using json_encode()
Documentation for json_encode
Use it like this
var goldPrice = <?php echo json_encode(array(0, 2000, 10000))?>;
Just replace the array for the dynamically created one.
First of all create a variable of json
var jsonO = <?php echo json_encode(array(0, 2000, 10000))?>;
this will be a json string, convert it to javascript array
var goldPrice = $.map(jsonO, function(el) { return el; })
then use goldPrice array.

How to pass PHP (index.php file ) Variable value to external JAVASCRIPT .js File?

Actually this code is wrote in index.php file but now i want to pass this javascript array value to external js file.
<?PHP
$qry2 = mysql_query("SELECT table_no FROM table_info");
while($res2 = mysql_fetch_array($qry2))
{
static $i = 0;
$i++;
$reg_table[$i] = $res2['table_no'];
}
?>
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
I want the bookedSeats variable to be in the external table.js file.
You have jQuery tag in there, so I am going to give you this... use Ajax:
test.php
<?php
// Handle Ajax Request
if (isset($_GET['loadData']))
{
// Query your db here, im building dummy data
$results = array();
for ($i = 0; $i < 10; $i++) {
$results[] = 'Data '. $i;
}
// Return Data
exit(json_encode($results));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Load Data Via Ajax
$.getJSON("test.php?loadData", function(bookedSeats)
{
console.log(bookedSeats);
});
</script>
When the page loads, we get the result like this:
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
This can be greatly simplified and made immune to XSS:
<script>
var bookedSeats = <?php echo json_encode(array_values($reg_table)); ?>;
</script>
You can now refer to bookedSeats in your external .js file, but only if that file is being run after this inline script has been placed. In other words, putting:
<script src="external.js"></script>
after the <script>...<?php ... ?>...</script> is okay, but putting it before is only okay if you are deferring its execution - it's just safer to put it after ;)
I have an alternative solution for you eventually even if Latheesan Kanes's one is right.
Mine is just given as a trivial exemple if you have access to a constructor in your Javascript object in the table.js file.
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)

Categories