1

I need to store the value of php variable $Q_ID in javascript array at index 0. Here is my code for storing it in javascript array record[0].

var record= [];
var choice= [];
var correct=[];

 record[0]=<?php echo $Q_ID ?>;/* Showing refernce error (ReferenceError: CSE6014 is not defined record[0]=CSE6014) */;

 correct[0]=<?php echo $corr ?>;

And this is the php code to get the value of Q_ID. I have placed the php code before tag in the page and the javascript code is in the body at the last position.

$sql= mysql_query( "select * from questions where Q_ID like '{$code}%' order by RAND() limit 1" ) or die(mysql_error());

$rows = mysql_fetch_array($sql);
$Q_ID = $rows['Q_ID'];
$question= $rows['Question'];
$opt1=$rows['Option_1'];
$opt2=$rows['Option_2'];

I have placed the php code before tag in the page and the javascript code is in the body at the last position. But everytime I execute this code it shows reference error in firebug console window.

ReferenceError: CSE6014 is not defined record[0]=CSE6014;/* Showing refernce error (ReferenceError: CSE6014 is not defi...

I don't know what I am doing wrong. Please help me. Thanks in advance.

5
  • 1
    Use record[0] = '<?php echo $Q_ID ?>'; Commented Jul 3, 2015 at 7:18
  • Can you please tell me how to use statement like this if(record.length< <?php echo $NoOfQuestion-1; ?>) where $NoOfQuestion is an integer. Commented Jul 3, 2015 at 9:11
  • What's the value of echo $NoOfQuestion; Commented Jul 3, 2015 at 9:12
  • I am retrieving its value from database. Consider it can be any integer value (maximum 100). Commented Jul 3, 2015 at 9:15
  • You can simply make a use of another variable as var myvar = <?php echo $NoOfQuestion; ?>-1 and if(record.length< myvar; ?>) and be sure that the value within your php code must be int and not a string Commented Jul 3, 2015 at 10:08

1 Answer 1

3

As $Q_ID and $corr are strings, you need to surround string with quotes. You can use either single quote ' or double quote ".

Use following code(Notice the quotes around the PHP tags):

record[0] = '<?php echo $Q_ID ?>';
correct[0] = '<?php echo $corr ?>';
Sign up to request clarification or add additional context in comments.

6 Comments

Sorry sir but its not working in this case. "$NoOfQuestion" is a number not string.
@vishnupriya Try if(record.length< parseInt('<?php echo $NoOfQuestion-1; ?>')
It is giving this error in firebug console SyntaxError: unterminated string literal if(record.length< parseInt('<br />
@vishnupriya if(record.length< parseInt('<?php echo $NoOfQuestion-1; ?>'))
Sir it is giving unterminated string literal syntax error
|

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.