Home > Mobile >  My PHP and jQuery code submits blank data to the database
My PHP and jQuery code submits blank data to the database

Time:08-19

I've tried everything to fix it, from changing the id attr names (wasn't sure if there was a collision anywhere) to rewriting it. Not too sure what else to troubleshoot, so I figured I'd ask the stack community.

My HTML code

<input type="hidden" id="quizid" value="Module 1" name="quizid">
<input type="hidden" id="quizby" value="Jordan" name="quizby">
<input type="hidden" id="monescore" value="" name="monescore">

The "monescore" updates at the end of the quiz with JS.

My PHP code

$conn = mysqli_connect("localhost", "root", "testing123", "quiz");

    $quiz_id = $_POST['quizid'];
    $quiz_by = $_POST['quizby'];
    $quiz_score = $_POST['monescore'];
    $addScore = mysqli_prepare($conn, "INSERT INTO quiz_scores (quiz_id, quiz_by, quiz_score) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($addScore, "sss", $quiz_id, $quiz_by, $quiz_score);
    mysqli_stmt_execute($addScore);

    mysqli_stmt_close($addScore);

and finally my jQuery / AJAX code...

var quiz_id = $('#quizid').val();
                var quiz_by = $('#quizby').val();
                var quiz_score = $('#monescore').val();

                $.ajax({
                    type: "POST",
                    url: "handlers/quiz-post.php",
                    data: {
                        quiz_id: quiz_id,
                        quiz_by: quiz_by,
                        quiz_score: quiz_score
                    },
                    cache: false,
                    success: function(data) {
                        alert('success');
                    }
                });

This is what my database shows;

enter image description here

CodePudding user response:

The problem is in the PHP file, when you send the information to the server via Ajax, the parameters have different names than what you receive in php.

for example from ajax, the parameter is called quiz_id but in php you receive it as $_POST['quizid'], you should receive it as $_POST['quiz_id']

CodePudding user response:

The best way to debug this is to check the data values of the quiz_id, quiz_value and quiz_score variables throughout your code.

Step 1: console.log() each of the variables in the jQuery and check if they contain the data.

Step 2: var_dump or print_r them in PHP to see the values and datatypes of each of the variables - the result of the PHP should come as response text on the jQuery.

If the data is available check in the your database data types, length limits and other settings to see if they are satisfied by the variables being passed. If that still doesn't work, I would recommend using PHP Data Objects (PDO) to see if this can send the data successfully.

Another quick reminder, check if the database connection was successful.

  • Related