I have a question. I get a variable from a DB lets call it carnumber with:
$data = mysql_fetch_array($result);
then to see the carnumber:
echo $data["carnumber"];
And now i need this carnumber in a javascript function with a for loop:
function example(text){
var mdstring ="";
var i=0;
var s;
var carnr = **"**<?php echo $data["carnumber"];?>**"**;
for(i=0;i<carnr;i++){
//run MD5
}
s=plain;
return s;
}
But this example does not work. Either with quotes (in strong) or without quotes. So how can i fix this mistake, that I can use my $data["carnumber"] in the javascript function?
best regards
-
More information here: stackoverflow.com/questions/415868/…Kenzo– Kenzo2012年11月14日 18:14:59 +00:00Commented Nov 14, 2012 at 18:14
-
Are you mixing PHP variables in a JavaScript script?! This doesn't make sense, you need to fetch your data through a query (consider jQuery - ajax) or pass directly the data when constructing your HTML.emartel– emartel2012年11月14日 18:34:05 +00:00Commented Nov 14, 2012 at 18:34
2 Answers 2
use json_encode:
var carnr = <?php echo json_encode($data['carnumber']); ?>;
it'll take your native php data and conver it to syntactically valid javascript.
1 Comment
The issue here is that $data is a PHP variable. You are trying to access it through JavaScript. There is no direct link with what processed the creation of the page on the server (PHP) and what happens on the client (JavaScript).
If you need to access the data dynamically, you will need to query the server again and ask specifically for the data contained in $data.
Consider taking a look at jQuery, it's a simple framework that will allow you to call ajax() and get through JavaScript new values from your server.