Search code examples
phpjavascriptfunctionvariablesreferenceerror

javascript ajax uncaught referenceerror function


Im getting the tittle error when im calling this function.

<script type="text/javascript">     
    function upvote(user, id){
        fazer = <?php echo $doornot ?>;
        if( fazer == 'true'){
            window.location = "http://www.dawnsource.com/forums/register.php";
        }else {
            user = <?php echo $user; ?>;
            id = <?php echo $_GET[id]; ?>;
             $.ajax({
             url: 'scripts/upvote.php',
             type: 'post',
             data: 'user='+user+'&id='+id,
            success: function() 
             {
              alert('success, upvote completed ');
          }, error: function()
          {
              alert('something went wrong, rating failed');
          }
        });
        }

    }
</script>

The error is going on:

user = <?php echo $user; ?>;

But its getting me the right value in the echo. Why is this happening?


Solution

  • You're missing quotes around your php data, so you're generating invalid javascript. Remember... whatever PHP is outputting has to be correct in a javascript context.

    <?php
    $foo = 'bar';
    ?>
    
    <script>
    baz = <?php echo $foo ?>;
    </script>
    

    is going to generate

    baz = bar;
    

    and bar will be interpreted as an undefined variable name.

    The proper solution is to simply pass everything through as json from PHP:

     bar = <?php echo json_encode($foo); ?>;
    

    which will ALWAYS produce valid javascript, no matter what's in $foo. and produces

    baz = "bar";