Q:

Making PhP code executes first before Javascript

<?PHP
//$errorMessage = "";
//$check = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        //===================================================
        //  GET THE QUESTION AND ANSWERS FROM THE FORM
        //===================================================
    $sID = $_POST['studentID'];
    $sID  = htmlspecialchars($sID);
        $firstName = $_POST['firstName'];
        $firstName  = htmlspecialchars($firstName);
        $lastName = $_POST['lastName'];
        $lastName  = htmlspecialchars($lastName);
        $grade = $_POST['grade'];
        $grade  = htmlspecialchars($grade);
        //var_dump($grade);

        //============================================
        //  OPEN A CONNECTION TO THE DATABASE
        //============================================
    $user_name = "root";
    $password = "";
    $database = "surveyTest";
    $server = "127.0.0.1";
    $db_handle = mysql_connect($server, $user_name, $password);
    $db_found = mysql_select_db($database, $db_handle);
    if ($db_found) {
        //============================================
        //  GET THE LAST QUESTION NUMBER
        //============================================
            $SQL = "Select * FROM students WHERE SID='$sID'";
            $result = mysql_query($SQL);
            $db_field = mysql_fetch_assoc($result);
            $studentID = $db_field['SID'];
            var_dump($studentID);
            //=========================================================
            //  Add a student to the students TABLE
            //=========================================================
            $SQL = "INSERT INTO students (SID, fName, lName, Grade) VALUES ('$sID', '$firstName', '$lastName', '$grade')";
            $result = mysql_query($SQL);
            //=============================================================
           //   SET Multiple rows IN THE answers TABLE for each question for a given student.
           //=============================================================
            /*$SQL = "Select * FROM tblquestions";
            $result = mysql_query($SQL);
            $numRows = mysql_num_rows($result); //return number of rows in the table
            for ($i = 1; $i <= $numRows; $i++){
                $qNum = 'q1';
                $SQL = "INSERT INTO answers (QID, A, B, C, D, E, SID) VALUES ('$qNum', 0, 0, 0, 0, 0, '$sID')";
                $question_Number = ltrim($qNum,'q');
                $question_Number++;
                $qNum ='q'.$question_Number;
                $result = mysql_query($SQL);
            }*/
            mysql_close($db_handle);
            print "The student with the following ID ".$sID. " has been added to the database";
        }
    else {
        print "Database NOT Found ";
        mysql_close($db_handle);
    }

}
?>
<html>
<head>
<title>Survey Admin Page</title>
</head>
<body>

<FORM NAME ="setQuestionForm" METHOD ="POST" ACTION ="setStudent.php" id="sStudent">
            <p>Enter student ID: <INPUT TYPE = 'TEXT' Name ='studentID' size="4"></p>
            <p>Enter First Name: <input type="text" name="firstName" size="20"></p>
            <p>Enter Last Name: <input type="text" name="lastName" size="20"></p>
            <p>Select Grade: <select name = "grade">
                <option value = "1">First Grade</option>
                <option value = "2">Second Grade</option>
                <option value = "3">Third Grade</option>
                <option value = "4">Fourth Grade</option>
                <option value = "5">Fifth Grade</option>
                <option value = "6">Sixth Grade</option>
                <option value = "7">Seventh Grade</option>
                <option value = "8">Eighth Grade</option>                           
            </select></p>
            <INPUT TYPE = "submit" Name = "Submit1"  VALUE = "Add Student">
        </FORM>
    <P>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    $(function(){
        if ($('form').length > 0) {
            $('form').submit(function(e){
                var check = "<?php echo $studentID; ?>";
                alert(check);
                if (check != "")
                {
                    alert ("This user already exists");
                    return false;
                }
                else
                {
                    return true;
                }
            });   
        } 
    }) 
</script>
</body>
</html>

The above code is used to add students to a database, and I'm trying to do some form validation to avoid duplicated records. My problem is that I set a php  variable $studentID that verifies whether the database contain the a student with the same ID.
However, when I try to add a duplicated record, it seems like my javascript code executes first and this can be observed by the alert message in the JQuery code that it shows a box of an empty string. Executing the code once more, do the correct thing.
Any help of how I can fix this?

A:

On initial page load:
The process flow looks like this:

Server Side code -> sends data to client -> browser begins rendering and executing JS

On form Submit:

Client Executes code (javascript) -> Sends data to server -> Server gets data and processes

to change the way this works you would want to do an ajax or post form submit and on "success" then execute the above JavaScript.  You can post to the same page or change it to a RESTful service.
Here are examples of AJAX and POST functions from jQuery:
AJAX
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

POST (JS)
$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

Here is the result specifically for you, taking the two snippets above.
JavaScript/jQuery
$(function () {
    if ($('form').length > 0) {
        $('form').submit(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "YOUR-URL",
                data: YOUR - FORM - DATA,
                success: function (result) {
                    //result will contain the xml or JSON result of calling the FORM
                    var check = "<?php echo $studentID; ?>";
                    alert(check);
                    if (check != "") {
                        alert("This user already exists");
                        return false;
                    } else {
                        return true;
                    }
                },
                dataType: "XML-OR-JSON"
            });
        });
    }
})

