0

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 http://example.design/wp-admin/admin-ajax.php? 404 (Not Found)

  • I would validate the POST score before trying to insert it into the database, that way you can do something like if( empty( $_POST['score'] ) ) { echo "score is null!"; die(); } which is super helpful for debugging. Also, your code examples are incomplete, please edit your question to complete them. Also can you verify that user1.currentScore actually has a value? Have you considered using the less error prone and easier to debug REST API instead of the ancient admin ajax endpoints? – Tom J Nowell Nov 13 '18 at 21:32
  • But as I know $_POST takes name attributes and I’m passing a variable to it, maybe that’s the problem? – Limpuls Nov 13 '18 at 21:34
  • Not sure what you mean by that? – Tom J Nowell Nov 13 '18 at 21:40
  • Can you pass anything to $_POST[]? Coz when working with forms, if I pas to it anything else than name attribute of the input field, it doesn't work. – Limpuls Nov 13 '18 at 21:41
  • Yes you can, also your check uses isset but what if it is set, but it's set to "null"? Have you actually checked that user1.currentScore is defined, and has a valid value? Again, please edit your question to include the necessary code, not the cut down version. There's an edit link at the bottom of the question just underneath the tags in gray you can use to update your question, there is not enough information at the moment to answer it – Tom J Nowell Nov 13 '18 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.