How my page works:
- The quiz php page loads and the user generates a score with a function inside
quiz.js. The score is then saved in a variablescoreinsidequiz.js - After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. Pressing the button would send the score to my database with a sql query I have in
sendData.php, without reloading the page.
My button looks like this:
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
And my PHP file being like this:
if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
$score = $_POST['score'];
$numQuiz = $_POST['numQuiz'];
// SQL query and stuff goes here
}
But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. Also, I can see the error pop up inside sendAjax before it loads the PHP file. I've tried adding to the form the attribute action="" but it doesn't work either.
.preventDefault(). Try adding an ID to the button, removeonclickand in js:$('#my-btn').on('click', function(e) { e.preventDefault() /* $.ajax(...) */ })urlis correct? I mean, isn't it 404 error? What do you see in theNetworktab in the Chrome DevTools?