Javascript和PHP执行if / else语句

I'm trying a simple if/else statement with Javascript & PHP (with jQuery cookie plugin).

My problem: every time this script fires, it executes both IF and ELSE statements. Even when my cookie is set, it creates a new one and adds it into my database. Am I using both languages properly?

Here's what it looks like:

<script type="text/javascript"> 

//check to see if cookie is present
if ($.cookie('uid')) {
    var userCookie = $.cookie('uid');
    alert(userCookie);      

}
else {
    //create cookie and check to see if it is taken
    <?php 
    $success = false;
    while (!$success) {
        $cookie = createUniqueCookie();
        $success = checkIfCookieIsTaken($cookie);
    }       

    //store into database and set into browser
    if ($result = $mysqli->query("INSERT INTO users (cookie) VALUES ('" . $cookie . "')")) {
    ?>
                $.cookie('uid', '<?php echo $cookie ?>', { expires: 730, path: '/' });
                var userCookie = $.cookie('uid');
                alert('new cookie for user is '+ userCookie);
    <?php
    }
    ?>
}

It looks like you are trying to run php and javascript at the same time. That doesn't work like that.

All the PHP is being run on the server. Every bit of it is parsed, and the resulting code is send to the browser. If there is any javascript in there that gets run by the browser, but then the 'evil' is allready done.

You can't just mix client and server code like that :)

PHP is executed on the server. Javascript is executed on the client (browser).

When a request is made to the web server for this script, PHP will ignore everything not in between <?php ?> tags and send the rest to the browser untouched. The browser will then parse/execute the resulting file.

Step through your design again, now with this in mind. You'll see that mixing the languages in the way you're trying to do it is impossible. In your particular case, it appears that all of this should be done server-side.