killertoge
killertoge

Reputation: 345

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 !!

Upvotes: 0

Views: 51

Answers (2)

Ray
Ray

Reputation: 793

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

Upvotes: 1

Barmar
Barmar

Reputation: 780994

You can use json_encode() to convert a PHP variable to its Javascript literal notation.

<script>
var urlarray = <?php echo json_encode($urlarray); ?>;
</script>

Upvotes: 1

Related Questions