Where is the bug?

Hello

From google chrome console.
I got this error below.
localhost/:244 Uncaught SyntaxError: Invalid or unexpected token

It says the error is on line 244 ?
Below are the codes where the error resides.

<?php

        $content = $this->session->userdata('content_data'); 
        $topic = $this->session->userdata('topic');
        
        $qa_data = $this->session->userdata('qa_data');
        
        $end = '';
        $end_of_array = $this->session->userdata('condition');
        $init = $this->session->userdata('init');
        $total_array = $this->session->userdata('total_array');
        $result_msg = $this->session->userdata('result_msg');

        
        if($end_of_array === 'yes')
        {
            $end = '/end/';
        }

        #$init = $this->session->userdata('init');
        #showArray($qa_data);
        #echo 'Question: '. $qa_data[0]->question;
        #echo '<br>Answer: '. $qa_data[0]->answer;
        #echo '<br>Reference: '. $qa_data[0]->info;        
        #echo '<br> Minutes: '. $qa_data[0]->time;

?>




    <div id="landingqa">
        <br>
        <center>
            <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <!-- codesmastery-top -->
            <ins class="adsbygoogle"
                 style="display:inline-block;width:970px;height:90px"
                 data-ad-client="ca-pub-6956881401283026"
                 data-ad-slot="6762698841"></ins>
            <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
            </script>            
        </center>
        <center>
        <h1><?php echo $content['subject']; echo ' ver. '. $content['version']; ?> Codes Mastery Test </h1>
        <?php echo '(<b>'.$topic. '</b>)'; ?><br><br>
        <?php
            if($init !== 'end')
            {         
            echo 'Try to answer the question below without looking at the documentation or cheating.';
            }
        ?>
        </center>
    </div>


<div align='center'>
    <div>
        <?php 
                //echo form_open('front/save_lang'); 
                #echo form_open(''); 
                
        ?>
        <table width="100%" border="0">
                <tr>
                    <td>
                        <?php
                        $str = htmlspecialchars_decode($qa_data[0]->question);                
                        
                        $data_question = array(
                                'name'          => 'question',
                                'id'            => 'question',
                                'value'         => $str,
                                'cols'          => '50',
                                'rows'          => '10',
                                'wrap'          => 'off',
                                'style'         => 'width:95%'
                        );

                        if($init !== 'end') {
                            echo form_textarea($data_question);         
                        }
                        ?>                        
                    </td>        
                </tr>
        </table>    
        <center>
            <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <!-- codesmastery-middle -->
            <ins class="adsbygoogle"
                 style="display:inline-block;width:970px;height:90px"
                 data-ad-client="ca-pub-6956881401283026"
                 data-ad-slot="8239432049"></ins>
            <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
            </script>                    
        </center>
            <table width="100%" border="0">
                <tr>
                    <td>
                        <?php
                        
                        $data_coder_answer = array(
                                'name'          => 'coder-answer',
                                'id'            => 'coder-answer',
                                'placeholder'   => 'Write the codes of your answer here.',
                                'cols'          => '50',
                                'rows'          => '18',
                                'wrap'          => 'off',
                                'style'         => 'width:95%'
                        );

                        if($init !== 'end') {
                            echo form_textarea($data_coder_answer);         
                        }
                        ?>
                    </td>
                    <td>
                        <div id="right-answer">
                        <?php
                        #$str = htmlspecialchars_decode($qa_data[0]->answer);                
                        $str = '';
                        
                        $data_right_answer = array(
                                'name'          => '',
                                'id'            => 'right-answer2',
                                'value'         => '',
                                'cols'          => '50',
                                'rows'          => '18',
                                'wrap'          => 'off',
                                'style'         => 'width:95%'
                        );

                        if($init !== 'end') {
                            echo form_textarea($data_right_answer);    
                        }
                        ?>
                        </div>
                    </td>
                </tr>                

                <tr>
                    <td>

                    </td>
                    <td>
                        
                    </td>
                </tr>                                
                <tr>
                        <td align="left" colspan="3">
                            <br>
        <?php 

            $data_done = array(
                    'name'          => 'done',
                    'id'            => 'done',
                    'value'         => 'Done and compare',
            );        

            if($init === 'end')
            {
            ?>
                <br><br>
                <center><h2><?php echo $result_msg; ?></h2></center>

            <?php
            }               
            else
            {
                echo '<center>Press this button below, when you are done answering the question.</center>';
                
                echo '<center>';
                echo form_submit($data_done);
                #echo form_close(); 
                echo '</center>';
            }
        ?>
                        </td>
                </tr>
        </table>    
        <br>
        <center>

        <?php
            if($init !== 'end')
            {            
                echo 'If there is missing character(s) in your codes then your answer is wrong.<br>
                     Pressing the buttons either Yes or No below, will proceed you to the next question.<br>
                    Is your answer corrrect?';
                     
                $data_yes = array(
                        'name'          => 'yes',
                        'id'            => 'yes',
                        'value'         => 'Yes',
                );                        
                
                echo form_open('language/show_qa/'. $topic . $end); 
                echo form_submit($data_yes);
                echo '<input type="submit" name="no" id="no" value="No" />';
                echo form_close();
                
            }
        ?>     
            

        </center>
        <br>
        <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- codesmastery-bottom -->
        <ins class="adsbygoogle"
             style="display:inline-block;width:970px;height:90px"
             data-ad-client="ca-pub-6956881401283026"
             data-ad-slot="9716165245"></ins>
        <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
        <br>
        <table width="100%" border="0">
                <tr>
                    <td>
                        <div id="reference">
                        <?php
                        $data_reference = array(
                                'name'          => 'reference',
                                'id'            => 'reference',
                                'value'         =>  $qa_data[0]->info,
                                'cols'          => '50',
                                'rows'          => '6',
                                'wrap'          => 'off',
                                'style'         => 'width:95%'
                        );

                        echo form_textarea($data_reference);         
                        ?>                        
                        </div>
                    </td>        
                </tr>
        </table>             
    </div>
</div>
<br><br>

<div id="wrapper">
    <div align='center'>
        <div>
            <a href="<?php echo base_url() . 'language/suggestion/'; ?>" target="_blank"><b>Leave Feedback</b></a>        
        </div>
    </div>
</div>

<!-- hidden inline form -->
<div id="inline">
	<form id="contact" name="contact" action="#" method="post">
	</form>
</div>

I tried finding the bug but failed many times…
Help me find the bug.

Thanks in advance.

Which line is line 244?

You’ve posted the original PHP code. The PHP code has dependencies that we cannot access.

Can you please post the generated HTML source code instead?

Here are the generated html codes.

<!doctype html>
<html class="no-js" lang="">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <!-- H5BP CSS -->
    <link rel="stylesheet" href="http://localhost/ci/ci3-codes-mastery3/assets/css/normalize.css">
    <link rel="stylesheet" href="http://localhost/ci/ci3-codes-mastery3/assets/css/main.css">

    <!-- MENU CSS -->
    <link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="http://localhost/ci/ci3-codes-mastery3/assets/menu/style.css">   

    <!-- front_master.css -->
    <link rel="stylesheet" href="http://localhost/ci/ci3-codes-mastery3/assets/css/front_master.css">

    <script type="text/javascript" src="http://gc.kis.scr.kaspersky-labs.com/1B74BD89-2A22-4B93-B451-1C9E1052A0EC/main.js" charset="UTF-8"></script><script src="http://localhost/ci/ci3-codes-mastery3/assets/js/vendor/modernizr-2.8.3.min.js"></script>
    <script src="http://localhost/ci/ci3-codes-mastery3/assets/js/vendor/jquery-1.11.3.min.js"></script>
  
    <style type="text/css">
        #message_box { 
            position: absolute; 
            top: 0; left: 0; 
            z-index: 10; 
            background:#ffc;
            padding:5px;
            border:1px solid #CCCCCC;
            text-align:center; 
            font-weight:bold; 
            width:99%;
        }        
    </style>

</head>

<body>
<!--[if lt IE 8]>
    <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->    
    
<div id="message_box"><img id="close_message" style="float:right;cursor:pointer"  src="http://localhost/ci/ci3-codes-mastery3/assets/img/12-em-cross.png" /><span id="time"></span></div>    

<div id='pagewrap'>
    <div id="header" class="clearfix">
               
<div id="header">
    <img align="right" src="http://localhost/ci/ci3-codes-mastery3/assets/img/beta2.jpg" alt="Beta" height="" width="">
</div>

 

    </div>		

    <div id="msg" class="clearfix">
            Welcome back      </div>	    
    
    <div id="menu">
            <nav class="clearfix">
        <ul class="clearfix">
                <li><a href="http://localhost/ci/ci3-codes-mastery3/front/home/">Home</a></li>
                <li><a href="http://localhost/ci/ci3-codes-mastery3/front/postqa/">Create Q & A</a></li>
                <li><a href="http://localhost/ci/ci3-codes-mastery3/front/yourqa">Your Q & A</a></li>
                <li><a href="http://localhost/ci/ci3-codes-mastery3/language/suggestion/">Suggestion</a></li>
                <li><a href="http://localhost/ci/ci3-codes-mastery3/front/masters/">Masters</a></li>
                <li><a href="http://localhost/ci/ci3-codes-mastery3/front/verifiers/">Verifiers</a></li>
                
        </ul>
        <a href="#" id="pull">Menu</a>
</nav>



    </div>

    <div id="content">
            



    <div id="landingqa">
        <br>
        <center>
            <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <!-- codesmastery-top -->
            <ins class="adsbygoogle"
                 style="display:inline-block;width:970px;height:90px"
                 data-ad-client="ca-pub-6956881401283026"
                 data-ad-slot="6762698841"></ins>
            <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
            </script>            
        </center>
        <center>
        <h1>codeigniter ver. 3 Codes Mastery Test </h1>
        (<b>general</b>)<br><br>
        Try to answer the question below without looking at the documentation or cheating.        </center>
    </div>


<div align='center'>
    <div>
                <table width="100%" border="0">
                <tr>
                    <td>
                        <textarea name="question" cols="50" rows="10" id="question" wrap="off" style="width:95%" >Write a controller called Blog that prints &#039;Hello World!&#039;.</textarea>
                        
                    </td>        
                </tr>
        </table>    
        <center>
            <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <!-- codesmastery-middle -->
            <ins class="adsbygoogle"
                 style="display:inline-block;width:970px;height:90px"
                 data-ad-client="ca-pub-6956881401283026"
                 data-ad-slot="8239432049"></ins>
            <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
            </script>                    
        </center>
            <table width="100%" border="0">
                <tr>
                    <td>
                        <textarea name="coder-answer" cols="50" rows="18" id="coder-answer" placeholder="Write the codes of your answer here." wrap="off" style="width:95%" ></textarea>
                    </td>
                    <td>
                        <div id="right-answer">
                        <textarea cols="50" rows="18" id="right-answer2" wrap="off" style="width:95%" ></textarea>
                        </div>
                    </td>
                </tr>                

                <tr>
                    <td>

                    </td>
                    <td>
                        
                    </td>
                </tr>                                
                <tr>
                        <td align="left" colspan="3">
                            <br>
        <center>Press this button below, when you are done answering the question.</center><center><input type="submit" name="done" value="Done and compare" id="done"  />
</center>                        </td>
                </tr>
        </table>    
        <br>
        <center>

        If there is missing character(s) in your codes then your answer is wrong.<br>
                     Pressing the buttons either Yes or No below, will proceed you to the next question.<br>
                    Is your answer corrrect?<form action="http://localhost/ci/ci3-codes-mastery3/language/show_qa/general" method="post" accept-charset="utf-8">
<input type="hidden" name="token" value="c94f3f6a" style="display:none;" />
<input type="submit" name="yes" value="Yes" id="yes"  />
<input type="submit" name="no" id="no" value="No" /></form>     
            

        </center>
        <br>
        <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- codesmastery-bottom -->
        <ins class="adsbygoogle"
             style="display:inline-block;width:970px;height:90px"
             data-ad-client="ca-pub-6956881401283026"
             data-ad-slot="9716165245"></ins>
        <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
        <br>
        <table width="100%" border="0">
                <tr>
                    <td>
                        <div id="reference">
                        <textarea name="reference" cols="50" rows="6" id="reference" wrap="off" style="width:95%" ></textarea>
                        
                        </div>
                    </td>        
                </tr>
        </table>             
    </div>
</div>
<br><br>

<div id="wrapper">
    <div align='center'>
        <div>
            <a href="http://localhost/ci/ci3-codes-mastery3/language/suggestion/" target="_blank"><b>Leave Feedback</b></a>        
        </div>
    </div>
</div>

<!-- hidden inline form -->
<div id="inline">
	<form id="contact" name="contact" action="#" method="post">
	</form>
</div>

    </div>
    

        
    <br><br>
    <div id="footer">
            <center>
<b>Copyright 2016</b>
</center>

    </div>
</div>
    


    <script src="http://localhost/ci/ci3-codes-mastery3/assets/js/plugins.js"></script>
    <script src="http://localhost/ci/ci3-codes-mastery3/assets/js/main.js"></script>   
    
    <script>
            $(function() {
                    var pull 		= $('#pull');
                            menu 		= $('nav ul');
                            menuHeight	= menu.height();

                    $(pull).on('click', function(e) {
                            e.preventDefault();
                            menu.slideToggle();
                    });

                    $(window).resize(function(){
                    var w = $(window).width();
                    if(w > 320 && menu.is(':hidden')) {
                            menu.removeAttr('style');
                    }
            });
            });
    </script>	
    
   <script>
        var answer = "class Blog extends CI_Controller {

        public function index()
        {
                echo 'Hello World!';
        }
}";
       
        $(function () {
            $("#right-answer2").hide();
            $("#reference").hide();
            
            $("#done").click(function(){
                $("#right-answer2").val(answer).show();
                $("#reference").show();     
                
            });
        });    
    </script>

    <script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-69339113-1', 'auto');
  ga('send', 'pageview');

</script>
   
    
     <script>
        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;
            setInterval(function () {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.text(minutes + ":" + seconds);

                if (--timer <= 0) {
                    $("#no").trigger("click");                    
                    timer = duration;
                }
            }, 1000);
        }

        jQuery(function ($) {
            var minutes = 2;
            var fiveMinutes = 60 * minutes,
                display = $('#time');
            startTimer(fiveMinutes, display);
        });    
    </script>   
    
    <script>
        $(document).delegate('#coder-answer', 'keydown', function(e) { 
          var keyCode = e.keyCode || e.which; 

          if (keyCode === 9) { 
            e.preventDefault(); 
            var start = $(this).get(0).selectionStart;
            var end = $(this).get(0).selectionEnd;

            // set textarea value to: text before caret + tab + text after caret
            $(this).val($(this).val().substring(0, start)
                        + "\t"
                        + $(this).val().substring(end));

            // put caret at right position again
            $(this).get(0).selectionStart = 
            $(this).get(0).selectionEnd = start + 1;
          } 
        });
    </script>
    
    <script>
        var $button_done = $("#done");
        $button_done.prop("disabled", true);

        $("#coder-answer").keyup(function(){
          $button_done.prop("disabled", (this.value === "")? true : false);
        });
        
        var $button_yes = $("#yes");
        $button_yes.prop("disabled", true);

        $("#coder-answer").keyup(function(){
          $button_yes.prop("disabled", (this.value === "")? true : false);
        });        
    </script>
    
    <script>
        window.onload = function () {
            if (typeof history.pushState === "function") {
                history.pushState("jibberish", null, null);
                window.onpopstate = function () {
                    history.pushState('newjibberish', null, null);
                    // Handle the back (or forward) buttons here
                    // Will NOT handle refresh, use onbeforeunload for this.
                };
            }
            else {
                var ignoreHashChange = true;
                window.onhashchange = function () {
                    if (!ignoreHashChange) {
                        ignoreHashChange = true;
                        window.location.hash = Math.random();
                        // Detect and redirect change here
                        // Works in older FF and IE9
                        // * it does mess with your hash symbol (anchor?) pound sign
                        // delimiter on the end of the URL
                    }
                    else {
                        ignoreHashChange = false;   
                    }
                };
            }
        };
    </script>
    
    <script type="text/javascript" language="javascript">
        //  Developed by Roshan Bhattarai 
        //  Visit http://roshanbh.com.np for this script and more.
        //  This notice MUST stay intact for legal use
        $(document).ready(function()
        {
            //scroll the message box to the top offset of browser's scrool bar
            $(window).scroll(function()
            {
                $('#message_box').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});  
            });
        //when the close button at right corner of the message box is clicked 
            $('#close_message').click(function()
            {
                //the messagebox gets scrool down with top property and gets hidden with zero opacity 
                $('#message_box').animate({ top:"+=15px",opacity:0 }, "slow");
            });
        });
     </script> 
</body>
</html>

Thanks in advance

Which line is 244?

1 Like

On genrated html codes.

Below is starting line 243 and 249

        var answer = "class Blog extends CI_Controller {

        public function index()
        {
                echo 'Hello World!';
        }
}";

Thanks in advance.

Actually on generated html codes starting line 243 and 249 was generated because of this codes below.

        var answer = "<?php  echo $ans; ?>";

This codes was under jquery codes.

Here are the complete codes of jquery codes for this.

   <script>
        var answer = "<?php  echo $ans; ?>";
       
        $(function () {
            $("#right-answer2").hide();
            $("#reference").hide();
            
            $("#done").click(function(){
                $("#right-answer2").val(answer).show();
                $("#reference").show();     
                
            });
        });    
    </script>

Thanks in advance.

That will be it. double quotes (and single quotes too) do not wrap across multiple lines.

There are two solutions. One is to replace the newline with a \n symbol instead, and the other is to end the line with a backslash.

The former is usually the preferred solution.

The string values were from php I converted it into javascript.
so this variable will have constantly receiving changing values.
So is there an automatic method in php to solve this?

Thanks in advance.

I guess the answer is nl2br()

I will try.

1 Like

Nope, that’s only if you plan to output HTML code. You are not outputting HTML code.

You just need to replace the newline characters with \n instead. Perhaps using the PHP replace command.

That is partially correct.

The problem is, you are using a textarea for displaying the right-answer, which is going to show the <br> tags.

@cpradio.

Actually I tried nl2br() but did not remove the error message.

So what would be the correct solution?
The reason I use textarea because of the scrolling bar feature of it.

The error is due to you having newline characters in between the double quotes.

Instead of:

var answer = "some stuff
    more stuff
    and more stuff";

You need it to be:

var answer = "some stuff\n    more stuff\n    and more stuff";

@paul

so how to make it one line with \n ?

thanks

It’s too late for me to run up a testing environment tonight, but I reckon that someone in the PHP forum will be able to easily answer that one.

The preg_replace command seems to be the right sort of direction for you to investigate.

Try this:

var answer = "<?php echo implode('\n', preg_split("/(\r\n|\r|\n)/", $ans)); ?>";

preg_split is breaking the answer into individual lines, then it is using implode to take those lines and concatenate them with a literal \n so JavaScript can interpret it.

1 Like

@cpradio

I tried it dude you codes.
But the error did not go away.

thanks for your effort.

Okay will try to experiment in pure php.
perhaps i’ll figure it out.

Provide the new HTML output for that script tag. Something must not be right, as when I tested it, it should have worked.

It should have created an output of

var answer = "class Blog extends CI_Controller {\n\n public function index()\n {\n echo 'Hello World!';\n }\n}";