-4

I wanted to store the value "totalscore" from my JavaScript code to my database. I tried using ajax call but something is not working, I have not used ajax before.

In the following JavaScript code, I display the value of score which i have found to the html element.

JavaScript code:

  if (matches==8){
            var totalscore = calcScore();
            document.getElementById("score").innerHTML=totalscore;
          }

I want to save the value of totalscore in my users database when the submit button is clicked. So i tried something like :

   $("#sendscore").on("click",function(){

   gamescore= document.getElementById('score').innerHTML;
   $.ajax({
   type:'POST',
   url: 'score-processor.php',
   data:{
      gamescore: gamescore,
    }
   })
  });

the php code :

<?php
  session_start();
  $db = mysqli_connect('localhost', 'root', '', 'registration');
  if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password_1']);

  if (empty($username)) {
   array_push($errors, "Username is required");
  }
  if (empty($password)) {
   array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
    $_SESSION['username'] = $username;
     header('location: profile.php');
    }
    else {
    array_push($errors, "Wrong username/password combination");
   }
 }
}
   if(isset($_POST['gamescore'])){
   $fetch = "SELECT id FROM users WHERE username='$username'";
   $fetchid =mysqli_query($db, $fetch);
   while ($row=mysqli_fetch_array($fetchid)){
   $id = $row['id'];
   $gamescore= $_POST['gamescore'];
   $updatescore= "INSERT INTO users(id, score)VALUES('$id','$gamescore') ON DUPLICATE KEY UPDATE score='$gamescore'";
   mysqli_query($db, $updatescore);
   }
   }

In my html :

 <?php session_start();?>

 <body> 
 <p>Your score: <span id=score></p>
 <button id="sendscore" class="Go-on">Submit</button>

the database table has columns , id, username, email, password and score.

the value for columns id, username, email and password are collected during login/register.

The game runs smoothly and presents the score but when I click the submit button which on clicked should add the value to the table, but nothing happens, no errors in the log and the value is not added to the table.

  • 3
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 27 '19 at 13:26
  • Post data should be stored in the data property of ajax options. It doesn't have a gamescore property. – Mark Baijens Aug 27 '19 at 13:28
  • After you fix your Sql injection vulnerability... you have not defined anywhere your $id and $username variable in the update script. The query will fail for that – Lelio Faieta Aug 27 '19 at 13:28
  • Please refer to this other post addressing AJAX calls https://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – Luke Pinto Aug 27 '19 at 13:29
  • See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php for more on how to prevent SQL injection attacks. – Yvonne Aburrow Aug 27 '19 at 13:31
  • I think u store json to database better then variable store to database – dılo sürücü Aug 27 '19 at 13:39
  • @dılosürücü — That sentence doesn't really make sense. I'm really not sure what you are getting at, but there's no reason to involve JSON in this problem at all. – Quentin Aug 27 '19 at 14:20
  • @Quentin can you help me with the problem , that i have commented in your response. Thank you for your explanations. –  Aug 27 '19 at 14:49
  • **Danger**: You are using [an unsuitable hashing algorithm](http://php.net/manual/en/faq.passwords.php) and need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of your users' passwords. – Quentin Aug 27 '19 at 15:57
  • @Quentin okay, i will change it with better algorithm –  Aug 27 '19 at 15:58

1 Answers1

1

Problem 1

gamescore= document.getElementById('score');

This is an HTML element, not the value of it.

You need to read the .innerHTML just like you wrote to it earlier


Problem 2

gamescore: gamescore

jQuery.ajax doesn't have a gamescore option. So this is meaningless.

You need to pass data.

data: {
    gamescore: gamescore
}

Problem 3

contentType: false,

This stops jQuery overriding the content-type when you pass a FormData object to generate a multipart request (which is useful for uploading files).

You aren't doing that, so contentType: false will break the normal allocation of the correct Content-Type header.

Remove that


Problem 4

processData: false

You need the data to be processed. The object you pass to data needs encoding into the HTML request.

Remove that.


Problem 5

  $updatescore= "UPDATE users SET(username='$username', score='$gamescore') WHERE (id='$id')";

You failed to define $username or $id.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I made the changes that you suggested and edited the code above, but still same problem , i cannot add the score to the table. The $username and $id are already present in the table, so i defined something like what i presented it the above code. can you tell me where i went wrong. Your explanation was very clear, thanks for that. –  Aug 27 '19 at 14:06
  • @vigneshu — Where do you expect `$_POST['username']` and `$_POST['$id']` to come from? They aren't in your Ajax `data`. – Quentin Aug 27 '19 at 14:11
  • thank you for that explanation, can you help me with an alternative to save the score data to the existing table with username and id. I already have the username and id, how can I link it to update this score data –  Aug 27 '19 at 14:34
  • "I already have the username and id" — It doesn't look like you do. – Quentin Aug 27 '19 at 14:50
  • I get the username and id in another php file for login and register system –  Aug 27 '19 at 14:53
  • okay , now i understand. I will put them in same file and check. –  Aug 27 '19 at 14:55
  • I edited the above code in the php. I tried using the php code for the ajax call along with the code where i get the username and session. but this time, the success alert pops up but the data is still not added to the table. Is there anything wrong with my data property in my ajax or something wrong with my sql query. Thanks for your kind assistance –  Aug 27 '19 at 15:55
  • `$_POST['username']` and `$_POST['password_1']` are still going to be empty because you aren't POSTing those fields. – Quentin Aug 27 '19 at 15:57
  • can i send you the full code through any means, so it will better to explain me –  Aug 27 '19 at 16:00
  • I get the values from username and password from login page. the condition If($_POST['login_user']) checks for login and starts the session. –  Aug 27 '19 at 16:03
  • `$_POST['username']`tries to get the value from **the current request** (where it doesn't exist) not some earlier request for a different URL. – Quentin Aug 27 '19 at 16:04
  • i edited the code above with the suggestion u gave me yesterday. Now I m able to insert the score in the table but, it creates a new row and saves the score. I want it to save it the score with reference to the user id. could you tell me where i went wrong. –  Aug 28 '19 at 16:16
  • You did an INSERT and not an UPDATE (and no, it isn't as simple as replacing the word INSERT with UPDATE, please read an introductory SQL tutorial). This is *well* outside the scope of the original question which was really too broad to begin with) – Quentin Aug 28 '19 at 16:17