I have a quiz application which stores user scores to a variable. There is a blueprint object for every user that looks like this:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
New user created like this:
var user1 = new User (lastItem.name);
Then there is event listener for button click, which increments user score. Inside the same event listener function I make AJAX request to store user score to database:
dbtn.addEventListener("click", function() {
question1.currentQuestion++;
if(question1.currentQuestio
n > 3 ) {
container.style = "display: none;"
var finished = document.createElement("h2");
finished.setAttribute("name", "score");
finished.innerHTML = "You scored: " + user1.currentScore;
body.appendChild(finished);
jQuery.ajax({
type:"POST",
url: window.location,
data: { score: user1.currentScore }
}).done(function(data) {
console.log("data sent");
});
}
I get consoled data sent
but database shows no values stored.
Then inside functions.php I just check globally (not inside the function) if $_POST['score]
is empty or not, if empty, echo a notice, otherwise insert into database.
if( empty( $_POST['score'] ) ) { echo "score is null!"; die(); }
if(isset($_POST['score']))
global $wpdb;
$table = 'username';
$dataa = array(
'score' => $_POST['score']
);
$score = $wpdb->insert($table, $dataa);
die();
The problem is that values doesn't get stored, but neither do I get a message score is null!
on the screen. It looks like there is no connection between my script.js file with AJAX request and functions.php code above. I'm not sure if URL
in AJAX request is correct and I pass the data to $_POST[]
correctly.
What I'm doing here wrong? I have managed to get data from DB to JS using ajax already, but I can't make it work when posting from JS to DB.
EDIT: I changed AJAX .done
function to console.log(data)
instead of success message and it consoles out the whole html template for some reason?
Some people suggested me to change AJAX url from window.location
to /wp-admin/admin-ajax.php?
but that returns
jquery.js?ver=1.12.4:4 POST /wp-admin/admin-ajax.php? 404 (Not Found)