3
<?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?

11
  • Try running your jQuery code inside $(window).load()? Commented Jul 8, 2013 at 17:34
  • 3
    The problem is that your php code runs after a POST. Commented Jul 8, 2013 at 17:35
  • 1
    @CollinHenderson: $(function(){ /*...*/ }); is jQuery's way of executing when the document is ready. Commented Jul 8, 2013 at 17:36
  • @Travesty3 AFAIK $(function(){ /*...*/ }); is equivalent to $(document).ready(), no? AKA it runs when the DOM is ready, but not necessarily when the page is fully loaded (which $(window).load() does) Commented Jul 8, 2013 at 17:38
  • Any ideas then?, Any other method of setting precedence? Commented Jul 8, 2013 at 17:38

1 Answer 1

5

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"
            });
        });
    }
})
Sign up to request clarification or add additional context in comments.

9 Comments

you are saying that I should use either one of them. Where should I insert this code?
in your $('form').submit(function(e){ e.preventDefault(); --INSERT CODE HERE!!! }
the above code doesn't work. It just allow me to add duplicated records if the rest of the fields are different (It doesn't really add to the database) but, it displays nothing for me.
The above code is still just pseudo code you will have to make it POST the proper data. And then the URL to your Webpage or RESTful service
I still don't understand this code. However, I omitted all the javascript from my file and used php code instead for validation. I never used AJAX before, and that's why I'm struggling to understand this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.