1

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

manuzi1
  • 1,068
  • 8
  • 18
  • More information here: http://stackoverflow.com/questions/415868/get-variable-from-php-to-javascript – Kenzo Nov 14 '12 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 Nov 14 '12 at 18:34

2 Answers2

1

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • @user1824579 If you feel someone has sufficiently answered your question, please click the checkmark to mark it as the accepted answer ^^ Welcome to SO! – Nick Rolando Nov 14 '12 at 18:55
0

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.

emartel
  • 7,712
  • 1
  • 30
  • 58