简体   繁体   中英

javascript syntax error, missing “;”

I have a form with potential errors in the form defined in php. I'm used javascript to change the form action depending on whether errors are present or not. I've converted the php error variable, $errors using json_encode so I can use it in javascript. Running the file in Firefox I get the following error in Firebug:

Syntax error: missing ;

before statement var errors = "{"firstnameErr:......etc} , with the pointer at the letter f in firstnameErr. It looks like I have the errors in the json_encode object.

Here is the javascript:

 <script type = "text/javascript">
    function switchFormAction() { 
    var errors = [];                               
    var errors = "<?php echo json_encode($errors); ?>";
    if(!empty(errors)) {
    alert("Please correct these errors");
    }                                        
    else    {
    var element = document.getElementById("regForm");
    element.setAttribute("action", "serraInsertForm.php");
    return true;
    }
    }
    window.onload = function() {
    document.getElementById("regForm").onsubmit = function()
    switchFormAction();
    }
</script>  

Probably something simple but I can't work it out. Javascript and json are new to me. Appreciate any help stackoverflow can offer.

var errors = "<?php echo json_encode($errors); ?>";
             ^---                                ^--

The indicated quotes are not necessary and are in fact causing the problem. json_encode() will produce whatever quotes/brackets are necessary to turn the data in $errors into syntactically valid Javascript. You're producing:

var errors = "{"somekey":"somevalue"}";
             ^--start string
               ^--end string
                ^^^^^^^ undefined variable

All you need is

var errors = <?php echo json_encode($errors); ?>;

Losing the quotes around here ought to do it.

var errors = "<?php echo json_encode($errors); ?>";

Should probably be:

var errors = <?php echo json_encode($errors); ?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM