2

I have this code which works very well. But I wanted use mysql.

Here is the code that works:

<?php if (date('w') == 2) { { ?>
<script> $(function() {
var times = [
// mysql import start
{'id': '1', 'name': 'Mardi 5H55', 'end': new Date('2017-01-31 05:55:00'),},
{'id': '2', 'name': 'Mardi 8H40', 'end': new Date('2017-01-31 08:40:00'),},
{'id': '3', 'name': 'Mardi 11H30', 'end': new Date('2017-01-31 11:30:00'),},
{'id': '4', 'name': 'Mardi 14H05', 'end': new Date('2017-01-31 14:05:00'),}
// mysql import end
];
        // Initialize the table values
        $.each(times, function( key, value ) {
            $('#mau-mpl').append('<tr><td>'+value.name+'</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-'+value.id+'-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
        });
        function countdown()
        {
            var now = new Date();
            console.log('updating time');

            $.each(times, function( key, value ) {
                var left = value.end - now;
                var days = Math.floor( left / (1000 * 60 * 60 * 24) );
                var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
                var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
                var seconds = Math.floor( (left % (1000 * 60)) / 1000 );

                displayTime = '';
                if (days > 0) {
                    displayTime = + days + " jr   ";
                }
if (minutes > 0) {
                displayTime = displayTime + hours + " H   " + minutes + " Mn   "  + seconds + " Sec   ";
} 
                echo = "Deja parti"; 


                $('#player-'+value.id+'-expiration').text(displayTime)
            });
        }
        timer = setInterval(countdown, 1000);        
    });</script><?php } } ?>

As you see my data that I want to put is after mysql import start. I made a php file that fetches data from mysql and I have this result:

  • {'id': '1', 'name': 'Mardi 5H', 'end': new Date('2017-01-31 05:00:00'),},
  • {'id': '2', 'name': 'Mardi 6H', 'end': new Date('2017-01-31 06:00:00'),},
  • {'id': '3', 'name': 'Mardi 7H', 'end': new Date('2017-01-31 07:00:00'),},

The php file is:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
// {'id': '1', 'name': '5H', 'end': new Date('2017-01-31, 05:55:00'),},";
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
} $conn->close();
?>  

+---+----------+---------------------+
| 1 | Mardi 5H | 2017-01-31 05:00:00 |
+---+----------+---------------------+
| 2 | Mardi 6H | 2017-01-31 06:00:00 |
+---+----------+---------------------+
| 3 | Mardi 7H | 2017-01-31 07:00:00 |
+---+----------+---------------------+

How do I put the result in javascript variable between "mysql import start" and "mysql import end" ?

1
  • var javascript_var = <?php echo $your_value;?>. json_encode() would help you to make it easier. Commented Jan 31, 2017 at 10:13

3 Answers 3

1

You can do this :

var js = <?php echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "')}"; ?>

But warning, I remove bad characters on your object at the last :

echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
---------------------------------------------------------------------------------------------------------------------------------^-^^^^^
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @R3tep your code does'nt show me the remaining time
There is no good reason to manually craft a json string with concatenation.
0

You can set var with a lot diferent ways ,ajax,embebed javascript code inside php code...

When you want get a PHP object or var to javascript you need serialized the object to JSON in your php code, then you need set your JSON string and convert this string to a valid javascript object.

JSON is a string like this

"{'propertyname':'stringvalue','property2':true,'property3':null,'property':[...]}" 

If now you can parse JSON on javascript code block

index.php

<?php 
   $result = getData() // your data like you want =>[ multiple objects ]
   $resultJSON =  json_encode($result); // "[{..},{...}]"
?>
<script>
    var jsondata = parse.JSON('<?php echo $resultJSON ?>') ; 
</script>

But i think is better slice the html/javascript code from php code, and get vars from ajax for example.

1 Comment

I would not bother with parse.JSON(' and ').
0

You can use AJAX call to a PHP script to store the data into Javascript variables.

In the following file the AJAX call using JQuery is demonstrated to store the data into Javascript

<?php if (date('w') == 2) { { ?>
<script>
        $(function() {
            var times = $.ajax({
                url: 'api.php', //the script to call to get data          
                data: "", //you can insert url argumnets here to pass to api.php
                //for example "id=5&parent=6"
                dataType: 'json', //data format      
                success: function(data) //on recieve of reply
                {
                    return data;
                }
            });
            $.each(times, function(key, value) {
                $('#mau-mpl').append('<tr><td>' + value.name + '</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-' + value.id + '-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
            });

            function countdown() {
                var now = new Date();
                console.log('updating time');
                $.each(times, function(key, value) {
                    var left = value.end - now;
                    var days = Math.floor(left / (1000 * 60 * 60 * 24));
                    var hours = Math.floor((left % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    var minutes = Math.floor((left % (1000 * 60 * 60)) / (1000 * 60));
                    var seconds = Math.floor((left % (1000 * 60)) / 1000);
                    displayTime = '';
                    if (days > 0) {
                        displayTime = +days + " jr   ";
                    }
                    if (minutes > 0) {
                        displayTime = displayTime + hours + " H   " + minutes + " Mn   " + seconds + " Sec   ";
                    }
                    echo = "Deja parti";
                    $('#player-' + value.id + '-expiration').text(displayTime)
                });
            }
            timer = setInterval(countdown, 1000);
        });
    });</script><?php } } ?>

Following is the code which fetches the data from the database.
Let's call this file api.

<?php
$servername = "localhost";
$username   = "root";
$password   = "root";
$dbname     = "horaires";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql    = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

    //storing result into an array
    $array = mysql_fetch_row($result);
}
$conn->close();

//encoding the array into JSON
echo json_encode($array);
?>

1 Comment

Hi and thank you very much for your answer. But i want to get this result: {'id': '1', 'name': 'Mardi 5H', 'end': new Date('2017-01-31 05:00:00'),}, instead of ["1","2017-01-31 18:00:00","Mardi 5H Test","",""] with your code. And with this i fetch only first line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.