Question

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?

Was it helpful?

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";

OTHER TIPS

true should be boolean if $doornot is. Additionally, in both PHP and JavaScript String quotes are peeled off when they return a value. Your JavaScript sees another variable, not a String. Try:

<script type="text/javascript">     
  function upvote(){
    var fazer = <?php echo $doornot ?>;
    if(fazer == true){
        window.location = 'http://www.dawnsource.com/forums/register.php';
    }
    else {
      var user = '<?php echo $user; ?>';
      var 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>

Side note:

I do not see a use for your user or id arguments in your upvote function, since you are getting those values from PHP, and only under a condition. Also, you should use the keyword var in JavaScript, unless you want those variables to be global.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top