lmpearce1
lmpearce1

Reputation: 179

Cannot send a database timestamp through JavaScript but can send other values

I'm using PHP5, MySQL, JavaScript and Fusion Charts.

I have the following time value returned from a database: 2011-12-19 12:00:00

After taking it from the database, I try to pass it through a JavaScript strURL to get it to another page where I can make further database calls using this value. The problem I have is that the JavaScript fails whenever I send it through a date/time. I can send through any other value type and it works so the problem seems to be with the time stamp. I've tried converting it to string before it is passed (just to be sure it's not one already) and that doesn't work. I'm guessing it's to do with the characters within the value. Any idea how to get around this?

The database call in PHP and then sending fields into the JavaScript:

$strQuery = "SELECT unit, watts, time, device, siteid FROM inverter WHERE time = '2011-12-19 12:00:00' AND siteid = '842'";
$result2 = mysql_query($strQuery) or die(mysql_error());

if ($result2) {
    while($ors2 = mysql_fetch_array($result2)) {
        $thetime = (string)$ors2['time'];
        $strXML .= "<set color='58ACFA' label='" . $ors2['device'] . "/" . $ors2['unit'] . "' value='" . $ors2['watts'] . "' link='javaScript:updateChart(" . $ors2['unit'] . " , " . $ors2['device'] . " , " . $ors2['siteid'] . " , " . $thetime . ")'/>";
    }
}

And then the JavaScript function:

function updateChart(first, second, third){
    //DataURL for the chart
    var strURL = "FactoryData.php?factoryId=" + first + "&device=" + second + "&siteid=" + third;
    FusionCharts("FactoryDetailed").setXMLUrl(strURL);
}

Upvotes: 1

Views: 255

Answers (2)

Felix Loether
Felix Loether

Reputation: 6190

link='javaScript:updateChart(" . $ors2['unit'] . " , " . $ors2['device'] . " , " . $ors2['siteid'] . " , " . $thetime . ")'

This JavaScript becomes something like

updateChart(341, 454, 842, 2011-12-19 12:00:00);

The first three arguments are valid numbers (I assume the IDs are integers), but the fourth argument causes a syntax error. What you need to do is wrap it in quotes to make it a string:

link='javaScript:updateChart(... " , \"" . $thetime . "\")'
                                     ^^                ^^

Now the JavaScript should be like this:

updateChart(341, 454, 842, "2011-12-19 12:00:00");

Upvotes: 1

amiuhle
amiuhle

Reputation: 2773

You can either convert the date to a timestamp with something like

new Date('2011-12-19 12:00:00').getTime()

or encode it using encodeURIComponent('2011-12-19 12:00:00')

The latter is probably the better solution, as it works with all kinds of values, not only dates. You can use decodeURIComponent if you want to read the parameters on the client side, that should already be working fine on the server side.

Upvotes: 0

Related Questions