Saving variables within while loop - javascript

not pretty sure how you do this. But I want to save my javascript variables as data(1,2,3,4,...) in my while loop. Happy for any help! Thanks
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
?>
<script>
var id = '<?php echo $id; ?>'; //1,2,3,4,5,6,...
var data = '<?php echo $id; ?>'; // Example - Data 1 = Frog, Data 2 = Bird
// So here I want to sava variables so the name will be
// var "data+'id'";
// And the output is data for that row
</script>
<?php
}
?>
//And here outside I want to use the variables like this:
document.write(data1); writes out "Frog"
document.write(data2); writes out "Pig"

<script>
var jsData = [];
<?php
$id = 0;
while($rows = mysql_fetch_array($data)){
$data = $rows['data'];
?>
jsData[<?php echo $id; ?>] = '<?php echo $data; ?>';
<?php
$id++;
}
?>
</script>
This would yield a JS Array called jsData where your ID is the index and which is filled with the PHP $data values.

Declare $data = new Array(); just before the WHILE LOOP then in the WHILE LOOP you could do $data['id'][$id]= $id which will collect all the IDS.
Add $data['data'][$id]= $row['data'] below it so as also to collect each data that you want.
in the script tag do this:
var id = <?php echo '['.join(',', $data['id']).']' ?> //will create --> [1,2,3,4,5,6,7]
var data = <?php echo '['.join(',', $data['data']).']' ?> //--> ['cat', 'dog', 'cow', 'sheep']
now you can access the variable in the Javascript array created eg. $data[0] // 'cat'

Related

passing array data from PHP to Javascript

I am fetching an array from a MySQL result into a array variable. I can successfully use a simple php echo line in the javascript beneath to grab the first $row element, but I want to use json_encode to get the whole array at once.
When I do this and try to set a javascript var to the first array element something goes wrong and even the single var method stops working.
<?php
.
.
.
while($row = $result->fetch_array(MYSQLI_NUM)) {
$row1 = $row[0];
}
?>
<script type="text/javascript">
var RowArray = <?php echo json_encode($row); ?>;
var RA1 = RowArray[0];
window.alert(RA1);
var Row1 = '<?php echo $row1; ?>';
window.alert(Row1);
</script>
Make an array containing all the records:
$rows = [];
while ($row = $result->fetch_array(MYSQLI_NUM))
{
// do custom modifications to $row if neededed
$rows[] = $row; // push to array
}
Or just:
$rows = $result->fetch_all(MYSQLI_NUM);
And then use json_encode() with $rows.

PHP MySQL value pass to JavaScript

hei,
$i=0;
while($row = $result->fetch_assoc()) {
echo "
<tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>";
this part works...it give me -> 1 test1 url1.de 2 test2 url2.de ...
So what I want is to pass the URL to a JavaScript Array...by doing in phpscript
$urlarray[]=$row["MusikURL"];
echo $urlarray[$i]; // gives me url1.de url2.de url3.de
i++; // to fill $urlarray[1] [2] [...] with urls
How do I pass the urls to a JavaScript Array so that I can access to those by
javascriptarrayurl[1] javascriptarrayurl[2] (result should be a clear url) ... I got troubles with JSON :c
thanks in advance !!
You can use jQuery and have something like
<?php
$returnArray = array();
while ($row = $result->fetch_assoc()) {
array_push($returnArray, $row);
}
$jsonArray = json_encode($returnArray);
?>
<script>
$(document).ready(function () {
var objArray = $.parseJSON("<?php echo $jsonArray; ?>");
for (var i = 0; i < objArray.length; i++) {
var row = objArray[i];
console.log(row);
// Now here you have access to row.Number row.MusikURL
}
});
You can use json_encode() to convert a PHP variable to its Javascript literal notation.
<script>
var urlarray = <?php echo json_encode($urlarray); ?>;
</script>

How to use php with sql query in javascript

var phpCode = '<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>';
alert(phpCode);
this is my code. how to make it work ????
Try this.
First initialize, variables to null.
$professorName = "";
$professorSurname = "";
This is because, if php code enters else part, you will not get any error in javascript part.
<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>
<script>
var professorName = "<?php echo $professorName ?>";
var professorSurname = "<?php echo $professorSurname ?>";
alert(professorName);
alert(professorSurname);
</script>
PHP is a server-side language. So it is processed on a server. Therefore you cannot have a PHP code in javascript.
If you want to have javascript managed some editing in database, you can use AJAX to do it without reloading the page.

Assigning PHP Variables To Javascript Variables Not Working

I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.

array from php to javascript (need fresh decision)

I have found these two ways:
1st way (width incorrect)
<?php
$arr = new Array (...);
?>
<input id="arr" value="<?php echo json_encode($arr); ?>" hidden>
<script>
$(function (){
var arr = $("#arr").val(); // array with trash
});
</script>
2nd (we need control sequence)
<?php
$arrJS = json_encode($arr);
?>
<script>
var arrJS = <?php echo $arrJS; ?>; // good array
</script>
Question: Is there a better attempt?
Have you considered using AJAX? Here's an example:
Javascript:
$.ajax( "example.php" )
.done(function(json) {
var jsObject = json;
})
and in your 'example.php' file:
<?php
$arr = new Array ('element1'=>'value1', 'element2'=>'value2');
header("Content-type: text/json");
echo json_encode($arr);
exit;
?>

Categories

Resources